From d9bbb830b31584fba3496998f4e593b864c922e7 Mon Sep 17 00:00:00 2001 From: Philoul Date: Wed, 6 Sep 2023 23:35:04 +0200 Subject: [PATCH 01/34] Wear Add preferenceMenuActivity --- wear/src/main/AndroidManifest.xml | 4 + .../androidaps/di/WearActivitiesModule.kt | 2 + .../WatchfaceConfigurationActivity.kt | 10 +- .../interaction/menus/MainMenuActivity.kt | 2 +- .../menus/PreferenceMenuActivity.kt | 49 +++++++++ wear/src/main/res/values/strings.xml | 6 + .../main/res/xml/complication_preferences.xml | 21 ++++ ...references.xml => display_preferences.xml} | 103 ------------------ wear/src/main/res/xml/graph_preferences.xml | 29 +++++ .../main/res/xml/interface_preferences.xml | 51 +++++++++ wear/src/main/res/xml/others_preferences.xml | 20 ++++ 11 files changed, 187 insertions(+), 110 deletions(-) create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt create mode 100644 wear/src/main/res/xml/complication_preferences.xml rename wear/src/main/res/xml/{preferences.xml => display_preferences.xml} (53%) create mode 100644 wear/src/main/res/xml/graph_preferences.xml create mode 100644 wear/src/main/res/xml/interface_preferences.xml create mode 100644 wear/src/main/res/xml/others_preferences.xml diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index ab50e950d1..837f323a78 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -602,6 +602,10 @@ android:name=".interaction.menus.StatusMenuActivity" android:exported="true" android:label="@string/menu_status" /> + startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_settings) -> startActivity(Intent(this, PreferenceMenuActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) getString(R.string.menu_resync) -> rxBus.send(EventWearToMobile(ActionResendData("Re-Sync"))) getString(R.string.status_profile_switch) -> rxBus.send(EventWearToMobile(EventData.ActionProfileSwitchSendInitialData(System.currentTimeMillis()))) getString(R.string.menu_tempt) -> startActivity(Intent(this, TempTargetActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt new file mode 100644 index 0000000000..c0e19ad06f --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.interaction.menus + +import android.content.Intent +import android.os.Bundle +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interaction.WatchfaceConfigurationActivity +import info.nightscout.androidaps.interaction.utils.MenuListActivity + +class PreferenceMenuActivity : MenuListActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setTitle(R.string.menu_settings) + super.onCreate(savedInstanceState) + } + + override fun provideElements(): List = + ArrayList().apply { + add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_display_settings))) + add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_graph_settings))) + add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_interface_settings))) + add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_complication_settings))) + add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_others_settings))) + } + + override fun doAction(position: String) { + when (position) { + getString(R.string.pref_display_settings) -> startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtra(getString(R.string.key_preference_id), R.xml.display_preferences) + }) + getString(R.string.pref_graph_settings) -> startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtra(getString(R.string.key_preference_id), R.xml.graph_preferences) + }) + getString(R.string.pref_interface_settings) -> startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtra(getString(R.string.key_preference_id), R.xml.interface_preferences) + }) + getString(R.string.pref_complication_settings) -> startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtra(getString(R.string.key_preference_id), R.xml.complication_preferences) + }) + getString(R.string.pref_others_settings) -> startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtra(getString(R.string.key_preference_id), R.xml.others_preferences) + }) + } + } +} diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 02d4feb90a..81b770c83f 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -24,6 +24,11 @@ Vibrate on Bolus Units for Actions U + Display + Graph + Interface + Others + Complication Show Date Show IOB Show detailed IOB @@ -175,6 +180,7 @@ No config available Wear controls disabled No data available + preference_id QuickWizard wearcontrol units_mgdl diff --git a/wear/src/main/res/xml/complication_preferences.xml b/wear/src/main/res/xml/complication_preferences.xml new file mode 100644 index 0000000000..c69586c648 --- /dev/null +++ b/wear/src/main/res/xml/complication_preferences.xml @@ -0,0 +1,21 @@ + + + + + + + + diff --git a/wear/src/main/res/xml/preferences.xml b/wear/src/main/res/xml/display_preferences.xml similarity index 53% rename from wear/src/main/res/xml/preferences.xml rename to wear/src/main/res/xml/display_preferences.xml index cd6bfbb80b..608b3cc8bb 100644 --- a/wear/src/main/res/xml/preferences.xml +++ b/wear/src/main/res/xml/display_preferences.xml @@ -110,101 +110,6 @@ app:wear_iconOff="@drawable/settings_off" app:wear_iconOn="@drawable/settings_on" /> - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/wear/src/main/res/xml/graph_preferences.xml b/wear/src/main/res/xml/graph_preferences.xml new file mode 100644 index 0000000000..2ea1779240 --- /dev/null +++ b/wear/src/main/res/xml/graph_preferences.xml @@ -0,0 +1,29 @@ + + + + + + + + + + diff --git a/wear/src/main/res/xml/interface_preferences.xml b/wear/src/main/res/xml/interface_preferences.xml new file mode 100644 index 0000000000..b2bdc24964 --- /dev/null +++ b/wear/src/main/res/xml/interface_preferences.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + diff --git a/wear/src/main/res/xml/others_preferences.xml b/wear/src/main/res/xml/others_preferences.xml new file mode 100644 index 0000000000..381cb5fd10 --- /dev/null +++ b/wear/src/main/res/xml/others_preferences.xml @@ -0,0 +1,20 @@ + + + + + + + From 6059a62b944b88b51cd840581d5995f22e9c0e2f Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Wed, 6 Sep 2023 21:04:44 -0700 Subject: [PATCH 02/34] Replaces assertTrue with truth matchers in DateUtilTest Issue #2745 --- .../info/nightscout/core/utils/DateUtilTest.kt | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt index 7dc59fdb5e..6f89532ac1 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt @@ -1,6 +1,7 @@ package info.nightscout.core.utils import android.content.Context +import com.google.common.truth.Truth.assertThat import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -40,7 +41,7 @@ class DateUtilTest : TestBase() { } @Test fun dateStringTest() { - Assertions.assertTrue(DateUtil(context).dateString(1513902750000L).contains("22")) + assertThat(DateUtil(context).dateString(1513902750000L)).contains("22") } @Test fun timeStringTest() { @@ -48,15 +49,15 @@ class DateUtilTest : TestBase() { } @Test fun dateAndTimeStringTest() { - Assertions.assertTrue(DateUtil(context).dateAndTimeString(1513902750000L).contains("22")) - Assertions.assertTrue(DateUtil(context).dateAndTimeString(1513902750000L).contains("32")) + assertThat(DateUtil(context).dateAndTimeString(1513902750000L)).contains("22") + assertThat(DateUtil(context).dateAndTimeString(1513902750000L)).contains("32") } @Test fun dateAndTimeRangeStringTest() { - Assertions.assertTrue(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22")) - Assertions.assertTrue(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32")) - Assertions.assertTrue(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22")) - Assertions.assertTrue(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32")) + assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("22") + assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("32") + assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("22") + assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("32") } /* @@ -69,4 +70,4 @@ class DateUtilTest : TestBase() { `when`(rh.gs(info.nightscout.shared.R.string.shorthour)).thenReturn("h") Assertions.assertEquals("(1h 1')", DateUtil(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), rh)) } -} \ No newline at end of file +} From 3f8488b935e487f2283b739ff7e3111f2ec1b7b6 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Wed, 6 Sep 2023 21:19:27 -0700 Subject: [PATCH 03/34] Adds @BeforeAll to set default timezone in DateUtilTest Fixes #2747 --- .../nightscout/core/utils/DateUtilTest.kt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt index 6f89532ac1..e8707962c1 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt @@ -8,15 +8,37 @@ import info.nightscout.shared.utils.T import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.AfterAll import org.mockito.Mock import org.mockito.Mockito.`when` import java.util.Date +import java.util.SimpleTimeZone +import java.util.TimeZone class DateUtilTest : TestBase() { @Mock lateinit var context: Context @Mock lateinit var rh: ResourceHelper + companion object { + + private lateinit var savedTimeZone: TimeZone + + @BeforeAll + @JvmStatic + fun setDefaultTimezoneUtc() { + savedTimeZone = TimeZone.getDefault() + TimeZone.setDefault(SimpleTimeZone(0, "UTC")) + } + + @AfterAll + @JvmStatic + fun restoreDefaultTimezone() { + TimeZone.setDefault(savedTimeZone) + } + } + @Test fun fromISODateStringTest() { Assertions.assertEquals(1511124634417L, DateUtil(context).fromISODateString("2017-11-19T22:50:34.417+0200")) From 572e5b6b9aa9e6c23a38ba839c2ca0c4a511b7d9 Mon Sep 17 00:00:00 2001 From: Philoul Date: Thu, 7 Sep 2023 19:41:49 +0200 Subject: [PATCH 04/34] Wear Update Icons for menu --- _docs/icons/ic_complication.svg | 16 ++++ _docs/icons/ic_display.svg | 86 +++++++++++++++++++ _docs/icons/ic_graph.svg | 82 ++++++++++++++++++ _docs/icons/ic_interface.svg | 37 ++++++++ _docs/icons/ic_others.svg | 31 +++++++ _docs/icons/ic_profile.svg | 14 +++ _docs/icons/ic_status.svg | 19 ++++ .../interaction/menus/MainMenuActivity.kt | 2 +- .../menus/PreferenceMenuActivity.kt | 10 +-- .../src/main/res/drawable/ic_complication.xml | 9 ++ wear/src/main/res/drawable/ic_display.xml | 51 +++++++++++ wear/src/main/res/drawable/ic_graph.xml | 26 ++++++ wear/src/main/res/drawable/ic_interface.xml | 16 ++++ wear/src/main/res/drawable/ic_others.xml | 7 ++ wear/src/main/res/drawable/ic_profile.xml | 5 ++ wear/src/main/res/drawable/ic_status.xml | 18 ++-- wear/src/main/res/xml/others_preferences.xml | 16 ++-- 17 files changed, 425 insertions(+), 20 deletions(-) create mode 100644 _docs/icons/ic_complication.svg create mode 100644 _docs/icons/ic_display.svg create mode 100644 _docs/icons/ic_graph.svg create mode 100644 _docs/icons/ic_interface.svg create mode 100644 _docs/icons/ic_others.svg create mode 100644 _docs/icons/ic_profile.svg create mode 100644 _docs/icons/ic_status.svg create mode 100644 wear/src/main/res/drawable/ic_complication.xml create mode 100644 wear/src/main/res/drawable/ic_display.xml create mode 100644 wear/src/main/res/drawable/ic_graph.xml create mode 100644 wear/src/main/res/drawable/ic_interface.xml create mode 100644 wear/src/main/res/drawable/ic_others.xml create mode 100644 wear/src/main/res/drawable/ic_profile.xml diff --git a/_docs/icons/ic_complication.svg b/_docs/icons/ic_complication.svg new file mode 100644 index 0000000000..50d44cf896 --- /dev/null +++ b/_docs/icons/ic_complication.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + diff --git a/_docs/icons/ic_display.svg b/_docs/icons/ic_display.svg new file mode 100644 index 0000000000..b7148cb224 --- /dev/null +++ b/_docs/icons/ic_display.svg @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_docs/icons/ic_graph.svg b/_docs/icons/ic_graph.svg new file mode 100644 index 0000000000..1f37dc82cf --- /dev/null +++ b/_docs/icons/ic_graph.svg @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_docs/icons/ic_interface.svg b/_docs/icons/ic_interface.svg new file mode 100644 index 0000000000..e41c38d0eb --- /dev/null +++ b/_docs/icons/ic_interface.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_docs/icons/ic_others.svg b/_docs/icons/ic_others.svg new file mode 100644 index 0000000000..bc5efd650d --- /dev/null +++ b/_docs/icons/ic_others.svg @@ -0,0 +1,31 @@ + + + + + + + + + + + diff --git a/_docs/icons/ic_profile.svg b/_docs/icons/ic_profile.svg new file mode 100644 index 0000000000..c9caf6be94 --- /dev/null +++ b/_docs/icons/ic_profile.svg @@ -0,0 +1,14 @@ + + + + + + + diff --git a/_docs/icons/ic_status.svg b/_docs/icons/ic_status.svg new file mode 100644 index 0000000000..3db1defbba --- /dev/null +++ b/_docs/icons/ic_status.svg @@ -0,0 +1,19 @@ + + + + + + + + + diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt index 88eec11e1e..da9f97097d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt @@ -32,7 +32,7 @@ class MainMenuActivity : MenuListActivity() { add(MenuItem(R.drawable.ic_e_carbs, getString(R.string.menu_ecarb))) add(MenuItem(R.drawable.ic_treatment, getString(R.string.menu_treatment))) add(MenuItem(R.drawable.ic_temptarget, getString(R.string.menu_tempt))) - add(MenuItem(R.drawable.ic_status, getString(R.string.status_profile_switch))) + add(MenuItem(R.drawable.ic_profile, getString(R.string.status_profile_switch))) add(MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))) add(MenuItem(R.drawable.ic_status, getString(R.string.menu_status))) if (sp.getBoolean(R.string.key_prime_fill, false)) diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt index c0e19ad06f..8607645d06 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/PreferenceMenuActivity.kt @@ -15,11 +15,11 @@ class PreferenceMenuActivity : MenuListActivity() { override fun provideElements(): List = ArrayList().apply { - add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_display_settings))) - add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_graph_settings))) - add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_interface_settings))) - add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_complication_settings))) - add(MenuItem(R.drawable.ic_settings, getString(R.string.pref_others_settings))) + add(MenuItem(R.drawable.ic_display, getString(R.string.pref_display_settings))) + add(MenuItem(R.drawable.ic_graph, getString(R.string.pref_graph_settings))) + add(MenuItem(R.drawable.ic_interface, getString(R.string.pref_interface_settings))) + add(MenuItem(R.drawable.ic_complication, getString(R.string.pref_complication_settings))) + add(MenuItem(R.drawable.ic_others, getString(R.string.pref_others_settings))) } override fun doAction(position: String) { diff --git a/wear/src/main/res/drawable/ic_complication.xml b/wear/src/main/res/drawable/ic_complication.xml new file mode 100644 index 0000000000..d876ada581 --- /dev/null +++ b/wear/src/main/res/drawable/ic_complication.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/wear/src/main/res/drawable/ic_display.xml b/wear/src/main/res/drawable/ic_display.xml new file mode 100644 index 0000000000..69f4e3dae2 --- /dev/null +++ b/wear/src/main/res/drawable/ic_display.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + diff --git a/wear/src/main/res/drawable/ic_graph.xml b/wear/src/main/res/drawable/ic_graph.xml new file mode 100644 index 0000000000..27daa79221 --- /dev/null +++ b/wear/src/main/res/drawable/ic_graph.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/wear/src/main/res/drawable/ic_interface.xml b/wear/src/main/res/drawable/ic_interface.xml new file mode 100644 index 0000000000..55553696d5 --- /dev/null +++ b/wear/src/main/res/drawable/ic_interface.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + diff --git a/wear/src/main/res/drawable/ic_others.xml b/wear/src/main/res/drawable/ic_others.xml new file mode 100644 index 0000000000..efdf7689f9 --- /dev/null +++ b/wear/src/main/res/drawable/ic_others.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/wear/src/main/res/drawable/ic_profile.xml b/wear/src/main/res/drawable/ic_profile.xml new file mode 100644 index 0000000000..62c72e746f --- /dev/null +++ b/wear/src/main/res/drawable/ic_profile.xml @@ -0,0 +1,5 @@ + + + + diff --git a/wear/src/main/res/drawable/ic_status.xml b/wear/src/main/res/drawable/ic_status.xml index 53cfc991f7..12a0c820fc 100644 --- a/wear/src/main/res/drawable/ic_status.xml +++ b/wear/src/main/res/drawable/ic_status.xml @@ -1,9 +1,15 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + android:pathData="M12,12m-12,0a12,12 0,1 1,24 0a12,12 0,1 1,-24 0" + android:fillColor="@android:color/white"/> + + diff --git a/wear/src/main/res/xml/others_preferences.xml b/wear/src/main/res/xml/others_preferences.xml index 381cb5fd10..64d8b2d8fb 100644 --- a/wear/src/main/res/xml/others_preferences.xml +++ b/wear/src/main/res/xml/others_preferences.xml @@ -2,14 +2,6 @@ - - + + From 27110b097ede4a631a0116226bc2808070c8f7a4 Mon Sep 17 00:00:00 2001 From: Philoul Date: Thu, 7 Sep 2023 22:26:29 +0200 Subject: [PATCH 05/34] Wear Improve graph icon --- _docs/icons/ic_graph.svg | 77 ++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/_docs/icons/ic_graph.svg b/_docs/icons/ic_graph.svg index 1f37dc82cf..169910eb8c 100644 --- a/_docs/icons/ic_graph.svg +++ b/_docs/icons/ic_graph.svg @@ -5,10 +5,11 @@ width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve"> - - - - + + + + + - - - - - - - - - - + + + + + + + @@ -69,14 +62,20 @@ c0.522,0.077,1.114,0.164,1.464,0.078c0.277-0.069,0.468-0.303,0.652-0.529c0.123-0.149,0.238-0.291,0.366-0.368 c0.66-0.401,1.201-0.824,1.773-1.273c0.286-0.223,0.576-0.45,0.886-0.678c0.529-0.388,1.251-0.466,1.95-0.541 c0.646-0.069,1.314-0.141,1.853-0.456c1.377-0.805,2.205-0.816,3.847-0.448l0.063-0.276C15.694,8.494,14.823,8.509,13.364,9.36z"/> - + + From 82681b5b126ebea8dd75bae811e74a3bfa179f31 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 7 Sep 2023 23:59:35 +0200 Subject: [PATCH 06/34] simplify core:validators dependencies --- .../sharedtests/TestBaseWithProfile.kt | 10 ++ .../info/nightscout/interfaces/GlucoseUnit.kt | 17 ++ .../interfaces/utils/DecimalFormatter.kt | 21 +++ .../shared/interfaces/ProfileUtil.kt | 146 ++++++++++++++++++ .../activities/HistoryBrowserData.kt | 10 +- .../activities/MyPreferenceFragment.kt | 9 +- .../constraints/ConstraintsCheckerTest.kt | 46 ++---- .../plugins/safety/SafetyPluginTest.kt | 2 +- .../nightscout/pump/PumpEnactResultTest.kt | 10 +- .../core/graph/data/BolusDataPoint.kt | 5 +- .../core/graph/data/ExtendedBolusDataPoint.kt | 5 +- .../core/graph/data/GlucoseValueDataPoint.kt | 15 +- .../core/graph/data/TherapyEventDataPoint.kt | 22 +-- .../info/nightscout/interfaces/GlucoseUnit.kt | 12 -- .../nightscout/interfaces/profile/Profile.kt | 60 ------- .../nightscout/interfaces/pump/PumpSync.kt | 10 +- .../nightscout/interfaces/stats/DexcomTIR.kt | 6 +- .../interfaces/utils/DecimalFormatter.kt | 29 ---- .../core/extensions/ExtendedBolusExtension.kt | 8 +- .../core/extensions/GlucoseValueExtension.kt | 9 -- .../core/extensions/ProfileSwitchExtension.kt | 4 +- .../extensions/TemporaryBasalExtension.kt | 12 +- .../extensions/TemporaryTargetExtension.kt | 18 +-- .../nightscout/core/iob/CobInfoExtension.kt | 10 +- .../core/iob/GlucoseStatusExtension.kt | 10 +- .../nightscout/core/profile/ProfileSealed.kt | 44 ++++-- .../core/pump/PumpEnactResultExtension.kt | 4 +- .../nightscout/core/wizard/BolusWizard.kt | 79 ++++++---- .../info/nightscout/core/data/ProfileTest.kt | 14 -- .../core/utils/DecimalFormatterTest.kt | 28 ---- core/validators/build.gradle | 1 - .../validators/DefaultEditTextValidator.kt | 19 ++- .../ValidatingEditTextPreference.kt | 9 +- .../validators/validators/BgRangeValidator.kt | 7 +- .../implementation/DefaultValueHelperImpl.kt | 21 ++- .../implementation/di/ImplementationModule.kt | 7 + .../iob/GlucoseStatusProviderImpl.kt | 6 +- .../overview/OverviewDataImpl.kt | 10 +- .../implementation/profile/ProfileUtilImpl.kt | 72 +++++++++ .../queue/CommandQueueImplementation.kt | 8 +- .../stats/DexcomTirCalculatorImpl.kt | 8 +- .../implementation/stats/DexcomTirImpl.kt | 29 ++-- .../implementation/stats/TirCalculatorImpl.kt | 11 +- .../UserEntryPresentationHelperImpl.kt | 30 ++-- .../utils/DecimalFormatterImpl.kt | 33 ++++ .../implementation/iob/GlucoseStatusTest.kt | 18 +-- .../overview/OverviewDataImplTest.kt | 16 +- .../profile/ProfileUtilImplTest.kt | 47 ++++++ .../queue/CommandQueueImplementationTest.kt | 10 +- .../implementation/queue/QueueThreadTest.kt | 2 +- .../utils/DecimalFormatterTest.kt | 41 +++++ .../implementation/wizard/BolusWizardTest.kt | 5 +- .../pump/insight/LocalInsightFragment.java | 11 +- .../nightscout/plugins/aps/APSResultObject.kt | 31 ++-- .../plugins/aps/loop/LoopFragment.kt | 12 +- .../DetermineBasalAdapterSMBDynamicISFJS.kt | 4 +- .../general/autotune/AutotuneFragment.kt | 5 +- .../general/autotune/data/ATProfile.kt | 8 +- .../general/autotune/AutotuneCoreTest.kt | 5 +- .../actions/ActionStartTempTarget.kt | 9 +- .../nightscout/automation/triggers/Trigger.kt | 2 + .../automation/triggers/TriggerBg.kt | 3 +- .../automation/triggers/TriggerDelta.kt | 3 +- .../triggers/TriggerTempTargetValue.kt | 3 +- .../automation/actions/ActionsTestBase.kt | 1 + .../automation/triggers/TriggerTestBase.kt | 3 +- .../elements/SWEditNumberWithUnits.kt | 11 +- .../constraints/safety/SafetyPlugin.kt | 25 +-- .../general/actions/ActionsFragment.kt | 6 +- .../general/overview/OverviewFragment.kt | 29 ++-- .../general/overview/ui/StatusLightHandler.kt | 9 +- .../PersistentNotificationPlugin.kt | 37 +++-- .../smsCommunicator/SmsCommunicatorPlugin.kt | 41 ++--- .../wear/wearintegration/DataHandlerMobile.kt | 57 +++---- .../IobCobCalculatorPlugin.kt | 5 +- .../plugins/profile/ProfileFragment.kt | 18 ++- .../plugins/profile/ProfilePlugin.kt | 13 +- .../extensions/GlucoseValueExtensionKtTest.kt | 7 - .../TemporaryTargetExtensionKtTest.kt | 8 +- .../SmsCommunicatorPluginTest.kt | 8 +- .../nightscout/source/BGSourceFragment.kt | 7 +- .../info/nightscout/source/DexcomPlugin.kt | 5 +- .../dataBroadcaster/DataBroadcastPlugin.kt | 7 +- .../plugins/sync/nsclient/NSClientPlugin.kt | 22 +-- .../BolusCalculatorResultExtension.kt | 9 +- .../extensions/ProfileSwitchExtension.kt | 5 +- .../extensions/TemporaryTargetExtension.kt | 16 +- .../workers/NSClientAddUpdateWorker.kt | 4 +- .../sync/nsclientV3/NSClientV3Plugin.kt | 6 +- .../extensions/ProfileSwitchExtension.kt | 5 +- .../plugins/sync/tidepool/comm/UploadChunk.kt | 8 +- .../tidepool/elements/BloodGlucoseElement.kt | 16 +- .../sync/tidepool/elements/ProfileElement.kt | 15 +- .../plugins/sync/xdrip/XdripPlugin.kt | 26 ++-- .../DataBroadcastPluginTest.kt | 2 +- .../sync/nsclientV3/NSClientV3PluginTest.kt | 2 +- .../ProfileSwitchExtensionKtTest.kt | 4 +- .../nsclientV3/workers/LoadBgWorkerTest.kt | 6 +- .../pump/combov2/AAPSPumpStateStore.kt | 3 - .../nightscout/pump/combov2/ComboV2Plugin.kt | 7 +- .../nightscout/pump/combov2}/Delegates.kt | 3 +- .../info/nightscout/pump/dana/DanaPump.kt | 6 +- .../dana/activities/DanaHistoryActivity.kt | 15 +- .../info/nightscout/pump/dana/DanaPumpTest.kt | 2 +- .../danaRKorean/DanaRKoreanPlugin.kt | 22 ++- .../androidaps/danaRv2/DanaRv2Plugin.java | 6 +- .../androidaps/danar/AbstractDanaRPlugin.java | 15 +- .../androidaps/danar/DanaRPlugin.java | 6 +- .../nightscout/pump/danaR/DanaRPluginTest.kt | 4 +- .../pump/danaR/comm/DanaRTestBase.kt | 19 +-- .../pump/danaRKorean/DanaRKoreanPluginTest.kt | 4 +- .../pump/danaRv2/DanaRv2PluginTest.kt | 4 +- .../nightscout/pump/danars/DanaRSPlugin.kt | 9 +- .../comm/DanaRSPacketBolusSet24CIRCFArray.kt | 4 +- .../pump/danars/DanaRSPluginTest.kt | 3 +- .../nightscout/pump/danars/DanaRSTestBase.kt | 2 +- .../DanaRsPacketBolusSetStepBolusStartTest.kt | 3 +- ...naRsPacketNotifyDeliveryRateDisplayTest.kt | 3 +- .../pump/diaconn/DiaconnG8Plugin.kt | 9 +- .../nightscout/pump/diaconn/DiaconnG8Pump.kt | 7 +- .../activities/DiaconnG8HistoryActivity.kt | 18 +-- pump/eopatch/build.gradle | 1 - .../pump/medtronic/MedtronicPumpPlugin.kt | 7 +- .../nightscout/pump/medtrum/MedtrumPlugin.kt | 9 +- .../omnipod/dash/OmnipodDashPumpPlugin.kt | 12 +- pump/omnipod-eros/build.gradle | 1 + .../omnipod/eros/OmnipodErosPumpPlugin.java | 13 +- .../omnipod/eros/OmnipodErosPumpPluginTest.kt | 6 +- .../pump/common/PumpPluginAbstract.kt | 14 +- .../pump/virtual/VirtualPumpFragment.kt | 6 +- .../TreatmentsProfileSwitchFragment.kt | 10 +- .../fragments/TreatmentsTempTargetFragment.kt | 15 +- .../TreatmentsTemporaryBasalsFragment.kt | 11 +- .../ui/defaultProfile/DefaultProfile.kt | 85 ++++++---- .../ui/defaultProfile/DefaultProfileDPV.kt | 14 +- .../ui/dialogs/CalibrationDialog.kt | 16 +- .../info/nightscout/ui/dialogs/CarbsDialog.kt | 32 ++-- .../info/nightscout/ui/dialogs/CareDialog.kt | 10 +- .../info/nightscout/ui/dialogs/FillDialog.kt | 14 +- .../nightscout/ui/dialogs/InsulinDialog.kt | 27 ++-- .../ui/dialogs/ProfileSwitchDialog.kt | 7 +- .../ui/dialogs/ProfileViewerDialog.kt | 24 ++- .../nightscout/ui/dialogs/TempTargetDialog.kt | 15 +- .../nightscout/ui/dialogs/TreatmentDialog.kt | 22 ++- .../nightscout/ui/dialogs/WizardDialog.kt | 23 ++- .../nightscout/ui/dialogs/WizardInfoDialog.kt | 11 +- .../ui/extensions/DoubleToSignedString.kt | 4 +- .../java/info/nightscout/ui/widget/Widget.kt | 37 +++-- .../ui/defaultProfile/DefaultProfileTest.kt | 6 +- .../workflow/PrepareBgDataWorker.kt | 11 +- .../PrepareIobAutosensGraphDataWorker.kt | 3 +- .../workflow/PreparePredictionsWorker.kt | 8 +- .../PrepareTemporaryTargetDataWorker.kt | 8 +- .../workflow/PrepareTreatmentsDataWorker.kt | 25 ++- .../workflow/iob/IobCobOref1Worker.kt | 3 +- .../workflow/iob/IobCobOrefWorker.kt | 3 +- 156 files changed, 1347 insertions(+), 964 deletions(-) create mode 100644 app-wear-shared/shared/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt create mode 100644 app-wear-shared/shared/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt create mode 100644 app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt delete mode 100644 core/interfaces/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt delete mode 100644 core/interfaces/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt delete mode 100644 core/main/src/test/java/info/nightscout/core/utils/DecimalFormatterTest.kt create mode 100644 implementation/src/main/java/info/nightscout/implementation/profile/ProfileUtilImpl.kt create mode 100644 implementation/src/main/java/info/nightscout/implementation/utils/DecimalFormatterImpl.kt create mode 100644 implementation/src/test/java/info/nightscout/implementation/profile/ProfileUtilImplTest.kt create mode 100644 implementation/src/test/java/info/nightscout/implementation/utils/DecimalFormatterTest.kt rename {app-wear-shared/shared/src/main/java/info/nightscout/shared/sharedPreferences => pump/combov2/src/main/kotlin/info/nightscout/pump/combov2}/Delegates.kt (96%) 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 From 9ea67288a1e51b0ab105cc4e820d82d75a5d38df Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:10:57 -0700 Subject: [PATCH 07/34] Rewrites ConstraintsCheckerTest with matchers Issue #2745 --- .../constraints/ConstraintsCheckerTest.kt | 76 +++++++++---------- 1 file changed, 38 insertions(+), 38 deletions(-) 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 fb423910eb..ad5bac6590 100644 --- a/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt @@ -1,5 +1,6 @@ package info.nightscout.plugins.constraints +import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.DanaRPlugin @@ -43,7 +44,6 @@ import info.nightscout.pump.danars.DanaRSPlugin import info.nightscout.pump.virtual.VirtualPumpPlugin import info.nightscout.sharedtests.TestBaseWithProfile import info.nightscout.source.GlimpPlugin -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock @@ -237,9 +237,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { comboPlugin.setPluginEnabled(PluginType.PUMP, true) comboPlugin.setValidBasalRateProfileSelectedOnPump(false) val c = constraintChecker.isLoopInvocationAllowed() - Assertions.assertEquals(true, c.reasonList.size == 2) // Combo & Objectives - Assertions.assertEquals(true, c.mostLimitedReasonList.size == 2) // Combo & Objectives - Assertions.assertEquals(java.lang.Boolean.FALSE, c.value()) + assertThat(c.reasonList).hasSize(2) // Combo & Objectives + assertThat(c.mostLimitedReasonList).hasSize(2) // Combo & Objectives + assertThat(c.value()).isFalse() } // Safety & Objectives @@ -250,13 +250,13 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { objectivesPlugin.objectives[Objectives.MAXIOB_ZERO_CL_OBJECTIVE].startedOn = 0 var c: Constraint = constraintChecker.isClosedLoopAllowed() aapsLogger.debug("Reason list: " + c.reasonList.toString()) -// Assertions.assertTrue(c.reasonList[0].toString().contains("Closed loop is disabled")) // Safety & Objectives - Assertions.assertEquals(false, c.value()) +// assertThat(c.reasonList[0].toString()).contains("Closed loop is disabled") // Safety & Objectives + assertThat(c.value()).isFalse() `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.OPEN.name) c = constraintChecker.isClosedLoopAllowed() - Assertions.assertTrue(c.reasonList[0].contains("Closed loop mode disabled in preferences")) // Safety & Objectives -// Assertions.assertEquals(3, c.reasonList.size) // 2x Safety & Objectives - Assertions.assertEquals(false, c.value()) + assertThat(c.reasonList[0]).contains("Closed loop mode disabled in preferences") // Safety & Objectives +// assertThat(c.reasonList).hasThat(3) // 2x Safety & Objectives + assertThat(c.value()).isFalse() } // Safety & Objectives @@ -266,9 +266,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { objectivesPlugin.objectives[Objectives.AUTOSENS_OBJECTIVE].startedOn = 0 `when`(sp.getBoolean(info.nightscout.plugins.aps.R.string.key_openapsama_use_autosens, false)).thenReturn(false) val c = constraintChecker.isAutosensModeEnabled() - Assertions.assertEquals(true, c.reasonList.size == 2) // Safety & Objectives - Assertions.assertEquals(true, c.mostLimitedReasonList.size == 2) // Safety & Objectives - Assertions.assertEquals(java.lang.Boolean.FALSE, c.value()) + assertThat(c.reasonList).hasSize(2) // Safety & Objectives + assertThat(c.mostLimitedReasonList).hasSize(2) // Safety & Objectives + assertThat( c.value()).isFalse() } // Safety @@ -276,9 +276,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { fun isAdvancedFilteringEnabledTest() { `when`(activePlugin.activeBgSource).thenReturn(glimpPlugin) val c = constraintChecker.isAdvancedFilteringEnabled() - Assertions.assertEquals(true, c.reasonList.size == 1) // Safety - Assertions.assertEquals(true, c.mostLimitedReasonList.size == 1) // Safety - Assertions.assertEquals(false, c.value()) + assertThat(c.reasonList).hasSize(1) // Safety + assertThat(c.mostLimitedReasonList).hasSize(1) // Safety + assertThat( c.value()).isFalse() } // SMB should limit @@ -286,7 +286,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { fun isSuperBolusEnabledTest() { openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true) val c = constraintChecker.isSuperBolusEnabled() - Assertions.assertEquals(java.lang.Boolean.FALSE, c.value()) // SMB should limit + assertThat( c.value()).isFalse() // SMB should limit } // Safety & Objectives @@ -298,9 +298,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.OPEN.name) // `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(Constraint(true)) val c = constraintChecker.isSMBModeEnabled() - Assertions.assertEquals(true, c.reasonList.size == 3) // 2x Safety & Objectives - Assertions.assertEquals(true, c.mostLimitedReasonList.size == 3) // 2x Safety & Objectives - Assertions.assertEquals(false, c.value()) + assertThat(c.reasonList).hasSize(3) // 2x Safety & Objectives + assertThat(c.mostLimitedReasonList).hasSize(3) // 2x Safety & Objectives + assertThat( c.value()).isFalse() } // applyBasalConstraints tests @@ -326,9 +326,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxBasalAllowed(validProfile) - Assertions.assertEquals(0.8, d.value(), 0.01) - Assertions.assertEquals(3, d.reasonList.size) - Assertions.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", d.getMostLimitedReasons(aapsLogger)) + assertThat( d.value()).isWithin( 0.01).of(0.8) + assertThat(d.reasonList).hasSize(3) + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit") } @Test @@ -353,9 +353,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val i = constraintChecker.getMaxBasalPercentAllowed(validProfile) - Assertions.assertEquals(200, i.value()) - Assertions.assertEquals(6, i.reasonList.size) - Assertions.assertEquals("Safety: Limiting max percent rate to 200% because of pump limit", i.getMostLimitedReasons(aapsLogger)) + assertThat(i.value()).isEqualTo(200) + assertThat(i.reasonList).hasSize(6) + assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting max percent rate to 200% because of pump limit") } // applyBolusConstraints tests @@ -380,9 +380,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxBolusAllowed() - Assertions.assertEquals(3.0, d.value(), 0.01) - Assertions.assertEquals(4, d.reasonList.size) // 2x Safety & RS & R - Assertions.assertEquals("Safety: Limiting bolus to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) + assertThat( d.value()).isWithin( 0.01).of(3.0) + assertThat(d.reasonList).hasSize(4) // 2x Safety & RS & R + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 3.0 U because of max value in preferences") } // applyCarbsConstraints tests @@ -393,9 +393,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val i = constraintChecker.getMaxCarbsAllowed() - Assertions.assertEquals(48, i.value()) - Assertions.assertEquals(true, i.reasonList.size == 1) - Assertions.assertEquals("Safety: Limiting carbs to 48 g because of max value in preferences", i.getMostLimitedReasons(aapsLogger)) + assertThat(i.value()).isEqualTo(48) + assertThat(i.reasonList).hasSize(1) + assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting carbs to 48 g because of max value in preferences") } // applyMaxIOBConstraints tests @@ -410,9 +410,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxIOBAllowed() - Assertions.assertEquals(1.5, d.value(), 0.01) - Assertions.assertEquals(2, d.reasonList.size) - Assertions.assertEquals("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) + assertThat( d.value()).isWithin( 0.01).of(1.5) + assertThat(d.reasonList).hasSize(2) + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences") } @Test @@ -426,8 +426,8 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxIOBAllowed() - Assertions.assertEquals(3.0, d.value(), 0.01) - Assertions.assertEquals(2, d.reasonList.size) - Assertions.assertEquals("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) + assertThat( d.value()).isWithin( 0.01).of(3.0) + assertThat(d.reasonList).hasSize(2) + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences") } -} \ No newline at end of file +} From 75ff796510cb4a76aae2e72244621111252bc88b Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:13:43 -0700 Subject: [PATCH 08/34] Rewrites SafetyPluginTest with matchers Issue #2745 --- .../plugins/safety/SafetyPluginTest.kt | 110 +++++++++--------- 1 file changed, 54 insertions(+), 56 deletions(-) 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 eb79869c31..56e88846d8 100644 --- a/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt @@ -1,5 +1,6 @@ package info.nightscout.plugins.safety +import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.database.impl.AppRepository @@ -21,7 +22,6 @@ import info.nightscout.plugins.constraints.safety.SafetyPlugin import info.nightscout.pump.virtual.VirtualPumpPlugin import info.nightscout.sharedtests.TestBaseWithProfile import info.nightscout.source.GlimpPlugin -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock @@ -88,8 +88,8 @@ class SafetyPluginTest : TestBaseWithProfile() { pumpDescription.isTempBasalCapable = false var c = Constraint(true) c = safetyPlugin.isLoopInvocationAllowed(c) - Assertions.assertEquals("Safety: Pump is not temp basal capable", c.getReasons(aapsLogger)) - Assertions.assertEquals(false, c.value()) + assertThat(c.getReasons(aapsLogger)).isEqualTo("Safety: Pump is not temp basal capable") + assertThat(c.value()).isFalse() } @Test @@ -98,8 +98,8 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(config.isEngineeringModeOrRelease()).thenReturn(false) var c = Constraint(true) c = safetyPlugin.isClosedLoopAllowed(c) - Assertions.assertTrue(c.getReasons(aapsLogger).contains("Running dev version. Closed loop is disabled.")) - Assertions.assertEquals(false, c.value()) + assertThat(c.getReasons(aapsLogger)).contains("Running dev version. Closed loop is disabled.") + assertThat(c.value()).isFalse() } @Test @@ -107,8 +107,8 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.OPEN.name) var c = Constraint(true) c = safetyPlugin.isClosedLoopAllowed(c) - Assertions.assertTrue(c.getReasons(aapsLogger).contains("Closed loop mode disabled in preferences")) - Assertions.assertEquals(false, c.value()) + assertThat(c.getReasons(aapsLogger)).contains("Closed loop mode disabled in preferences") + assertThat(c.value()).isFalse() } @Test @@ -117,8 +117,8 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(constraintChecker.isClosedLoopAllowed(anyObject())).thenReturn(Constraint(true)) var c = Constraint(true) c = openAPSSMBPlugin.isSMBModeEnabled(c) - Assertions.assertTrue(c.getReasons(aapsLogger).contains("SMB disabled in preferences")) - Assertions.assertEquals(false, c.value()) + assertThat(c.getReasons(aapsLogger)).contains("SMB disabled in preferences") + assertThat(c.value()).isFalse() } @Test @@ -127,8 +127,8 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(constraintChecker.isClosedLoopAllowed(anyObject())).thenReturn(Constraint(false)) var c = Constraint(true) c = safetyPlugin.isSMBModeEnabled(c) - Assertions.assertTrue(c.getReasons(aapsLogger).contains("SMB not allowed in open loop mode")) - Assertions.assertEquals(false, c.value()) + assertThat(c.getReasons(aapsLogger)).contains("SMB not allowed in open loop mode") + assertThat(c.value()).isFalse() } @Test @@ -136,8 +136,8 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(activePlugin.activeBgSource).thenReturn(glimpPlugin) var c = Constraint(true) c = safetyPlugin.isAdvancedFilteringEnabled(c) - Assertions.assertEquals("Safety: SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering", c.getReasons(aapsLogger)) - Assertions.assertEquals(false, c.value()) + assertThat(c.getReasons(aapsLogger)).isEqualTo("Safety: SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") + assertThat(c.value()).isFalse() } @Test @@ -148,13 +148,12 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") val c = Constraint(Constants.REALLYHIGHBASALRATE) safetyPlugin.applyBasalConstraints(c, validProfile) - Assertions.assertEquals(2.0, c.value(), 0.01) - Assertions.assertEquals( + assertThat(c.value()).isWithin(0.01).of(2.0) + assertThat(c.getReasons(aapsLogger)).isEqualTo( """ Safety: Limiting max basal rate to 2.00 U/h because of hard limit - """.trimIndent(), c.getReasons(aapsLogger) - ) - Assertions.assertEquals("Safety: Limiting max basal rate to 2.00 U/h because of hard limit", c.getMostLimitedReasons(aapsLogger)) + """.trimIndent()) + assertThat(c.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting max basal rate to 2.00 U/h because of hard limit") } @Test @@ -162,8 +161,9 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") val d = Constraint(-0.5) safetyPlugin.applyBasalConstraints(d, validProfile) - Assertions.assertEquals(0.0, d.value(), 0.01) - Assertions.assertEquals("Safety: Limiting max basal rate to 0.00 U/h because of it must be positive value", d.getReasons(aapsLogger)) + assertThat(d.value()).isWithin(0.01).of(0.0) + assertThat(d.getReasons(aapsLogger)).isEqualTo( + "Safety: Limiting max basal rate to 0.00 U/h because of it must be positive value") } @Test @@ -175,16 +175,17 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") val i = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) safetyPlugin.applyBasalPercentConstraints(i, validProfile) - Assertions.assertEquals(200, i.value()) - Assertions.assertEquals( + assertThat(i.value()).isEqualTo(200) + assertThat(i.getReasons(aapsLogger)).isEqualTo( """ Safety: Percent rate 1111111% recalculated to 11111.11 U/h with current basal 1.00 U/h Safety: Limiting max basal rate to 2.00 U/h because of hard limit Safety: Limiting max percent rate to 200% because of pump limit Safety: Limiting max basal rate to 500.00 U/h because of pump limit - """.trimIndent(), i.getReasons(aapsLogger) + """.trimIndent() ) - Assertions.assertEquals("Safety: Limiting max percent rate to 200% because of pump limit", i.getMostLimitedReasons(aapsLogger)) + assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo( + "Safety: Limiting max percent rate to 200% because of pump limit") } @Test @@ -197,15 +198,14 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true) val i = Constraint(Constants.REALLYHIGHBASALRATE) openAPSSMBPlugin.applyBasalConstraints(i, validProfile) - Assertions.assertEquals(1.0, i.value(), 0.01) - Assertions.assertEquals( + assertThat(i.value()).isWithin(0.01).of(1.0) + assertThat(i.getReasons(aapsLogger)).isEqualTo( """ OpenAPSSMB: Limiting max basal rate to 1.00 U/h because of max value in preferences OpenAPSSMB: Limiting max basal rate to 4.00 U/h because of max basal multiplier OpenAPSSMB: Limiting max basal rate to 3.00 U/h because of max daily basal multiplier - """.trimIndent(), i.getReasons(aapsLogger) - ) - Assertions.assertEquals("OpenAPSSMB: Limiting max basal rate to 1.00 U/h because of max value in preferences", i.getMostLimitedReasons(aapsLogger)) + """.trimIndent()) + assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting max basal rate to 1.00 U/h because of max value in preferences") } @Test @@ -213,15 +213,14 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") val i = Constraint(-22) safetyPlugin.applyBasalPercentConstraints(i, validProfile) - Assertions.assertEquals(0, i.value()) - Assertions.assertEquals( + assertThat(i.value()).isEqualTo(0) + assertThat(i.getReasons(aapsLogger)).isEqualTo( """ Safety: Percent rate -22% recalculated to -0.22 U/h with current basal 1.00 U/h Safety: Limiting max basal rate to 0.00 U/h because of it must be positive value Safety: Limiting max percent rate to 0% because of pump limit - """.trimIndent(), i.getReasons(aapsLogger) - ) - Assertions.assertEquals("Safety: Limiting max percent rate to 0% because of pump limit", i.getMostLimitedReasons(aapsLogger)) + """.trimIndent()) + assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting max percent rate to 0% because of pump limit") } @Test @@ -230,14 +229,13 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") var d = Constraint(Constants.REALLYHIGHBOLUS) d = safetyPlugin.applyBolusConstraints(d) - Assertions.assertEquals(3.0, d.value(), 0.01) - Assertions.assertEquals( + assertThat(d.value()).isWithin(0.01).of(3.0) + assertThat(d.getReasons(aapsLogger)).isEqualTo( """ Safety: Limiting bolus to 3.0 U because of max value in preferences Safety: Limiting bolus to 5.0 U because of hard limit - """.trimIndent(), d.getReasons(aapsLogger) - ) - Assertions.assertEquals("Safety: Limiting bolus to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) + """.trimIndent()) + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 3.0 U because of max value in preferences") } @Test @@ -246,9 +244,9 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") var d = Constraint(-22.0) d = safetyPlugin.applyBolusConstraints(d) - Assertions.assertEquals(0.0, d.value(), 0.01) - Assertions.assertEquals("Safety: Limiting bolus to 0.0 U because of it must be positive value", d.getReasons(aapsLogger)) - Assertions.assertEquals("Safety: Limiting bolus to 0.0 U because of it must be positive value", d.getMostLimitedReasons(aapsLogger)) + assertThat(d.value()).isWithin(0.01).of(0.0) + assertThat(d.getReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 0.0 U because of it must be positive value") + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 0.0 U because of it must be positive value") } @Test @@ -259,13 +257,13 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit // Negative carbs not allowed var i = Constraint(-22) safetyPlugin.applyCarbsConstraints(i) - Assertions.assertEquals(0, i.value()) - Assertions.assertEquals("Safety: Limiting carbs to 0 g because of it must be positive value", i.getReasons(aapsLogger)) + assertThat(i.value()).isEqualTo(0) + assertThat(i.getReasons(aapsLogger)).isEqualTo("Safety: Limiting carbs to 0 g because of it must be positive value") // Apply all limits i = safetyPlugin.applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS)) - Assertions.assertEquals(48, i.value()) - Assertions.assertEquals("Safety: Limiting carbs to 48 g because of max value in preferences", i.getReasons(aapsLogger)) + assertThat(i.value()).isEqualTo(48) + assertThat(i.getReasons(aapsLogger)).isEqualTo("Safety: Limiting carbs to 48 g because of max value in preferences") } @Test @@ -282,22 +280,22 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit // Apply all limits var d = Constraint(Constants.REALLYHIGHIOB) d = safetyPlugin.applyMaxIOBConstraints(d) - Assertions.assertEquals(HardLimits.MAX_IOB_LGS, d.value(), 0.01) - Assertions.assertEquals("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend", d.getReasons(aapsLogger)) - Assertions.assertEquals("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend", d.getMostLimitedReasons(aapsLogger)) + assertThat(d.value()).isWithin(0.01).of(HardLimits.MAX_IOB_LGS) + assertThat(d.getReasons(aapsLogger)).isEqualTo("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend") + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend") // Apply all limits d = Constraint(Constants.REALLYHIGHIOB) val a = openAPSAMAPlugin.applyMaxIOBConstraints(d) - Assertions.assertEquals(1.5, a.value(), 0.01) - Assertions.assertEquals("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences\nOpenAPSAMA: Limiting IOB to 7.0 U because of hard limit", d.getReasons(aapsLogger)) - Assertions.assertEquals("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) + assertThat(a.value()).isWithin(0.01).of(1.5) + assertThat(d.getReasons(aapsLogger)).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences\nOpenAPSAMA: Limiting IOB to 7.0 U because of hard limit") + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences") // Apply all limits d = Constraint(Constants.REALLYHIGHIOB) val s = openAPSSMBPlugin.applyMaxIOBConstraints(d) - Assertions.assertEquals(3.0, s.value(), 0.01) - Assertions.assertEquals("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences\nOpenAPSSMB: Limiting IOB to 22.0 U because of hard limit", d.getReasons(aapsLogger)) - Assertions.assertEquals("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) + assertThat(s.value()).isWithin(0.01).of(3.0) + assertThat(d.getReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences\nOpenAPSSMB: Limiting IOB to 22.0 U because of hard limit") + assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences") } -} \ No newline at end of file +} From f639a78ff4f151cd2ac80d6d4a9db3cac1b98064 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:14:28 -0700 Subject: [PATCH 09/34] Rewrites IobTest with matchers Issue #2745 --- .../java/info/nightscout/core/data/IobTest.kt | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/core/main/src/test/java/info/nightscout/core/data/IobTest.kt b/core/main/src/test/java/info/nightscout/core/data/IobTest.kt index 754bd50591..e9c850b613 100644 --- a/core/main/src/test/java/info/nightscout/core/data/IobTest.kt +++ b/core/main/src/test/java/info/nightscout/core/data/IobTest.kt @@ -1,7 +1,7 @@ package info.nightscout.core.data +import com.google.common.truth.Truth.assertThat import info.nightscout.interfaces.iob.Iob -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class IobTest { @@ -10,23 +10,23 @@ class IobTest { val a = Iob().iobContrib(1.0).activityContrib(2.0) val b = Iob().iobContrib(3.0).activityContrib(4.0) a.plus(b) - Assertions.assertEquals(4.0, a.iobContrib, 0.01) - Assertions.assertEquals(6.0, a.activityContrib, 0.01) + assertThat(a.iobContrib).isWithin(0.01).of(4.0) + assertThat(a.activityContrib).isWithin(0.01).of(6.0) } @Test fun equalTest() { val a1 = Iob().iobContrib(1.0).activityContrib(2.0) val a2 = Iob().iobContrib(1.0).activityContrib(2.0) val b = Iob().iobContrib(3.0).activityContrib(4.0) - Assertions.assertTrue(a1 == a2) - Assertions.assertFalse(a1 == b) - @Suppress("SENSELESS_COMPARISON") - Assertions.assertFalse(a1 == null) - Assertions.assertFalse(a1 == Any()) + assertThat(a1).isEqualTo(a1) + assertThat(a1).isEqualTo(a2) + assertThat(a1).isNotEqualTo(b) + assertThat(a1).isNotNull() + assertThat(a1).isNotEqualTo(Any()) } @Test fun hashCodeTest() { val a = Iob().iobContrib(1.0).activityContrib(2.0) - Assertions.assertNotEquals(0, a.hashCode().toLong()) + assertThat(a.hashCode().toLong()).isNotEqualTo(0L) } -} \ No newline at end of file +} From ce5d2dfdbd9a39ce126322d0c408a40841e94271 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:20:39 -0700 Subject: [PATCH 10/34] Rewrites MidnightTimeTest with matchers Issue #2745 --- .../nightscout/core/utils/MidnightTimeTest.kt | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/core/main/src/test/java/info/nightscout/core/utils/MidnightTimeTest.kt b/core/main/src/test/java/info/nightscout/core/utils/MidnightTimeTest.kt index 1a14a6f9df..7f10b96e7e 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/MidnightTimeTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/MidnightTimeTest.kt @@ -1,7 +1,7 @@ package info.nightscout.core.utils +import com.google.common.truth.Truth.assertThat import info.nightscout.interfaces.utils.MidnightTime -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import java.util.Calendar @@ -10,40 +10,40 @@ class MidnightTimeTest { @Test fun calc() { // We get real midnight val now = System.currentTimeMillis() - Assertions.assertTrue(now >= MidnightTime.calc()) + assertThat(MidnightTime.calc()).isAtMost(now) val c = Calendar.getInstance() c.timeInMillis = MidnightTime.calc() - Assertions.assertEquals(c[Calendar.HOUR_OF_DAY].toLong(), 0) - Assertions.assertEquals(c[Calendar.MINUTE].toLong(), 0) - Assertions.assertEquals(c[Calendar.SECOND].toLong(), 0) - Assertions.assertEquals(c[Calendar.MILLISECOND].toLong(), 0) + assertThat(c[Calendar.HOUR_OF_DAY].toLong()).isEqualTo(0L) + assertThat(c[Calendar.MINUTE].toLong()).isEqualTo(0L) + assertThat(c[Calendar.SECOND].toLong()).isEqualTo(0L) + assertThat(c[Calendar.MILLISECOND].toLong()).isEqualTo(0L) } @Test fun calc_time() { // We get real midnight val now = System.currentTimeMillis() val midnight = MidnightTime.calc(now) - Assertions.assertTrue(now >= midnight) + assertThat(midnight).isAtMost(now) val c = Calendar.getInstance() c.timeInMillis = MidnightTime.calc(now) - Assertions.assertEquals(c[Calendar.HOUR_OF_DAY].toLong(), 0) - Assertions.assertEquals(c[Calendar.MINUTE].toLong(), 0) - Assertions.assertEquals(c[Calendar.SECOND].toLong(), 0) - Assertions.assertEquals(c[Calendar.MILLISECOND].toLong(), 0) + assertThat(c[Calendar.HOUR_OF_DAY].toLong()).isEqualTo(0L) + assertThat(c[Calendar.MINUTE].toLong()).isEqualTo(0L) + assertThat(c[Calendar.SECOND].toLong()).isEqualTo(0L) + assertThat(c[Calendar.MILLISECOND].toLong()).isEqualTo(0L) // Assure we get the same time from cache - Assertions.assertEquals(midnight, MidnightTime.calc(now)) + assertThat(midnight).isEqualTo(MidnightTime.calc(now)) } @Test fun resetCache() { val now = System.currentTimeMillis() MidnightTime.calc(now) MidnightTime.resetCache() - Assertions.assertEquals(0, MidnightTime.times.size().toLong()) + assertThat(MidnightTime.times.size().toLong()).isEqualTo(0L) } @Test fun log() { val now = System.currentTimeMillis() MidnightTime.calc(now) - Assertions.assertTrue(MidnightTime.log().startsWith("Hits:")) + assertThat(MidnightTime.log()).startsWith("Hits:") } -} \ No newline at end of file +} From 788eff46829b46896af39c23e16c6d00b60c354f Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:21:52 -0700 Subject: [PATCH 11/34] Rewrites TTest with matchers Issue #2745 --- .../java/info/nightscout/core/utils/TTest.kt | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/core/main/src/test/java/info/nightscout/core/utils/TTest.kt b/core/main/src/test/java/info/nightscout/core/utils/TTest.kt index fd35265c9c..bf067c9c21 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/TTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/TTest.kt @@ -1,7 +1,7 @@ package info.nightscout.core.utils +import com.google.common.truth.Truth.assertThat import info.nightscout.shared.utils.T -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import kotlin.math.abs @@ -9,33 +9,33 @@ import kotlin.math.abs class TTest { @Test fun toUnits() { - Assertions.assertEquals(1, T.msecs(1000).secs()) - Assertions.assertEquals(1, T.secs(60).mins()) - Assertions.assertEquals(1, T.mins(60).hours()) - Assertions.assertEquals(1, T.hours(24).days()) - Assertions.assertEquals(24, T.days(1).hours()) - Assertions.assertEquals(60000, T.mins(1).msecs()) + assertThat(T.msecs(1000).secs()).isEqualTo(1) + assertThat(T.secs(60).mins()).isEqualTo(1) + assertThat(T.mins(60).hours()).isEqualTo(1) + assertThat(T.hours(24).days()).isEqualTo(1) + assertThat(T.days(1).hours()).isEqualTo(24) + assertThat(T.mins(1).msecs()).isEqualTo(60000) } @Test fun now() { - Assertions.assertTrue(abs(T.now().msecs() - System.currentTimeMillis()) < 5000) + assertThat(abs(T.now().msecs() - System.currentTimeMillis())).isLessThan(5_000L) } @Test fun additions() { val nowMsecs = System.currentTimeMillis() val now = T.msecs(nowMsecs) - Assertions.assertEquals(now.plus(T.secs(5)).msecs(), nowMsecs + 5 * 1000) - Assertions.assertEquals(now.plus(T.mins(5)).msecs(), nowMsecs + 5 * 60 * 1000) - Assertions.assertEquals(now.plus(T.hours(5)).msecs(), nowMsecs + 5 * 60 * 60 * 1000) - Assertions.assertEquals(now.plus(T.days(5)).msecs(), nowMsecs + 5 * 24 * 60 * 60 * 1000) + assertThat(nowMsecs + 5 * 1000).isEqualTo(now.plus(T.secs(5)).msecs()) + assertThat(nowMsecs + 5 * 60 * 1000).isEqualTo(now.plus(T.mins(5)).msecs()) + assertThat(nowMsecs + 5 * 60 * 60 * 1000).isEqualTo(now.plus(T.hours(5)).msecs()) + assertThat(nowMsecs + 5 * 24 * 60 * 60 * 1000).isEqualTo(now.plus(T.days(5)).msecs()) } @Test fun subtractions() { val nowMsecs = System.currentTimeMillis() val now = T.msecs(nowMsecs) - Assertions.assertEquals(now.minus(T.secs(5)).msecs(), nowMsecs - 5 * 1000) - Assertions.assertEquals(now.minus(T.mins(5)).msecs(), nowMsecs - 5 * 60 * 1000) - Assertions.assertEquals(now.minus(T.hours(5)).msecs(), nowMsecs - 5 * 60 * 60 * 1000) - Assertions.assertEquals(now.minus(T.days(5)).msecs(), nowMsecs - 5 * 24 * 60 * 60 * 1000) + assertThat(nowMsecs - 5 * 1000).isEqualTo(now.minus(T.secs(5)).msecs()) + assertThat(nowMsecs - 5 * 60 * 1000).isEqualTo(now.minus(T.mins(5)).msecs()) + assertThat(nowMsecs - 5 * 60 * 60 * 1000).isEqualTo(now.minus(T.hours(5)).msecs()) + assertThat(nowMsecs - 5 * 24 * 60 * 60 * 1000).isEqualTo(now.minus(T.days(5)).msecs()) } -} \ No newline at end of file +} From e3e17456c2526a9f56f760491f9f4fe8beaa1d4a Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:22:55 -0700 Subject: [PATCH 12/34] Rewrites BolusWizardTest with matchers Issue #2745 --- .../implementation/wizard/BolusWizardTest.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 bb39a0b381..707134a5ab 100644 --- a/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt @@ -1,5 +1,6 @@ package info.nightscout.implementation.wizard +import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.core.wizard.BolusWizard @@ -14,7 +15,6 @@ import info.nightscout.interfaces.pump.defs.PumpDescription import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.rx.bus.RxBus import info.nightscout.sharedtests.TestBaseWithProfile -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.Mockito @@ -113,7 +113,7 @@ class BolusWizardTest : TestBaseWithProfile() { useAlarm = false ) val bolusForBg54 = bw.calculatedTotalInsulin - Assertions.assertEquals(bolusForBg42, bolusForBg54, 0.01) + assertThat(bolusForBg54).isWithin( 0.01).of(bolusForBg42) } @Test @@ -159,7 +159,7 @@ class BolusWizardTest : TestBaseWithProfile() { useAlarm = false ) val bolusForBgInRange = bw.calculatedTotalInsulin - Assertions.assertTrue(bolusForHighBg > bolusForBgInRange) + assertThat(bolusForHighBg).isGreaterThan(bolusForBgInRange) } @Test @@ -205,6 +205,6 @@ class BolusWizardTest : TestBaseWithProfile() { useAlarm = false ) val bolusForBgInRange = bw.calculatedTotalInsulin - Assertions.assertTrue(bolusForLowBg < bolusForBgInRange) + assertThat(bolusForLowBg).isLessThan(bolusForBgInRange) } -} \ No newline at end of file +} From e709ff7d45d14d0dc79487a1672ea4fb029e88be Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:28:06 -0700 Subject: [PATCH 13/34] Rewrites TriggerConnectorTest with matchers Issue #2745 --- .../triggers/TriggerConnectorTest.kt | 45 +++++++++---------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerConnectorTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerConnectorTest.kt index 02d4737f66..df5b1a7e51 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerConnectorTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerConnectorTest.kt @@ -1,8 +1,8 @@ package info.nightscout.automation.triggers +import com.google.common.truth.Truth.assertThat import org.json.JSONException import org.json.JSONObject -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class TriggerConnectorTest : TriggerTestBase() { @@ -15,66 +15,65 @@ class TriggerConnectorTest : TriggerTestBase() { val t = TriggerConnector(injector) val t2 = TriggerConnector(injector) val t3 = TriggerConnector(injector) - Assertions.assertTrue(t.size() == 0) + assertThat(t.size()).isEqualTo(0) t.list.add(t2) - Assertions.assertTrue(t.size() == 1) - Assertions.assertEquals(t2, t.list[0]) + assertThat(t.size()).isEqualTo(1) + assertThat(t.list).containsExactly(t2) t.list.add(t3) - Assertions.assertTrue(t.size() == 2) - Assertions.assertEquals(t2, t.list[0]) - Assertions.assertEquals(t3, t.list[1]) - Assertions.assertTrue(t.list.remove(t2)) - Assertions.assertTrue(t.size() == 1) - Assertions.assertEquals(t3, t.list[0]) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.size()).isEqualTo(2) + assertThat(t.list).containsExactly(t2, t3).inOrder() + assertThat(t.list.remove(t2)).isTrue() + assertThat(t.size()).isEqualTo(1) + assertThat(t.list).containsExactly(t3) + assertThat(t.shouldRun()).isTrue() } @Test fun testListTriggerOR() { val t = TriggerConnector(injector, TriggerConnector.Type.OR) t.list.add(TriggerDummy(injector)) t.list.add(TriggerDummy(injector)) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() t.list.add(TriggerDummy(injector, true)) t.list.add(TriggerDummy(injector)) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() } @Test fun testListTriggerXOR() { val t = TriggerConnector(injector, TriggerConnector.Type.XOR) t.list.add(TriggerDummy(injector)) t.list.add(TriggerDummy(injector)) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() t.list.add(TriggerDummy(injector, true)) t.list.add(TriggerDummy(injector)) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() t.list.add(TriggerDummy(injector, true)) t.list.add(TriggerDummy(injector)) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() } @Test fun testListTriggerAND() { val t = TriggerConnector(injector, TriggerConnector.Type.AND) t.list.add(TriggerDummy(injector, true)) t.list.add(TriggerDummy(injector, true)) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() t.list.add(TriggerDummy(injector, true)) t.list.add(TriggerDummy(injector)) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() } @Test fun toJSONTest() { val t = TriggerConnector(injector) - Assertions.assertEquals(empty, t.toJSON()) + assertThat(t.toJSON()).isEqualTo(empty) t.list.add(TriggerConnector(injector)) - Assertions.assertEquals(oneItem, t.toJSON()) + assertThat(t.toJSON()).isEqualTo(oneItem) } @Test @Throws(JSONException::class) fun fromJSONTest() { val t = TriggerConnector(injector) t.list.add(TriggerConnector(injector)) val t2 = TriggerDummy(injector).instantiate(JSONObject(t.toJSON())) as TriggerConnector - Assertions.assertEquals(1, t2.size().toLong()) - Assertions.assertTrue(t2.list[0] is TriggerConnector) + assertThat(t2.size()).isEqualTo(1) + assertThat(t2.list[0]).isInstanceOf(TriggerConnector::class.java) } -} \ No newline at end of file +} From 2d8b1ecd9051a36dc63e416667f59d5e9590d1de Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:31:19 -0700 Subject: [PATCH 14/34] Rewrites TriggerDeltaTest with matchers Issue #2745 --- .../automation/triggers/TriggerDeltaTest.kt | 55 +++++++++---------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerDeltaTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerDeltaTest.kt index 16c009be62..97cf9aba43 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerDeltaTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerDeltaTest.kt @@ -1,6 +1,6 @@ package info.nightscout.automation.triggers -import com.google.common.base.Optional +import com.google.common.truth.Truth.assertThat import info.nightscout.automation.R import info.nightscout.automation.elements.Comparator import info.nightscout.automation.elements.InputDelta.DeltaType @@ -8,7 +8,6 @@ import info.nightscout.database.entities.GlucoseValue import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.iob.InMemoryGlucoseValue import org.json.JSONObject -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mockito.`when` @@ -25,40 +24,40 @@ class TriggerDeltaTest : TriggerTestBase() { @Test fun shouldRunTest() { `when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateValidBgData()) var t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(73.0, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL) - Assertions.assertFalse(t.shouldRun()) - Assertions.assertEquals(DeltaType.LONG_AVERAGE, t.delta.deltaType) + assertThat(t.shouldRun()).isFalse() + assertThat(t.delta.deltaType).isEqualTo(DeltaType.LONG_AVERAGE) t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(-2.0, DeltaType.SHORT_AVERAGE).comparator(Comparator.Compare.IS_EQUAL) - Assertions.assertFalse(t.shouldRun()) - Assertions.assertEquals(DeltaType.SHORT_AVERAGE, t.delta.deltaType) + assertThat(t.shouldRun()).isFalse() + assertThat(t.delta.deltaType).isEqualTo(DeltaType.SHORT_AVERAGE) t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(-3.0, DeltaType.DELTA).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER) - Assertions.assertTrue(t.shouldRun()) - Assertions.assertEquals(DeltaType.DELTA, t.delta.deltaType) + assertThat(t.shouldRun()).isTrue() + assertThat(t.delta.deltaType).isEqualTo(DeltaType.DELTA) t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(2.0, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(2.0, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(0.3, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(0.1, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(-0.5, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(-0.2, DeltaType.LONG_AVERAGE).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() `when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(ArrayList()) t = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(213.0, DeltaType.DELTA).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) - Assertions.assertFalse(t.shouldRun()) + assertThat(t.shouldRun()).isFalse() t = TriggerDelta(injector).comparator(Comparator.Compare.IS_NOT_AVAILABLE) - Assertions.assertTrue(t.shouldRun()) + assertThat(t.shouldRun()).isTrue() } @Test fun copyConstructorTest() { val t: TriggerDelta = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(213.0, DeltaType.DELTA).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) val t1 = t.duplicate() as TriggerDelta - Assertions.assertEquals(213.0, t1.delta.value, 0.01) - Assertions.assertEquals(GlucoseUnit.MGDL, t1.units) - Assertions.assertEquals(DeltaType.DELTA, t.delta.deltaType) - Assertions.assertEquals(Comparator.Compare.IS_EQUAL_OR_LESSER, t.comparator.value) + assertThat( t1.delta.value).isWithin( 0.01).of(213.0) + assertThat(t1.units).isEqualTo(GlucoseUnit.MGDL) + assertThat(t.delta.deltaType).isEqualTo(DeltaType.DELTA) + assertThat(t.comparator.value).isEqualTo(Comparator.Compare.IS_EQUAL_OR_LESSER) } private var deltaJson = "{\"data\":{\"comparator\":\"IS_EQUAL\",\"deltaType\":\"DELTA\",\"units\":\"mg/dl\",\"value\":4.1},\"type\":\"TriggerDelta\"}" @@ -66,26 +65,26 @@ class TriggerDeltaTest : TriggerTestBase() { @Test fun toJSONTest() { val t: TriggerDelta = TriggerDelta(injector).units(GlucoseUnit.MGDL).setValue(4.1, DeltaType.DELTA).comparator(Comparator.Compare.IS_EQUAL) - Assertions.assertEquals(deltaJson, t.toJSON()) + assertThat(t.toJSON()).isEqualTo(deltaJson) } @Test fun fromJSONTest() { val t: TriggerDelta = TriggerDelta(injector).units(GlucoseUnit.MMOL).setValue(4.1, DeltaType.DELTA).comparator(Comparator.Compare.IS_EQUAL) val t2 = TriggerDummy(injector).instantiate(JSONObject(t.toJSON())) as TriggerDelta - Assertions.assertEquals(Comparator.Compare.IS_EQUAL, t2.comparator.value) - Assertions.assertEquals(4.1, t2.delta.value, 0.01) - Assertions.assertEquals(GlucoseUnit.MMOL, t2.units) - Assertions.assertEquals(DeltaType.DELTA, t2.delta.deltaType) + assertThat(t2.comparator.value).isEqualTo(Comparator.Compare.IS_EQUAL) + assertThat( t2.delta.value).isWithin( 0.01).of(4.1) + assertThat(t2.units).isEqualTo(GlucoseUnit.MMOL) + assertThat(t2.delta.deltaType).isEqualTo(DeltaType.DELTA) } @Test fun iconTest() { - Assertions.assertEquals(Optional.of(R.drawable.ic_auto_delta), TriggerDelta(injector).icon()) + assertThat(TriggerDelta(injector).icon()).hasValue(R.drawable.ic_auto_delta) } @Test fun initializerTest() { val t = TriggerDelta(injector) - Assertions.assertTrue(t.units == GlucoseUnit.MGDL) + assertThat(t.units).isEqualTo(GlucoseUnit.MGDL) } private fun generateValidBgData(): MutableList { @@ -100,4 +99,4 @@ class TriggerDeltaTest : TriggerTestBase() { list.add(InMemoryGlucoseValue(value = 228.0, timestamp = 1514764800000, trendArrow = GlucoseValue.TrendArrow.FLAT, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN)) return list } -} \ No newline at end of file +} From e83d83b350acd52d242006f11168bc38912b1d2d Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:33:00 -0700 Subject: [PATCH 15/34] Rewrites SntpClientTest with matchers Issue #2745 --- .../constraints/objectives/SntpClientTest.kt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/SntpClientTest.kt b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/SntpClientTest.kt index 4846aab209..10431b0875 100644 --- a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/SntpClientTest.kt +++ b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/SntpClientTest.kt @@ -1,8 +1,8 @@ package info.nightscout.plugins.constraints.objectives +import com.google.common.truth.Truth.assertThat import info.nightscout.shared.utils.DateUtil import info.nightscout.sharedtests.TestBase -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mock import kotlin.math.abs @@ -16,17 +16,17 @@ class SntpClientTest : TestBase() { // no internet SntpClient(aapsLogger, dateUtil).ntpTime(object : SntpClient.Callback() { override fun run() { - Assertions.assertFalse(networkConnected) - Assertions.assertFalse(success) - Assertions.assertEquals(0L, time) + assertThat(networkConnected).isFalse() + assertThat(success).isFalse() + assertThat(time).isEqualTo(0L) } }, false) // internet SntpClient(aapsLogger, dateUtil).doNtpTime(object : SntpClient.Callback() { override fun run() { - Assertions.assertTrue(success) - Assertions.assertTrue(abs(time - System.currentTimeMillis()) < 60000) + assertThat(success).isTrue() + assertThat(abs(time - System.currentTimeMillis())).isLessThan(60_000L) } }) } -} \ No newline at end of file +} From 152ef1f910b49bd4df49b4278ce5cdf6f3bfe475 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:34:42 -0700 Subject: [PATCH 16/34] Rewrites InsulinOrefBasePluginTest with matchers Issue #2745 --- .../insulin/InsulinOrefBasePluginTest.kt | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefBasePluginTest.kt b/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefBasePluginTest.kt index 4a3550392a..76874d63fc 100644 --- a/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefBasePluginTest.kt +++ b/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefBasePluginTest.kt @@ -1,5 +1,6 @@ package info.nightscout.insulin +import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.database.entities.Bolus @@ -13,7 +14,6 @@ import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.AAPSLogger import info.nightscout.shared.interfaces.ResourceHelper import org.json.JSONObject -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -81,12 +81,12 @@ class InsulinOrefBasePluginTest { @Test fun testGetDia() { - Assertions.assertEquals(5.0, sut.dia, 0.0) + assertThat(sut.dia).isEqualTo(5.0) testUserDefinedDia = 5.0 + 1 - Assertions.assertEquals(5.0 + 1, sut.dia, 0.0) + assertThat(sut.dia).isEqualTo(5.0 + 1) testUserDefinedDia = 5.0 - 1 - Assertions.assertEquals(5.0, sut.dia, 0.0) - Assertions.assertTrue(shortDiaNotificationSend) + assertThat(sut.dia).isEqualTo(5.0) + assertThat(shortDiaNotificationSend).isTrue() } @Test @@ -98,22 +98,22 @@ class InsulinOrefBasePluginTest { // check directly after bolus treatment.timestamp = time treatment.amount = 10.0 - Assertions.assertEquals(10.0, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1) + assertThat(sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib).isWithin(0.01).of(10.0) // check after 1 hour treatment.timestamp = time - 1 * 60 * 60 * 1000 // 1 hour treatment.amount = 10.0 - Assertions.assertEquals(3.92, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1) + assertThat(sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib).isWithin(0.01).of(3.92) // check after 2 hour treatment.timestamp = time - 2 * 60 * 60 * 1000 // 2 hours treatment.amount = 10.0 - Assertions.assertEquals(0.77, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1) + assertThat(sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib).isWithin(0.01).of(0.77) // check after 3 hour treatment.timestamp = time - 3 * 60 * 60 * 1000 // 3 hours treatment.amount = 10.0 - Assertions.assertEquals(0.10, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1) + assertThat(sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib).isWithin(0.01).of(0.10) // check after dia treatment.timestamp = time - 4 * 60 * 60 * 1000 // 4 hours treatment.amount = 10.0 - Assertions.assertEquals(0.0, sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib, 0.1) + assertThat(sut.iobCalcForTreatment(treatment, time, Constants.defaultDIA).iobContrib).isWithin(0.01).of(0.0) } -} \ No newline at end of file +} From 14262b5176eae9dd18d5080a2a32c6e348e6850a Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:38:26 -0700 Subject: [PATCH 17/34] Rewrites SmsCommunicatorPluginTest with matchers Issue #2745 --- .../SmsCommunicatorPluginTest.kt | 550 +++++++++--------- 1 file changed, 275 insertions(+), 275 deletions(-) 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 6030e485fe..a591e04dc8 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 @@ -1,6 +1,7 @@ package info.nightscout.plugins.general.smsCommunicator import android.telephony.SmsManager +import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.database.entities.GlucoseValue @@ -34,7 +35,6 @@ import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T import info.nightscout.sharedtests.TestBaseWithProfile import io.reactivex.rxjava3.core.Single -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.ArgumentMatchers @@ -249,27 +249,27 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { @Test fun processSettingsTest() { // called from constructor - Assertions.assertEquals("1234", smsCommunicatorPlugin.allowedNumbers[0]) - Assertions.assertEquals("5678", smsCommunicatorPlugin.allowedNumbers[1]) - Assertions.assertEquals(2, smsCommunicatorPlugin.allowedNumbers.size) + assertThat(smsCommunicatorPlugin.allowedNumbers[0]).isEqualTo("1234") + assertThat(smsCommunicatorPlugin.allowedNumbers[1]).isEqualTo("5678") + assertThat(smsCommunicatorPlugin.allowedNumbers).hasSize(2) } @Test fun isCommandTest() { - Assertions.assertTrue(smsCommunicatorPlugin.isCommand("BOLUS", "")) + assertThat(smsCommunicatorPlugin.isCommand("BOLUS", "")).isTrue() smsCommunicatorPlugin.messageToConfirm = null - Assertions.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "")) + assertThat(smsCommunicatorPlugin.isCommand("BLB", "")).isFalse() smsCommunicatorPlugin.messageToConfirm = AuthRequest(injector, Sms("1234", "ddd"), "RequestText", "ccode", object : SmsAction(false) { override fun run() {} }) - Assertions.assertTrue(smsCommunicatorPlugin.isCommand("BLB", "1234")) - Assertions.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "2345")) + assertThat(smsCommunicatorPlugin.isCommand("BLB", "1234")).isTrue() + assertThat(smsCommunicatorPlugin.isCommand("BLB", "2345")).isFalse() smsCommunicatorPlugin.messageToConfirm = null } @Test fun isAllowedNumberTest() { - Assertions.assertTrue(smsCommunicatorPlugin.isAllowedNumber("5678")) - Assertions.assertFalse(smsCommunicatorPlugin.isAllowedNumber("56")) + assertThat(smsCommunicatorPlugin.isAllowedNumber("5678")).isTrue() + assertThat(smsCommunicatorPlugin.isAllowedNumber("56")).isFalse() } @Test fun processSmsTest() { @@ -278,32 +278,32 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("12", "aText") smsCommunicatorPlugin.processSms(sms) - Assertions.assertTrue(sms.ignored) - Assertions.assertEquals("aText", smsCommunicatorPlugin.messages[0].text) + assertThat(sms.ignored).isTrue() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("aText") //UNKNOWN smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "UNKNOWN") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("UNKNOWN", smsCommunicatorPlugin.messages[0].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("UNKNOWN") //BG smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BG") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BG", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("IOB:")) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Last BG: 100")) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("COB: 10(2)g")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BG") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("IOB:") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("Last BG: 100") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("COB: 10(2)g") // LOOP : test remote control disabled `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(false) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP STATUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Remote command is not allowed")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //LOOP STATUS : disabled @@ -311,8 +311,8 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP STATUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is disabled", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is disabled") //LOOP STATUS : suspended `when`(loop.minutesToEndOfSuspend()).thenReturn(10) @@ -321,8 +321,8 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP STATUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Suspended (10 m)", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Suspended (10 m)") //LOOP STATUS : enabled - APS mode - Closed `when`(loop.enabled).thenReturn(true) @@ -331,51 +331,51 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP STATUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is enabled - $modeClosed", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is enabled - $modeClosed") //LOOP STATUS : enabled - APS mode - Open `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.OPEN.name) smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is enabled - $modeOpen", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is enabled - $modeOpen") //LOOP STATUS : enabled - APS mode - LGS `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.LGS.name) smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is enabled - $modeLgs", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is enabled - $modeLgs") //LOOP STATUS : enabled - APS mode - unknown `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn("some wrong value") smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is enabled - $modeUnknown", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is enabled - $modeUnknown") //LOOP : wrong format `when`(loop.enabled).thenReturn(true) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //LOOP DISABLE : already disabled `when`(loop.enabled).thenReturn(false) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP DISABLE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is disabled", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP DISABLE") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is disabled") //LOOP DISABLE : from enabled hasBeenRun = false @@ -387,23 +387,23 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP DISABLE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To disable loop reply with code ")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP DISABLE") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To disable loop reply with code ") var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Loop has been disabled Temp basal canceled", smsCommunicatorPlugin.messages[3].text) - //Assertions.assertTrue(hasBeenRun) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Loop has been disabled Temp basal canceled") + //assertThat(hasBeenRun).isTrue() //LOOP ENABLE : already enabled `when`(loop.enabled).thenReturn(true) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP ENABLE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Loop is enabled", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP ENABLE") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Loop is enabled") //LOOP ENABLE : from disabled hasBeenRun = false @@ -415,14 +415,14 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP ENABLE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enable loop reply with code ")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP ENABLE") + assertThat(smsCommunicatorPlugin.messages[1].text.contains("To enable loop reply with code ")).isTrue() passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Loop has been enabled", smsCommunicatorPlugin.messages[3].text) - //Assertions.assertTrue(hasBeenRun) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Loop has been enabled") + //assertThat(hasBeenRun).isTrue() //LOOP RESUME : already enabled `when`( @@ -432,29 +432,29 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP RESUME") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP RESUME", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To resume loop reply with code ")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP RESUME") + assertThat(smsCommunicatorPlugin.messages[1].text.contains("To resume loop reply with code ")).isTrue() passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Loop resumed", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Loop resumed") //LOOP SUSPEND 1 2: wrong format smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP SUSPEND 1 2") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP SUSPEND 1 2", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP SUSPEND 1 2") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //LOOP SUSPEND 0 : wrong duration smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP SUSPEND 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP SUSPEND 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong duration", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP SUSPEND 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong duration") //LOOP SUSPEND 100 : suspend for 100 min + correct answer `when`( @@ -464,41 +464,41 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP SUSPEND 100") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP SUSPEND 100", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To suspend loop for 100 minutes reply with code ")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP SUSPEND 100") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To suspend loop for 100 minutes reply with code ") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Loop suspended Temp basal canceled", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Loop suspended Temp basal canceled") //LOOP SUSPEND 200 : limit to 180 min + wrong answer smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP SUSPEND 200") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP SUSPEND 200", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To suspend loop for 180 minutes reply with code ")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP SUSPEND 200") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To suspend loop for 180 minutes reply with code ") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! // ignore from other number smsCommunicatorPlugin.processSms(Sms("5678", passCode)) `when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.ERROR_WRONG_OTP) smsCommunicatorPlugin.processSms(Sms("1234", "XXXX")) `when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.OK) - Assertions.assertEquals("XXXX", smsCommunicatorPlugin.messages[3].text) - Assertions.assertEquals("Wrong code. Command cancelled.", smsCommunicatorPlugin.messages[4].text) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("XXXX") + assertThat(smsCommunicatorPlugin.messages[4].text).isEqualTo("Wrong code. Command cancelled.") //then correct code should not work smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[5].text) - Assertions.assertEquals(6, smsCommunicatorPlugin.messages.size.toLong()) // processed as common message + assertThat(smsCommunicatorPlugin.messages[5].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages).hasSize(6) // processed as common message //LOOP BLABLA smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "LOOP BLABLA") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("LOOP BLABLA", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("LOOP BLABLA") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //LOOP CLOSED var smsCommand = "LOOP CLOSED" @@ -508,13 +508,13 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", smsCommand) smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals(smsCommand, smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains(replyClosed)) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo(smsCommand) + assertThat(smsCommunicatorPlugin.messages[1].text).contains(replyClosed) passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Current loop mode: $modeClosed", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Current loop mode: $modeClosed") //LOOP LGS smsCommand = "LOOP LGS" @@ -523,13 +523,13 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", smsCommand) smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals(smsCommand, smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains(replyLgs)) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo(smsCommand) + assertThat(smsCommunicatorPlugin.messages[1].text).contains(replyLgs) passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Current loop mode: $modeLgs", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Current loop mode: $modeLgs") //NSCLIENT RESTART `when`(loop.isEnabled()).thenReturn(true) @@ -537,9 +537,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "NSCLIENT RESTART") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("NSCLIENT RESTART", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("NSCLIENT RESTART")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("NSCLIENT RESTART") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("NSCLIENT RESTART") //NSCLIENT BLA BLA `when`(loop.isEnabled()).thenReturn(true) @@ -547,9 +547,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "NSCLIENT BLA BLA") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("NSCLIENT BLA BLA", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("NSCLIENT BLA BLA") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //NSCLIENT BLABLA `when`(loop.isEnabled()).thenReturn(true) @@ -557,32 +557,32 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "NSCLIENT BLABLA") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("NSCLIENT BLABLA", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("NSCLIENT BLABLA") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PUMP smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PUMP", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Virtual Pump", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Virtual Pump") //PUMP CONNECT 1 2: wrong format smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP CONNECT 1 2") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("PUMP CONNECT 1 2", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP CONNECT 1 2") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PUMP CONNECT BLABLA smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP BLABLA") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("PUMP BLABLA", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP BLABLA") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PUMP CONNECT `when`( @@ -593,116 +593,116 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP CONNECT") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("PUMP CONNECT", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To connect pump reply with code ")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP CONNECT") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To connect pump reply with code ") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Pump reconnected", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Pump reconnected") //PUMP DISCONNECT 1 2: wrong format smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP DISCONNECT 1 2") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("PUMP DISCONNECT 1 2", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP DISCONNECT 1 2") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PUMP DISCONNECT 0 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP DISCONNECT 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("Wrong duration", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong duration") //PUMP DISCONNECT 30 `when`(profileFunction.getProfile()).thenReturn(validProfile) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP DISCONNECT 30") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("PUMP DISCONNECT 30", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To disconnect pump for")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP DISCONNECT 30") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To disconnect pump for") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Pump disconnected", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Pump disconnected") //PUMP DISCONNECT 30 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PUMP DISCONNECT 200") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("PUMP DISCONNECT 200", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To disconnect pump for")) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PUMP DISCONNECT 200") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To disconnect pump for") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Pump disconnected", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Pump disconnected") //HELP smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "HELP") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("HELP", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("PUMP")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("HELP") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("PUMP") //HELP PUMP smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "HELP PUMP") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("HELP PUMP", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("PUMP")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("HELP PUMP") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("PUMP") //SMS : wrong format smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "SMS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("SMS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("SMS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //SMS STOP smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "SMS DISABLE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("SMS DISABLE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To disable the SMS Remote Service reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("SMS DISABLE") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To disable the SMS Remote Service reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).contains("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.") //TARGET : wrong format smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "TARGET") smsCommunicatorPlugin.processSms(sms) - Assertions.assertFalse(sms.ignored) - Assertions.assertEquals("TARGET", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(sms.ignored).isFalse() + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("TARGET") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //TARGET MEAL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "TARGET MEAL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("TARGET MEAL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To set the Temp Target")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("TARGET MEAL") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To set the Temp Target") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("set successfully")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).contains("set successfully") //TARGET STOP/CANCEL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "TARGET STOP") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("TARGET STOP", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To cancel Temp Target reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("TARGET STOP") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To cancel Temp Target reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Temp Target canceled successfully")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).contains("Temp Target canceled successfully") } @Test fun processProfileTest() { @@ -711,23 +711,23 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("1234", "PROFILE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //PROFILE smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PROFILE LIST (no profile defined) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE LIST") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Not configured", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE LIST") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Not configured") `when`(profileSource.profile).thenReturn(getValidProfileStore()) `when`(profileFunction.getProfileName()).thenReturn(TESTPROFILENAME) @@ -736,55 +736,55 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE STATUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE STATUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals(TESTPROFILENAME, smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE STATUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo(TESTPROFILENAME) //PROFILE LIST smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE LIST") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("1. $TESTPROFILENAME", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE LIST") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("1. $TESTPROFILENAME") //PROFILE 2 (non existing) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE 2") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE 2", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE 2") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PROFILE 1 0(wrong percentage) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE 1 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE 1 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE 1 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PROFILE 0(wrong index) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //PROFILE 1(OK) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE 1") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE 1", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To switch profile to someProfile 100% reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE 1") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To switch profile to someProfile 100% reply with code") //PROFILE 1 90(OK) `when`(profileFunction.createProfileSwitch(anyObject(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), anyLong())).thenReturn(true) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE 1 90") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("PROFILE 1 90", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To switch profile to someProfile 90% reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("PROFILE 1 90") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To switch profile to someProfile 90% reply with code") val passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Profile switch created", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Profile switch created") } @Test fun processBasalTest() { @@ -793,95 +793,95 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("1234", "BASAL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //BASAL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //BASAL CANCEL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL CANCEL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL CANCEL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To stop temp basal reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL CANCEL") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To stop temp basal reply with code") var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Temp basal canceled")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).contains("Temp basal canceled") `when`(profileFunction.getProfile()).thenReturn(validProfile) //BASAL a% smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL a%") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL a%", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL a%") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //BASAL 10% 0 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL 10% 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("TBR duration must be a multiple of 30 minutes and greater than 0.", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 10% 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") //BASAL 20% 20 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL 20% 20") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("TBR duration must be a multiple of 30 minutes and greater than 0.", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 20% 20") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20)) //BASAL 20% 30 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL 20% 30") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL 20% 30", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To start basal 20% for 30 min reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 20% 30") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To start basal 20% for 30 min reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Temp basal 20% for 30 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Temp basal 20% for 30 min started successfully\nVirtual Pump") //BASAL a smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL a") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL a", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL a") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //BASAL 1 0 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL 1 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL 1 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("TBR duration must be a multiple of 30 minutes and greater than 0.", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 1 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(Constraint(1.0)) //BASAL 1 20 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL 1 20") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL 1 20", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("TBR duration must be a multiple of 30 minutes and greater than 0.", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 1 20") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(Constraint(1.0)) //BASAL 1 30 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BASAL 1 30") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BASAL 1 30", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To start basal 1.00U/h for 30 min reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 1 30") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To start basal 1.00U/h for 30 min reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Temp basal 1.00U/h for 30 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Temp basal 1.00U/h for 30 min started successfully\nVirtual Pump") } @Test fun processExtendedTest() { @@ -890,53 +890,53 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("1234", "EXTENDED") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("EXTENDED", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //EXTENDED smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "EXTENDED") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("EXTENDED", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //EXTENDED CANCEL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "EXTENDED CANCEL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("EXTENDED CANCEL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To stop extended bolus reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED CANCEL") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To stop extended bolus reply with code") var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Extended bolus canceled")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).contains("Extended bolus canceled") //EXTENDED a% smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "EXTENDED a%") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("EXTENDED a%", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED a%") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) //EXTENDED 1 0 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "EXTENDED 1 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("EXTENDED 1 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED 1 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //EXTENDED 1 20 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "EXTENDED 1 20") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("EXTENDED 1 20", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To start extended bolus 1.00U for 20 min reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED 1 20") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To start extended bolus 1.00U for 20 min reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Extended bolus 1.00U for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Extended bolus 1.00U for 20 min started successfully\nVirtual Pump") } @Test fun processBolusTest() { @@ -945,16 +945,16 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("1234", "BOLUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //BOLUS smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) `when`(dateUtilMocked.now()).thenReturn(1000L) `when`(sp.getLong(R.string.key_smscommunicator_remote_bolus_min_distance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L) @@ -962,8 +962,8 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS 1") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 1") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote bolus not available. Try again later.") `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) `when`(dateUtilMocked.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L) @@ -971,15 +971,15 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //BOLUS a smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS a") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS a", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS a") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) @@ -987,12 +987,12 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS 1") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To deliver bolus 1.00U reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 1") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To deliver bolus 1.00U reply with code") var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Bolus 1.00U delivered successfully")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).contains("Bolus 1.00U delivered successfully") //BOLUS 1 (Suspended pump) smsCommunicatorPlugin.lastRemoteBolusTime = 0 @@ -1000,28 +1000,28 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS 1") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Pump suspended", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 1") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Pump suspended") testPumpPlugin.pumpSuspended = false //BOLUS 1 a smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS 1 a") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS 1 a", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 1 a") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(profileFunction.getProfile()).thenReturn(validProfile) //BOLUS 1 MEAL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "BOLUS 1 MEAL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("BOLUS 1 MEAL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To deliver meal bolus 1.00U reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 1 MEAL") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To deliver meal bolus 1.00U reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Meal Bolus 1.00U delivered successfully\nVirtual Pump\nTarget 5.0 for 45 minutes", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Meal Bolus 1.00U delivered successfully\nVirtual Pump\nTarget 5.0 for 45 minutes") } @Test fun processCalTest() { @@ -1030,34 +1030,34 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("1234", "CAL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CAL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CAL") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //CAL smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CAL") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CAL", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CAL") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") //CAL 0 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CAL 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CAL 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CAL 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(xDripBroadcast.sendCalibration(ArgumentMatchers.anyDouble())).thenReturn(true) //CAL 1 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CAL 1") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CAL 1", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To send calibration 1.00 reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CAL 1") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To send calibration 1.00 reply with code") val passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertEquals("Calibration sent. Receiving must be enabled in xDrip.", smsCommunicatorPlugin.messages[3].text) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).isEqualTo("Calibration sent. Receiving must be enabled in xDrip.") } @Test fun processCarbsTest() { @@ -1068,80 +1068,80 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.messages = ArrayList() var sms = Sms("1234", "CARBS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote command is not allowed") `when`(sp.getBoolean(R.string.key_smscommunicator_remote_commands_allowed, false)).thenReturn(true) //CARBS smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0)) //CARBS 0 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 0") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS 0", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 0") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1)) //CARBS 1 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS 1", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enter 1g at")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 1") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To enter 1g at") var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).startsWith("Carbs 1g entered successfully") //CARBS 1 a smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1 a") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS 1 a", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 1 a") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("Wrong format") //CARBS 1 00 smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1 00") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS 1 00", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 1 00") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("Wrong format") //CARBS 1 12:01 `when`(dateUtilMocked.timeString(anyLong())).thenReturn("12:01PM") smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1 12:01") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS 1 12:01", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enter 1g at 12:01PM reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 1 12:01") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To enter 1g at 12:01PM reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).startsWith("Carbs 1g entered successfully") //CARBS 1 3:01AM `when`(dateUtilMocked.timeString(anyLong())).thenReturn("03:01AM") smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1 3:01AM") smsCommunicatorPlugin.processSms(sms) - Assertions.assertEquals("CARBS 1 3:01AM", smsCommunicatorPlugin.messages[0].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enter 1g at 03:01AM reply with code")) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 1 3:01AM") + assertThat(smsCommunicatorPlugin.messages[1].text).contains("To enter 1g at 03:01AM reply with code") passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! smsCommunicatorPlugin.processSms(Sms("1234", passCode)) - Assertions.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) - Assertions.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) + assertThat(smsCommunicatorPlugin.messages[2].text).isEqualTo(passCode) + assertThat(smsCommunicatorPlugin.messages[3].text).startsWith("Carbs 1g entered successfully") } @Test fun sendNotificationToAllNumbers() { smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.sendNotificationToAllNumbers("abc") - Assertions.assertEquals("abc", smsCommunicatorPlugin.messages[0].text) - Assertions.assertEquals("abc", smsCommunicatorPlugin.messages[1].text) + assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("abc") + assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("abc") } -} \ No newline at end of file +} From 5a19329889c1afc7364491e88b220b2cc2eafdae Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:39:01 -0700 Subject: [PATCH 18/34] Rewrites DanaPumpTest with matchers Issue #2745 --- .../src/test/java/info/nightscout/pump/dana/DanaPumpTest.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 b6c9c555d3..78e87039ed 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 @@ -1,8 +1,8 @@ package info.nightscout.pump.dana +import com.google.common.truth.Truth.assertThat import info.nightscout.interfaces.profile.Instantiator import info.nightscout.sharedtests.TestBaseWithProfile -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock @@ -21,6 +21,6 @@ class DanaPumpTest : TestBaseWithProfile() { @Test fun detectDanaRS() { sut.hwModel = 0x05 - Assertions.assertTrue(sut.modelFriendlyName().contains("DanaRS")) + assertThat(sut.modelFriendlyName()).contains("DanaRS") } -} \ No newline at end of file +} From 369c876d49b7b564847f08eb7eb0fa6f57bcab46 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:42:39 -0700 Subject: [PATCH 19/34] Rewrites DanaRsPacketBasalGetBasalRateTest with matchers Issue #2745 --- .../danars/comm/DanaRsPacketBasalGetBasalRateTest.kt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt index b80f964144..0d851e2560 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt @@ -1,9 +1,9 @@ package info.nightscout.pump.danars.comm +import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.pump.danars.DanaRSTestBase -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class DanaRsPacketBasalGetBasalRateTest : DanaRSTestBase() { @@ -28,9 +28,9 @@ class DanaRsPacketBasalGetBasalRateTest : DanaRSTestBase() { putIntToArray(array, 0, (1.0 * 100).toInt()) putByteToArray(array, 2, (0.05 * 100).toInt().toByte()) packet.handleMessage(array) - Assertions.assertEquals(1.0, danaPump.maxBasal, 0.0) - Assertions.assertEquals(0.05, danaPump.basalStep, 0.0) - Assertions.assertTrue(packet.failed) - Assertions.assertEquals("BASAL__GET_BASAL_RATE", packet.friendlyName) + assertThat(danaPump.maxBasal).isWithin(0.001).of(1.0) + assertThat(danaPump.basalStep).isWithin(0.001).of(0.05) + assertThat(packet.failed).isTrue() + assertThat(packet.friendlyName).isEqualTo("BASAL__GET_BASAL_RATE") } -} \ No newline at end of file +} From 16d0f562c741dd098ea0ddd12efbea6fc720587c Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:45:45 -0700 Subject: [PATCH 20/34] Rewrites PayloadSplitterTest with matchers Issue #2745 --- .../dash/driver/comm/message/PayloadSplitterTest.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitterTest.kt b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitterTest.kt index ad55d3edd8..ed049b88bc 100644 --- a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitterTest.kt +++ b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitterTest.kt @@ -1,9 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message +import com.google.common.truth.Truth.assertThat import com.google.crypto.tink.subtle.Hex import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.PayloadSplitter import info.nightscout.core.utils.toHex -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class PayloadSplitterTest { @@ -16,10 +16,10 @@ class PayloadSplitterTest { val splitter = PayloadSplitter(payload) val packets = splitter.splitInPackets() - Assertions.assertEquals(packets.size, 2) - Assertions.assertEquals(f1, packets[0].toByteArray().toHex()) + assertThat(packets).hasSize(2) + assertThat(packets[0].toByteArray().toHex()).isEqualTo(f1) val p2 = packets[1].toByteArray() - Assertions.assertTrue(p2.size >= 10) - Assertions.assertEquals(f2.subSequence(0, 20), p2.copyOfRange(0, 10).toHex()) + assertThat(p2.size).isAtLeast(10) + assertThat(p2.copyOfRange(0, 10).toHex()).isEqualTo(f2.subSequence(0, 20)) } } From 6606f5453eee3366e33f31d88764aaa5ef9c3895 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:48:54 -0700 Subject: [PATCH 21/34] Rewrites StatusResponseTest with matchers Issue #2745 --- .../message/response/StatusResponseTest.java | 90 +++++++++---------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/StatusResponseTest.java b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/StatusResponseTest.java index 10d7529762..8b504f49ba 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/StatusResponseTest.java +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/StatusResponseTest.java @@ -1,8 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response; -import org.joda.time.Duration; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryStatus; @@ -10,6 +8,9 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Om import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.pump.core.utils.ByteUtil; +import org.joda.time.Duration; +import org.junit.jupiter.api.Test; + class StatusResponseTest { @Test @@ -18,7 +19,7 @@ class StatusResponseTest { StatusResponse statusResponse = new StatusResponse(encodedData); - Assertions.assertArrayEquals(encodedData, statusResponse.getRawData()); + assertThat(statusResponse.getRawData()).isEqualTo(encodedData); } @Test @@ -28,7 +29,7 @@ class StatusResponseTest { StatusResponse statusResponse = new StatusResponse(encodedData); - Assertions.assertArrayEquals(expected, statusResponse.getRawData()); + assertThat(statusResponse.getRawData()).isEqualTo(expected); } @Test @@ -36,17 +37,17 @@ class StatusResponseTest { byte[] bytes = ByteUtil.fromHexString("1d180258f80000146fff"); // From https://github.com/openaps/openomni/wiki/Command-1D-Status-response StatusResponse statusResponse = new StatusResponse(bytes); - Assertions.assertEquals(DeliveryStatus.NORMAL, statusResponse.getDeliveryStatus()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, statusResponse.getPodProgressStatus()); - Assertions.assertNull(statusResponse.getReservoirLevel()); - Assertions.assertEquals(Duration.standardMinutes(1307).getMillis(), statusResponse.getTimeActive().getMillis()); - Assertions.assertEquals(1201, statusResponse.getTicksDelivered()); - Assertions.assertEquals(60.05, statusResponse.getInsulinDelivered(), 0.000001); - Assertions.assertEquals(15, statusResponse.getPodMessageCounter()); - Assertions.assertEquals(0, statusResponse.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(0, statusResponse.getUnacknowledgedAlerts().getAlertSlots().size()); + assertThat(statusResponse.getDeliveryStatus()).isEqualTo(DeliveryStatus.NORMAL); + assertThat(statusResponse.getPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(statusResponse.getReservoirLevel()).isNull(); + assertThat(statusResponse.getTimeActive().getMillis()).isEqualTo(Duration.standardMinutes(1307).getMillis()); + assertThat(statusResponse.getTicksDelivered()).isEqualTo(1201); + assertThat(statusResponse.getInsulinDelivered()).isWithin(0.000001).of(60.05); + assertThat(statusResponse.getPodMessageCounter()).isEqualTo(15); + assertThat(statusResponse.getBolusNotDelivered()).isWithin(0.000001).of(0); + assertThat(statusResponse.getUnacknowledgedAlerts().getAlertSlots()).isEmpty(); - Assertions.assertArrayEquals(ByteUtil.fromHexString("1d180258f80000146fff"), statusResponse.getRawData()); + assertThat(statusResponse.getRawData()).isEqualTo(ByteUtil.fromHexString("1d180258f80000146fff")); } @Test @@ -54,18 +55,17 @@ class StatusResponseTest { byte[] bytes = ByteUtil.fromHexString("1d19061f6800044295e8"); // From https://github.com/openaps/openomni/wiki/Status-Response-1D-long-run-%28Lytrix%29 StatusResponse statusResponse = new StatusResponse(bytes); - Assertions.assertEquals(DeliveryStatus.NORMAL, statusResponse.getDeliveryStatus()); - Assertions.assertEquals(PodProgressStatus.FIFTY_OR_LESS_UNITS, statusResponse.getPodProgressStatus()); - Assertions.assertEquals(24.4, statusResponse.getReservoirLevel(), 0.000001); - Assertions.assertEquals(Duration.standardMinutes(4261).getMillis(), statusResponse.getTimeActive().getMillis()); - Assertions.assertEquals(3134, statusResponse.getTicksDelivered()); - Assertions.assertEquals(156.7, statusResponse.getInsulinDelivered(), 0.000001); - Assertions.assertEquals(13, statusResponse.getPodMessageCounter()); - Assertions.assertEquals(0, statusResponse.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(1, statusResponse.getUnacknowledgedAlerts().getAlertSlots().size()); - Assertions.assertEquals(AlertSlot.SLOT3, statusResponse.getUnacknowledgedAlerts().getAlertSlots().get(0)); + assertThat(statusResponse.getDeliveryStatus()).isEqualTo(DeliveryStatus.NORMAL); + assertThat(statusResponse.getPodProgressStatus()).isEqualTo(PodProgressStatus.FIFTY_OR_LESS_UNITS); + assertThat(statusResponse.getReservoirLevel()).isWithin(0.000001).of(24.4); + assertThat(statusResponse.getTimeActive().getMillis()).isEqualTo(Duration.standardMinutes(4261).getMillis()); + assertThat(statusResponse.getTicksDelivered()).isEqualTo(3134); + assertThat(statusResponse.getInsulinDelivered()).isWithin(0.000001).of(156.7); + assertThat(statusResponse.getPodMessageCounter()).isEqualTo(13); + assertThat(statusResponse.getBolusNotDelivered()).isWithin(0.000001).of(0); + assertThat(statusResponse.getUnacknowledgedAlerts().getAlertSlots()).containsExactly(AlertSlot.SLOT3); - Assertions.assertArrayEquals(ByteUtil.fromHexString("1d19061f6800044295e8"), statusResponse.getRawData()); + assertThat(statusResponse.getRawData()).isEqualTo(ByteUtil.fromHexString("1d19061f6800044295e8")); } @Test @@ -73,16 +73,16 @@ class StatusResponseTest { byte[] bytes = ByteUtil.fromHexString("1d11ffffffffffffffff"); StatusResponse statusResponse = new StatusResponse(bytes); - Assertions.assertEquals(Duration.standardMinutes(8191).getMillis(), statusResponse.getTimeActive().getMillis()); - Assertions.assertEquals(OmnipodConstants.POD_PULSE_SIZE * 1023, statusResponse.getBolusNotDelivered(), 0.000001); - Assertions.assertNull(statusResponse.getReservoirLevel()); - Assertions.assertEquals(OmnipodConstants.POD_PULSE_SIZE * 8191, statusResponse.getInsulinDelivered(), 0.0000001); - Assertions.assertEquals(8191, statusResponse.getTicksDelivered()); - Assertions.assertEquals(OmnipodConstants.POD_PULSE_SIZE * 8191, statusResponse.getInsulinDelivered(), 0.0000001); - Assertions.assertEquals(15, statusResponse.getPodMessageCounter()); - Assertions.assertEquals(8, statusResponse.getUnacknowledgedAlerts().getAlertSlots().size()); + assertThat(statusResponse.getTimeActive().getMillis()).isEqualTo(Duration.standardMinutes(8191).getMillis()); + assertThat(statusResponse.getBolusNotDelivered()).isWithin(0.000001).of(OmnipodConstants.POD_PULSE_SIZE * 1023); + assertThat(statusResponse.getReservoirLevel()).isNull(); + assertThat(statusResponse.getInsulinDelivered()).isWithin(0.0000001).of(OmnipodConstants.POD_PULSE_SIZE * 8191); + assertThat(statusResponse.getTicksDelivered()).isEqualTo(8191); + assertThat(statusResponse.getInsulinDelivered()).isWithin(0.0000001).of(OmnipodConstants.POD_PULSE_SIZE * 8191); + assertThat(statusResponse.getPodMessageCounter()).isEqualTo(15); + assertThat(statusResponse.getUnacknowledgedAlerts().getAlertSlots()).hasSize(8); - Assertions.assertArrayEquals(ByteUtil.fromHexString("1d11ffffffffffffffff"), statusResponse.getRawData()); + assertThat(statusResponse.getRawData()).isEqualTo(ByteUtil.fromHexString("1d11ffffffffffffffff")); } @Test @@ -90,15 +90,15 @@ class StatusResponseTest { byte[] bytes = ByteUtil.fromHexString("1d19050ec82c08376f98"); StatusResponse statusResponse = new StatusResponse(bytes); - Assertions.assertTrue(Duration.standardMinutes(3547).isEqual(statusResponse.getTimeActive())); - Assertions.assertEquals(DeliveryStatus.NORMAL, statusResponse.getDeliveryStatus()); - Assertions.assertEquals(PodProgressStatus.FIFTY_OR_LESS_UNITS, statusResponse.getPodProgressStatus()); - Assertions.assertEquals(2589, statusResponse.getTicksDelivered()); - Assertions.assertEquals(129.45, statusResponse.getInsulinDelivered(), 0.00001); - Assertions.assertEquals(46.00, statusResponse.getReservoirLevel(), 0.00001); - Assertions.assertEquals(2.2, statusResponse.getBolusNotDelivered(), 0.0001); - Assertions.assertEquals(9, statusResponse.getPodMessageCounter()); + assertThat(statusResponse.getTimeActive()).isEqualTo(Duration.standardMinutes(3547)); + assertThat(statusResponse.getDeliveryStatus()).isEqualTo(DeliveryStatus.NORMAL); + assertThat(statusResponse.getPodProgressStatus()).isEqualTo(PodProgressStatus.FIFTY_OR_LESS_UNITS); + assertThat(statusResponse.getTicksDelivered()).isEqualTo(2589); + assertThat(statusResponse.getInsulinDelivered()).isWithin(0.00001).of(129.45); + assertThat(statusResponse.getReservoirLevel()).isWithin(0.00001).of(46.00); + assertThat(statusResponse.getBolusNotDelivered()).isWithin(0.0001).of(2.2); + assertThat(statusResponse.getPodMessageCounter()).isEqualTo(9); - Assertions.assertArrayEquals(ByteUtil.fromHexString("1d19050ec82c08376f98"), statusResponse.getRawData()); + assertThat(statusResponse.getRawData()).isEqualTo(ByteUtil.fromHexString("1d19050ec82c08376f98")); } -} \ No newline at end of file +} From 19d2f9635afa2b59dabc10eb761431967789da6d Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:49:32 -0700 Subject: [PATCH 22/34] Rewrites PodInfoActiveAlertsTest with matchers Issue #2745 --- .../response/podinfo/PodInfoActiveAlertsTest.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoActiveAlertsTest.java b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoActiveAlertsTest.java index cca0912812..60bb39e6cc 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoActiveAlertsTest.java +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoActiveAlertsTest.java @@ -1,7 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo; +import static com.google.common.truth.Truth.assertThat; + import org.joda.time.Duration; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; @@ -15,7 +16,7 @@ class PodInfoActiveAlertsTest { PodInfoActiveAlerts podInfoActiveAlerts = new PodInfoActiveAlerts(encodedMessage); List alertActivations = podInfoActiveAlerts.getAlertActivations(); - Assertions.assertEquals(0, alertActivations.size()); + assertThat(alertActivations).isEmpty(); } @Test @@ -24,10 +25,10 @@ class PodInfoActiveAlertsTest { PodInfoActiveAlerts podInfoActiveAlerts = new PodInfoActiveAlerts(encodedMessage); List alertActivations = podInfoActiveAlerts.getAlertActivations(); - Assertions.assertEquals(1, alertActivations.size()); + assertThat(alertActivations).hasSize(1); PodInfoActiveAlerts.AlertActivation alertActivation = alertActivations.get(0); Duration expectedDuration = Duration.standardHours(72).plus(Duration.standardMinutes(1)); - Assertions.assertTrue(expectedDuration.isEqual(alertActivation.getValueAsDuration())); + assertThat(expectedDuration).isEqualTo(alertActivation.getValueAsDuration()); } } From 3d384c7db561df90d339108e7fc131fe267d4795 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:52:47 -0700 Subject: [PATCH 23/34] Rewrites PodInfoDataLogTest with matchers Issue #2745 --- .../response/podinfo/PodInfoDataLogTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDataLogTest.java b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDataLogTest.java index 2e5f99f6c3..2f1211ea9f 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDataLogTest.java +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDataLogTest.java @@ -1,9 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo; -import org.joda.time.Duration; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; +import org.joda.time.Duration; +import org.junit.jupiter.api.Test; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.pump.core.utils.ByteUtil; @@ -12,10 +12,10 @@ class PodInfoDataLogTest { void testDecoding() { PodInfoDataLog podInfoDataLog = new PodInfoDataLog(ByteUtil.fromHexString("030100010001043c"), 8); // From https://github.com/ps2/rileylink_ios/blob/omnipod-testing/OmniKitTests/PodInfoTests.swift - Assertions.assertEquals(FaultEventCode.FAILED_FLASH_ERASE, podInfoDataLog.getFaultEventCode()); - Assertions.assertTrue(Duration.standardMinutes(1).isEqual(podInfoDataLog.getTimeFaultEvent())); - Assertions.assertTrue(Duration.standardMinutes(1).isEqual(podInfoDataLog.getTimeSinceActivation())); - Assertions.assertEquals(4, podInfoDataLog.getDataChunkSize()); - Assertions.assertEquals(60, podInfoDataLog.getMaximumNumberOfDwords()); + assertThat(podInfoDataLog.getFaultEventCode()).isEqualTo(FaultEventCode.FAILED_FLASH_ERASE); + assertThat(podInfoDataLog.getTimeFaultEvent()).isEqualTo(Duration.standardMinutes(1)); + assertThat(podInfoDataLog.getTimeSinceActivation()).isEqualTo(Duration.standardMinutes(1)); + assertThat(podInfoDataLog.getDataChunkSize()).isEqualTo(4); + assertThat(podInfoDataLog.getMaximumNumberOfDwords()).isEqualTo(60); } } From 29113520c2bafa9445e55c26d1a49c290c76880c Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:53:50 -0700 Subject: [PATCH 24/34] Rewrites PodInfoDetailedStatusTest with matchers Issue #2745 --- .../podinfo/PodInfoDetailedStatusTest.java | 210 +++++++++--------- 1 file changed, 105 insertions(+), 105 deletions(-) diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatusTest.java b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatusTest.java index 3eb40e127b..de080d81eb 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatusTest.java +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatusTest.java @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo; -import org.joda.time.Duration; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryStatus; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ErrorEventInfo; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus; import info.nightscout.pump.core.utils.ByteUtil; +import org.joda.time.Duration; +import org.junit.jupiter.api.Test; /** * @noinspection SpellCheckingInspection @@ -18,143 +18,143 @@ class PodInfoDetailedStatusTest { void testPodInfoFaultEventNoFaultAlerts() { PodInfoDetailedStatus podInfoDetailedStatus = new PodInfoDetailedStatus(ByteUtil.fromHexString("02080100000a003800000003ff008700000095ff0000")); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, podInfoDetailedStatus.getPodProgressStatus()); - Assertions.assertEquals(DeliveryStatus.NORMAL, podInfoDetailedStatus.getDeliveryStatus()); - Assertions.assertEquals(0, podInfoDetailedStatus.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(0x0a, podInfoDetailedStatus.getPodMessageCounter()); - Assertions.assertNull(podInfoDetailedStatus.getFaultEventCode()); - Assertions.assertTrue(Duration.ZERO.isEqual(podInfoDetailedStatus.getFaultEventTime())); - Assertions.assertNull(podInfoDetailedStatus.getReservoirLevel()); - Assertions.assertTrue(Duration.standardSeconds(8100).isEqual(podInfoDetailedStatus.getTimeActive())); - Assertions.assertEquals(0, podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()); - Assertions.assertFalse(podInfoDetailedStatus.isFaultAccessingTables()); + assertThat(podInfoDetailedStatus.getPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getDeliveryStatus()).isEqualTo(DeliveryStatus.NORMAL); + assertThat(podInfoDetailedStatus.getBolusNotDelivered()).isWithin(0.000001).of(0); + assertThat(podInfoDetailedStatus.getPodMessageCounter()).isEqualTo(0x0a); + assertThat(podInfoDetailedStatus.getFaultEventCode()).isNull(); + assertThat(podInfoDetailedStatus.getFaultEventTime()).isEqualTo(Duration.ZERO); + assertThat(podInfoDetailedStatus.getReservoirLevel()).isNull(); + assertThat(podInfoDetailedStatus.getTimeActive()).isEqualTo(Duration.standardSeconds(8100)); + assertThat(podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()).isEqualTo(0); + assertThat(podInfoDetailedStatus.isFaultAccessingTables()).isFalse(); ErrorEventInfo errorEventInfo = podInfoDetailedStatus.getErrorEventInfo(); - Assertions.assertNull(errorEventInfo); - Assertions.assertNull(podInfoDetailedStatus.getPreviousPodProgressStatus()); - Assertions.assertEquals(2, podInfoDetailedStatus.getReceiverLowGain()); - Assertions.assertEquals(21, podInfoDetailedStatus.getRadioRSSI()); + assertThat(errorEventInfo).isNull(); + assertThat(podInfoDetailedStatus.getPreviousPodProgressStatus()).isNull(); + assertThat(podInfoDetailedStatus.getReceiverLowGain()).isEqualTo(2); + assertThat(podInfoDetailedStatus.getRadioRSSI()).isEqualTo(21); } @Test void testPodInfoFaultEventDeliveryErrorDuringPriming() { PodInfoDetailedStatus podInfoDetailedStatus = new PodInfoDetailedStatus(ByteUtil.fromHexString("020f0000000900345c000103ff0001000005ae056029")); - Assertions.assertEquals(PodProgressStatus.INACTIVE, podInfoDetailedStatus.getPodProgressStatus()); - Assertions.assertEquals(DeliveryStatus.SUSPENDED, podInfoDetailedStatus.getDeliveryStatus()); - Assertions.assertEquals(0, podInfoDetailedStatus.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(0x09, podInfoDetailedStatus.getPodMessageCounter()); - Assertions.assertEquals(FaultEventCode.PRIME_OPEN_COUNT_TOO_LOW, podInfoDetailedStatus.getFaultEventCode()); - Assertions.assertTrue(Duration.standardSeconds(60).isEqual(podInfoDetailedStatus.getFaultEventTime())); - Assertions.assertNull(podInfoDetailedStatus.getReservoirLevel()); - Assertions.assertTrue(Duration.standardSeconds(60).isEqual(podInfoDetailedStatus.getTimeActive())); - Assertions.assertEquals(0, podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()); - Assertions.assertFalse(podInfoDetailedStatus.isFaultAccessingTables()); + assertThat(podInfoDetailedStatus.getPodProgressStatus()).isEqualTo(PodProgressStatus.INACTIVE); + assertThat(podInfoDetailedStatus.getDeliveryStatus()).isEqualTo(DeliveryStatus.SUSPENDED); + assertThat(podInfoDetailedStatus.getBolusNotDelivered()).isWithin(0.000001).of(0); + assertThat(podInfoDetailedStatus.getPodMessageCounter()).isEqualTo(0x09); + assertThat(podInfoDetailedStatus.getFaultEventCode()).isEqualTo(FaultEventCode.PRIME_OPEN_COUNT_TOO_LOW); + assertThat(podInfoDetailedStatus.getFaultEventTime()).isEqualTo(Duration.standardSeconds(60)); + assertThat(podInfoDetailedStatus.getReservoirLevel()).isNull(); + assertThat(podInfoDetailedStatus.getTimeActive()).isEqualTo(Duration.standardSeconds(60)); + assertThat(podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()).isEqualTo(0); + assertThat(podInfoDetailedStatus.isFaultAccessingTables()).isFalse(); ErrorEventInfo errorEventInfo = podInfoDetailedStatus.getErrorEventInfo(); - Assertions.assertFalse(errorEventInfo.isInsulinStateTableCorruption()); - Assertions.assertEquals(0x00, errorEventInfo.getInternalVariable()); - Assertions.assertFalse(errorEventInfo.isImmediateBolusInProgress()); - Assertions.assertEquals(PodProgressStatus.PRIMING_COMPLETED, errorEventInfo.getPodProgressStatus()); - Assertions.assertEquals(PodProgressStatus.PRIMING_COMPLETED, podInfoDetailedStatus.getPreviousPodProgressStatus()); - Assertions.assertEquals(2, podInfoDetailedStatus.getReceiverLowGain()); - Assertions.assertEquals(46, podInfoDetailedStatus.getRadioRSSI()); + assertThat(errorEventInfo.isInsulinStateTableCorruption()).isFalse(); + assertThat(errorEventInfo.getInternalVariable()).isEqualTo(0x00); + assertThat(errorEventInfo.isImmediateBolusInProgress()).isFalse(); + assertThat(errorEventInfo.getPodProgressStatus()).isEqualTo(PodProgressStatus.PRIMING_COMPLETED); + assertThat(podInfoDetailedStatus.getPreviousPodProgressStatus()).isEqualTo(PodProgressStatus.PRIMING_COMPLETED); + assertThat(podInfoDetailedStatus.getReceiverLowGain()).isEqualTo(2); + assertThat(podInfoDetailedStatus.getRadioRSSI()).isEqualTo(46); } @Test void testPodInfoFaultEventErrorShuttingDown() { PodInfoDetailedStatus podInfoDetailedStatus = new PodInfoDetailedStatus(ByteUtil.fromHexString("020d0000000407f28609ff03ff0a0200000823080000")); - Assertions.assertEquals(PodProgressStatus.FAULT_EVENT_OCCURRED, podInfoDetailedStatus.getPodProgressStatus()); - Assertions.assertEquals(DeliveryStatus.SUSPENDED, podInfoDetailedStatus.getDeliveryStatus()); - Assertions.assertEquals(2034, podInfoDetailedStatus.getTicksDelivered()); - Assertions.assertEquals(101.7, podInfoDetailedStatus.getInsulinDelivered(), 0.000001); - Assertions.assertEquals(0, podInfoDetailedStatus.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(0x04, podInfoDetailedStatus.getPodMessageCounter()); - Assertions.assertEquals(FaultEventCode.BASAL_OVER_INFUSION_PULSE, podInfoDetailedStatus.getFaultEventCode()); - Assertions.assertTrue(Duration.standardMinutes(2559).isEqual(podInfoDetailedStatus.getFaultEventTime())); - Assertions.assertNull(podInfoDetailedStatus.getReservoirLevel()); - Assertions.assertEquals(0, podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()); - Assertions.assertFalse(podInfoDetailedStatus.isFaultAccessingTables()); + assertThat(podInfoDetailedStatus.getPodProgressStatus()).isEqualTo(PodProgressStatus.FAULT_EVENT_OCCURRED); + assertThat(podInfoDetailedStatus.getDeliveryStatus()).isEqualTo(DeliveryStatus.SUSPENDED); + assertThat(podInfoDetailedStatus.getTicksDelivered()).isEqualTo(2034); + assertThat(podInfoDetailedStatus.getInsulinDelivered()).isWithin(0.000001).of(101.7); + assertThat(podInfoDetailedStatus.getBolusNotDelivered()).isWithin(0.000001).of(0); + assertThat(podInfoDetailedStatus.getPodMessageCounter()).isEqualTo(0x04); + assertThat(podInfoDetailedStatus.getFaultEventCode()).isEqualTo(FaultEventCode.BASAL_OVER_INFUSION_PULSE); + assertThat(podInfoDetailedStatus.getFaultEventTime()).isEqualTo(Duration.standardMinutes(2559)); + assertThat(podInfoDetailedStatus.getReservoirLevel()).isNull(); + assertThat(podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()).isEqualTo(0); + assertThat(podInfoDetailedStatus.isFaultAccessingTables()).isFalse(); ErrorEventInfo errorEventInfo = podInfoDetailedStatus.getErrorEventInfo(); - Assertions.assertFalse(errorEventInfo.isInsulinStateTableCorruption()); - Assertions.assertEquals(0x00, errorEventInfo.getInternalVariable()); - Assertions.assertFalse(errorEventInfo.isImmediateBolusInProgress()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, errorEventInfo.getPodProgressStatus()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, podInfoDetailedStatus.getPreviousPodProgressStatus()); - Assertions.assertEquals(0, podInfoDetailedStatus.getReceiverLowGain()); - Assertions.assertEquals(35, podInfoDetailedStatus.getRadioRSSI()); + assertThat(errorEventInfo.isInsulinStateTableCorruption()).isFalse(); + assertThat(errorEventInfo.getInternalVariable()).isEqualTo(0x00); + assertThat(errorEventInfo.isImmediateBolusInProgress()).isFalse(); + assertThat(errorEventInfo.getPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getPreviousPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getReceiverLowGain()).isEqualTo(0); + assertThat(podInfoDetailedStatus.getRadioRSSI()).isEqualTo(35); } @Test void testPodInfoFaultEventInsulinNotDelivered() { PodInfoDetailedStatus podInfoDetailedStatus = new PodInfoDetailedStatus(ByteUtil.fromHexString("020f0000010200ec6a026803ff026b000028a7082023")); - Assertions.assertEquals(PodProgressStatus.INACTIVE, podInfoDetailedStatus.getPodProgressStatus()); - Assertions.assertEquals(DeliveryStatus.SUSPENDED, podInfoDetailedStatus.getDeliveryStatus()); - Assertions.assertEquals(236, podInfoDetailedStatus.getTicksDelivered()); - Assertions.assertEquals(11.8, podInfoDetailedStatus.getInsulinDelivered(), 0.000001); - Assertions.assertEquals(0.05, podInfoDetailedStatus.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(0x02, podInfoDetailedStatus.getPodMessageCounter()); - Assertions.assertEquals(FaultEventCode.OCCLUSION_CHECK_ABOVE_THRESHOLD, podInfoDetailedStatus.getFaultEventCode()); - Assertions.assertTrue(Duration.standardMinutes(616).isEqual(podInfoDetailedStatus.getFaultEventTime())); - Assertions.assertNull(podInfoDetailedStatus.getReservoirLevel()); - Assertions.assertEquals(0, podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()); - Assertions.assertFalse(podInfoDetailedStatus.isFaultAccessingTables()); + assertThat(podInfoDetailedStatus.getPodProgressStatus()).isEqualTo(PodProgressStatus.INACTIVE); + assertThat(podInfoDetailedStatus.getDeliveryStatus()).isEqualTo(DeliveryStatus.SUSPENDED); + assertThat(podInfoDetailedStatus.getTicksDelivered()).isEqualTo(236); + assertThat(podInfoDetailedStatus.getInsulinDelivered()).isWithin(0.000001).of(11.8); + assertThat(podInfoDetailedStatus.getBolusNotDelivered()).isWithin(0.000001).of(0.05); + assertThat(podInfoDetailedStatus.getPodMessageCounter()).isEqualTo(0x02); + assertThat(podInfoDetailedStatus.getFaultEventCode()).isEqualTo(FaultEventCode.OCCLUSION_CHECK_ABOVE_THRESHOLD); + assertThat(podInfoDetailedStatus.getFaultEventTime()).isEqualTo(Duration.standardMinutes(616)); + assertThat(podInfoDetailedStatus.getReservoirLevel()).isNull(); + assertThat(podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()).isEqualTo(0); + assertThat(podInfoDetailedStatus.isFaultAccessingTables()).isFalse(); ErrorEventInfo errorEventInfo = podInfoDetailedStatus.getErrorEventInfo(); - Assertions.assertFalse(errorEventInfo.isInsulinStateTableCorruption()); - Assertions.assertEquals(0x01, errorEventInfo.getInternalVariable()); - Assertions.assertFalse(errorEventInfo.isImmediateBolusInProgress()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, errorEventInfo.getPodProgressStatus()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, podInfoDetailedStatus.getPreviousPodProgressStatus()); - Assertions.assertEquals(2, podInfoDetailedStatus.getReceiverLowGain()); - Assertions.assertEquals(39, podInfoDetailedStatus.getRadioRSSI()); + assertThat(errorEventInfo.isInsulinStateTableCorruption()).isFalse(); + assertThat(errorEventInfo.getInternalVariable()).isEqualTo(0x01); + assertThat(errorEventInfo.isImmediateBolusInProgress()).isFalse(); + assertThat(errorEventInfo.getPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getPreviousPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getReceiverLowGain()).isEqualTo(2); + assertThat(podInfoDetailedStatus.getRadioRSSI()).isEqualTo(39); } @Test void testPodInfoFaultEventMaxBolusNotDelivered() { PodInfoDetailedStatus podInfoDetailedStatus = new PodInfoDetailedStatus(ByteUtil.fromHexString("020f00ffff0200ec6a026803ff026b000028a7082023")); - Assertions.assertEquals(PodProgressStatus.INACTIVE, podInfoDetailedStatus.getPodProgressStatus()); - Assertions.assertEquals(DeliveryStatus.SUSPENDED, podInfoDetailedStatus.getDeliveryStatus()); - Assertions.assertEquals(236, podInfoDetailedStatus.getTicksDelivered()); - Assertions.assertEquals(11.8, podInfoDetailedStatus.getInsulinDelivered(), 0.000001); - Assertions.assertEquals(3276.75, podInfoDetailedStatus.getBolusNotDelivered(), 0.000001); // Insane and will not happen, but this verifies that we convert it to an unsigned int - Assertions.assertEquals(0x02, podInfoDetailedStatus.getPodMessageCounter()); - Assertions.assertEquals(FaultEventCode.OCCLUSION_CHECK_ABOVE_THRESHOLD, podInfoDetailedStatus.getFaultEventCode()); - Assertions.assertTrue(Duration.standardMinutes(616).isEqual(podInfoDetailedStatus.getFaultEventTime())); - Assertions.assertNull(podInfoDetailedStatus.getReservoirLevel()); - Assertions.assertEquals(0, podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()); - Assertions.assertFalse(podInfoDetailedStatus.isFaultAccessingTables()); + assertThat(podInfoDetailedStatus.getPodProgressStatus()).isEqualTo(PodProgressStatus.INACTIVE); + assertThat(podInfoDetailedStatus.getDeliveryStatus()).isEqualTo(DeliveryStatus.SUSPENDED); + assertThat(podInfoDetailedStatus.getTicksDelivered()).isEqualTo(236); + assertThat(podInfoDetailedStatus.getInsulinDelivered()).isWithin(0.000001).of(11.8); + assertThat(podInfoDetailedStatus.getBolusNotDelivered()).isWithin(0.000001).of(3276.75); // Insane and will not happen, but this verifies that we convert it to an unsigned int + assertThat(podInfoDetailedStatus.getPodMessageCounter()).isEqualTo(0x02); + assertThat(podInfoDetailedStatus.getFaultEventCode()).isEqualTo(FaultEventCode.OCCLUSION_CHECK_ABOVE_THRESHOLD); + assertThat(podInfoDetailedStatus.getFaultEventTime()).isEqualTo(Duration.standardMinutes(616)); + assertThat(podInfoDetailedStatus.getReservoirLevel()).isNull(); + assertThat(podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()).isEqualTo(0); + assertThat(podInfoDetailedStatus.isFaultAccessingTables()).isFalse(); ErrorEventInfo errorEventInfo = podInfoDetailedStatus.getErrorEventInfo(); - Assertions.assertFalse(errorEventInfo.isInsulinStateTableCorruption()); - Assertions.assertEquals(0x01, errorEventInfo.getInternalVariable()); - Assertions.assertFalse(errorEventInfo.isImmediateBolusInProgress()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, errorEventInfo.getPodProgressStatus()); - Assertions.assertEquals(PodProgressStatus.ABOVE_FIFTY_UNITS, podInfoDetailedStatus.getPreviousPodProgressStatus()); - Assertions.assertEquals(2, podInfoDetailedStatus.getReceiverLowGain()); - Assertions.assertEquals(39, podInfoDetailedStatus.getRadioRSSI()); + assertThat(errorEventInfo.isInsulinStateTableCorruption()).isFalse(); + assertThat(errorEventInfo.getInternalVariable()).isEqualTo(0x01); + assertThat(errorEventInfo.isImmediateBolusInProgress()).isFalse(); + assertThat(errorEventInfo.getPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getPreviousPodProgressStatus()).isEqualTo(PodProgressStatus.ABOVE_FIFTY_UNITS); + assertThat(podInfoDetailedStatus.getReceiverLowGain()).isEqualTo(2); + assertThat(podInfoDetailedStatus.getRadioRSSI()).isEqualTo(39); } @Test void testPodInfoFaultEventInsulinStateTableCorruptionFoundDuringErrorLogging() { PodInfoDetailedStatus podInfoDetailedStatus = new PodInfoDetailedStatus(ByteUtil.fromHexString("020D00000000000012FFFF03FF00160000879A070000")); - Assertions.assertEquals(PodProgressStatus.FAULT_EVENT_OCCURRED, podInfoDetailedStatus.getPodProgressStatus()); - Assertions.assertEquals(DeliveryStatus.SUSPENDED, podInfoDetailedStatus.getDeliveryStatus()); - Assertions.assertEquals(0, podInfoDetailedStatus.getBolusNotDelivered(), 0.000001); - Assertions.assertEquals(0x00, podInfoDetailedStatus.getPodMessageCounter()); - Assertions.assertEquals(FaultEventCode.RESET_DUE_TO_LVD, podInfoDetailedStatus.getFaultEventCode()); - Assertions.assertTrue(Duration.ZERO.isEqual(podInfoDetailedStatus.getFaultEventTime())); - Assertions.assertNull(podInfoDetailedStatus.getReservoirLevel()); - Assertions.assertTrue(Duration.standardSeconds(1320).isEqual(podInfoDetailedStatus.getTimeActive())); - Assertions.assertEquals(0, podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()); - Assertions.assertFalse(podInfoDetailedStatus.isFaultAccessingTables()); + assertThat(podInfoDetailedStatus.getPodProgressStatus()).isEqualTo(PodProgressStatus.FAULT_EVENT_OCCURRED); + assertThat(podInfoDetailedStatus.getDeliveryStatus()).isEqualTo(DeliveryStatus.SUSPENDED); + assertThat(podInfoDetailedStatus.getBolusNotDelivered()).isWithin(0.000001).of(0); + assertThat(podInfoDetailedStatus.getPodMessageCounter()).isEqualTo(0x00); + assertThat(podInfoDetailedStatus.getFaultEventCode()).isEqualTo(FaultEventCode.RESET_DUE_TO_LVD); + assertThat(podInfoDetailedStatus.getFaultEventTime()).isNull(); + assertThat(podInfoDetailedStatus.getReservoirLevel()).isNull(); + assertThat(podInfoDetailedStatus.getTimeActive()).isEqualTo(Duration.standardSeconds(1320)); + assertThat(podInfoDetailedStatus.getUnacknowledgedAlerts().getRawValue()).isEqualTo(0); + assertThat(podInfoDetailedStatus.isFaultAccessingTables()).isFalse(); ErrorEventInfo errorEventInfo = podInfoDetailedStatus.getErrorEventInfo(); - Assertions.assertTrue(errorEventInfo.isInsulinStateTableCorruption()); - Assertions.assertEquals(0x00, errorEventInfo.getInternalVariable()); - Assertions.assertFalse(errorEventInfo.isImmediateBolusInProgress()); - Assertions.assertEquals(PodProgressStatus.INSERTING_CANNULA, errorEventInfo.getPodProgressStatus()); - Assertions.assertEquals(PodProgressStatus.INSERTING_CANNULA, podInfoDetailedStatus.getPreviousPodProgressStatus()); - Assertions.assertEquals(2, podInfoDetailedStatus.getReceiverLowGain()); - Assertions.assertEquals(26, podInfoDetailedStatus.getRadioRSSI()); + assertThat(errorEventInfo.isInsulinStateTableCorruption()).isTrue(); + assertThat(errorEventInfo.getInternalVariable()).isEqualTo(0x00); + assertThat(errorEventInfo.isImmediateBolusInProgress()).isFalse(); + assertThat(errorEventInfo.getPodProgressStatus()).isEqualTo(PodProgressStatus.INSERTING_CANNULA); + assertThat(podInfoDetailedStatus.getPreviousPodProgressStatus()).isEqualTo(PodProgressStatus.INSERTING_CANNULA); + assertThat(podInfoDetailedStatus.getReceiverLowGain()).isEqualTo(2); + assertThat(podInfoDetailedStatus.getRadioRSSI()).isEqualTo(26); } } From 36ce238cc96d1bff8304b4dbb2b26a55bd2fefa7 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:55:14 -0700 Subject: [PATCH 25/34] Rewrites PodInfoFaultAndInitializationTimeTest with matchers Issue #2745 --- ...PodInfoFaultAndInitializationTimeTest.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoFaultAndInitializationTimeTest.java b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoFaultAndInitializationTimeTest.java index 68e4f82eee..6259a7e17c 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoFaultAndInitializationTimeTest.java +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoFaultAndInitializationTimeTest.java @@ -1,26 +1,26 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo; -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +import static com.google.common.truth.Truth.assertThat; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FaultEventCode; import info.nightscout.pump.core.utils.ByteUtil; +import org.joda.time.DateTime; +import org.joda.time.Duration; +import org.junit.jupiter.api.Test; class PodInfoFaultAndInitializationTimeTest { @Test void testDecoding() { PodInfoFaultAndInitializationTime podInfoFaultAndInitializationTime = new PodInfoFaultAndInitializationTime(ByteUtil.fromHexString("059200010000000000000000091912170e")); // From https://github.com/ps2/rileylink_ios/blob/omnipod-testing/OmniKitTests/PodInfoTests.swift - Assertions.assertEquals(FaultEventCode.BAD_PUMP_REQ_2_STATE, podInfoFaultAndInitializationTime.getFaultEventCode()); - Assertions.assertTrue(Duration.standardMinutes(1).isEqual(podInfoFaultAndInitializationTime.getTimeFaultEvent())); + assertThat(podInfoFaultAndInitializationTime.getFaultEventCode()).isEqualTo(FaultEventCode.BAD_PUMP_REQ_2_STATE); + assertThat(podInfoFaultAndInitializationTime.getTimeFaultEvent()).isEqualTo(Duration.standardMinutes(1)); DateTime dateTime = podInfoFaultAndInitializationTime.getInitializationTime(); - Assertions.assertEquals(2018, dateTime.getYear()); - Assertions.assertEquals(9, dateTime.getMonthOfYear()); - Assertions.assertEquals(25, dateTime.getDayOfMonth()); - Assertions.assertEquals(23, dateTime.getHourOfDay()); - Assertions.assertEquals(14, dateTime.getMinuteOfHour()); + assertThat(dateTime.getYear()).isEqualTo(2018); + assertThat(dateTime.getMonthOfYear()).isEqualTo(9); + assertThat(dateTime.getDayOfMonth()).isEqualTo(25); + assertThat(dateTime.getHourOfDay()).isEqualTo(23); + assertThat(dateTime.getMinuteOfHour()).isEqualTo(14); } } From 89bd1769966876d1a6e4a65095305d0ec6eb5b01 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:56:43 -0700 Subject: [PATCH 26/34] Rewrites PairTest with matchers Issue #2745 --- .../nightscout/androidaps/interaction/utils/PairTest.kt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt index 19e427bcd8..4f4d782bc6 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.interaction.utils +import com.google.common.truth.Truth.assertThat import org.junit.Assert import org.junit.jupiter.api.Test @@ -34,15 +35,15 @@ class PairTest { val set: MutableSet> = HashSet() // THEN - Assert.assertFalse(set.contains(inserted)) + assertThat(set).doesNotContain(inserted) set.add(inserted) - Assert.assertTrue(set.contains(inserted)) + assertThat(set).contains(inserted) } @Test fun toStringTest() { // GIVEN val pair: Pair<*, *> = Pair.create("the-first", "2nd") - Assert.assertTrue(pair.toString().contains("the-first")) - Assert.assertTrue(pair.toString().contains("2nd")) + assertThat(pair.toString()).contains("the-first") + assertThat(pair.toString()).contains("2nd") } } \ No newline at end of file From 6e72ffed013ddb65c07598a8acffbb58f0b717f8 Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Fri, 8 Sep 2023 19:59:12 -0700 Subject: [PATCH 27/34] Rewrites WearUtilTest with matchers Issue #2745 --- .../interaction/utils/WearUtilTest.kt | 68 ++++++++----------- 1 file changed, 30 insertions(+), 38 deletions(-) diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt index b2bf2cbc30..2afd43d7b2 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.interaction.utils +import com.google.common.truth.Truth.assertThat import info.nightscout.androidaps.WearTestBase import info.nightscout.androidaps.testing.mockers.WearUtilMocker -import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test /** @@ -14,21 +14,18 @@ class WearUtilTest : WearTestBase() { @Test fun timestampAndTimeDiffsTest() { // smoke for mocks - since we freeze "now" to get stable tests - Assertions.assertEquals(WearUtilMocker.REF_NOW, wearUtil.timestamp()) - Assertions.assertEquals(0L, wearUtil.msTill(WearUtilMocker.REF_NOW)) - Assertions.assertEquals(3456L, wearUtil.msTill(WearUtilMocker.REF_NOW + 3456L)) - Assertions.assertEquals(-6294L, wearUtil.msTill(WearUtilMocker.REF_NOW - 6294L)) - Assertions.assertEquals(0L, wearUtil.msTill(WearUtilMocker.REF_NOW)) - Assertions.assertEquals(-3456L, wearUtil.msSince(WearUtilMocker.REF_NOW + 3456L)) - Assertions.assertEquals(6294L, wearUtil.msSince(WearUtilMocker.REF_NOW - 6294L)) + assertThat(wearUtil.timestamp()).isEqualTo(WearUtilMocker.REF_NOW) + assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW)).isEqualTo(0L) + assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW + 3456L)).isEqualTo(3456L) + assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW - 6294L)).isEqualTo(-6294L) + assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW)).isEqualTo(0L) + assertThat(wearUtil.msSince(WearUtilMocker.REF_NOW + 3456L)).isEqualTo(-3456L) + assertThat(wearUtil.msSince(WearUtilMocker.REF_NOW - 6294L)).isEqualTo(6294L) } @Test fun joinSetTest() { // GIVEN - val refSet: MutableSet = HashSet() - refSet.add("element1") - refSet.add("second-elem") - refSet.add("3rd") + val refSet = setOf("element1", "second-elem", "3rd") // WHEN val joined = persistence.joinSet(refSet, "|") @@ -36,10 +33,10 @@ class WearUtilTest : WearTestBase() { // THEN // we cannot guarantee order of items in joined string // but all items have to be there - Assertions.assertEquals(joined.length, "element1".length + "second-elem".length + "3rd".length + "|".length * 2) - Assertions.assertTrue("|$joined|".contains("|" + "element1" + "|")) - Assertions.assertTrue("|$joined|".contains("|" + "second-elem" + "|")) - Assertions.assertTrue("|$joined|".contains("|" + "3rd" + "|")) + assertThat(joined).hasLength(refSet.sumOf { it.length } + (refSet.size-1)) + assertThat("|$joined|").contains("|element1|") + assertThat("|$joined|").contains("|second-elem|") + assertThat("|$joined|").contains("|3rd|") } @Test fun explodeSetTest() { @@ -50,10 +47,7 @@ class WearUtilTest : WearTestBase() { val set = persistence.explodeSet(serializedSet, ":") // THEN - Assertions.assertEquals(set.size, 3) - Assertions.assertTrue(set.contains("element1")) - Assertions.assertTrue(set.contains("second-elem")) - Assertions.assertTrue(set.contains("3rd")) + assertThat(set).containsExactly( "element1", "second-elem", "3rd") } @Test fun explodeSetEmptyElemsTest() { @@ -64,27 +58,25 @@ class WearUtilTest : WearTestBase() { val set = persistence.explodeSet(serializedSet, ",") // THEN - Assertions.assertEquals(set.size, 2) - Assertions.assertEquals(true, set.contains("real")) - Assertions.assertEquals(true, set.contains("another")) + assertThat(set).containsExactly("real", "another") } @Test fun joinExplodeStabilityTest() { // GIVEN - val refSet: MutableSet = HashSet() - refSet.add("element1") - refSet.add("second-elem") - refSet.add("3rd") - refSet.add("czwarty") - refSet.add("V") - refSet.add("6") + val refSet = setOf( + "element1", + "second-elem", + "3rd", + "czwarty", + "V", + "6") // WHEN val joinedSet = persistence.joinSet(refSet, "#") val explodedSet = persistence.explodeSet(joinedSet, "#") // THEN - Assertions.assertEquals(explodedSet, refSet) + assertThat(explodedSet).containsExactlyElementsIn(refSet) } /* Mike: failing with new mockito @@ -100,8 +92,8 @@ class WearUtilTest : WearTestBase() { // THEN // we cannot guarantee to be exact to the millisecond - we add some margin of error - Assertions.assertTrue(60L > measuredSleepDuration) - Assertions.assertTrue(requestedSleepDuration + measuringMargin < measuredSleepDuration) + assertThat(measuredSleepDuration).isLessThan(60L) + assertThat(measuredSleepDuration).isGreaterThan(requestedSleepDuration + measuringMargin) } */ @Test fun rateLimitTest() { @@ -115,9 +107,9 @@ class WearUtilTest : WearTestBase() { val callAfterRateLimit = wearUtil.isBelowRateLimit("test-limit", 3) // THEN - Assertions.assertTrue(firstCall) - Assertions.assertFalse(callAfterward) - Assertions.assertFalse(callTooSoon) - Assertions.assertTrue(callAfterRateLimit) + assertThat(firstCall).isTrue() + assertThat(callAfterward).isFalse() + assertThat(callTooSoon).isFalse() + assertThat(callAfterRateLimit).isTrue() } -} \ No newline at end of file +} From aa85b4f17313b825649fbc6ad1b222bf69b8e9ee Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 9 Sep 2023 19:11:49 +0200 Subject: [PATCH 28/34] Wear CWF Refactor to allow more flexibility in additional resources --- .../rx/weardata/CustomWatchfaceFormat.kt | 23 +++----- .../CustomWatchfaceImportListActivity.kt | 2 +- .../plugins/general/wear/WearFragment.kt | 2 +- .../wear/activities/CwfInfosActivity.kt | 2 +- .../androidaps/watchfaces/CustomWatchface.kt | 56 +++++++++---------- 5 files changed, 38 insertions(+), 47 deletions(-) diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt index 35a30a9f7f..6b104b1355 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt @@ -50,11 +50,7 @@ enum class ResFileMap(val fileName: String) { ARROW_FLAT("ArrowFlat"), ARROW_FORTY_FIVE_DOWN("Arrow45Down"), ARROW_SINGLE_DOWN("ArrowSingleDown"), - ARROW_DOUBLE_DOWN("ArrowDoubleDown"), - FONT1("Font1"), - FONT2("Font2"), - FONT3("Font3"), - FONT4("Font4"); + ARROW_DOUBLE_DOWN("ArrowDoubleDown"); companion object { @@ -134,7 +130,7 @@ data class ResData(val value: ByteArray, val format: ResFormat) { } } -typealias CwfResDataMap = MutableMap +typealias CwfResDataMap = MutableMap typealias CwfMetadataMap = MutableMap @Serializable @@ -259,11 +255,7 @@ enum class JsonKeyValues(val key: String, val jsonKey: JsonKeys) { BOLD("bold", JsonKeys.FONTSTYLE), BOLD_ITALIC("bold_italic", JsonKeys.FONTSTYLE), ITALIC("italic", JsonKeys.FONTSTYLE), - BGCOLOR("bgColor", JsonKeys.COLOR), - FONT1("font1", JsonKeys.FONTCOLOR), - FONT2("font2", JsonKeys.FONTCOLOR), - FONT3("font3", JsonKeys.FONTCOLOR), - FONT4("font4", JsonKeys.FONTCOLOR) + BGCOLOR("bgColor", JsonKeys.COLOR) } enum class ViewType(@StringRes val comment: Int?) { @@ -309,14 +301,15 @@ class ZipWatchfaceFormat { val cwfResFileMap = ResFileMap.fromFileName(entryName) val drawableFormat = ResFormat.fromFileName(entryName) if (cwfResFileMap != ResFileMap.UNKNOWN && drawableFormat != ResFormat.UNKNOWN) { - resDatas[cwfResFileMap] = ResData(byteArrayOutputStream.toByteArray(), drawableFormat) - } + resDatas[cwfResFileMap.fileName] = ResData(byteArrayOutputStream.toByteArray(), drawableFormat) + } else if (drawableFormat != ResFormat.UNKNOWN) + resDatas[entryName.substringBeforeLast(".")] = ResData(byteArrayOutputStream.toByteArray(), drawableFormat) } zipEntry = zipInputStream.nextEntry } // Valid CWF file must contains a valid json file with a name within metadata and a custom watchface image - return if (metadata.containsKey(CwfMetadataKey.CWF_NAME) && resDatas.containsKey(ResFileMap.CUSTOM_WATCHFACE)) + return if (metadata.containsKey(CwfMetadataKey.CWF_NAME) && resDatas.containsKey(ResFileMap.CUSTOM_WATCHFACE.fileName)) CwfData(json.toString(4), metadata, resDatas) else null @@ -338,7 +331,7 @@ class ZipWatchfaceFormat { zipOutputStream.closeEntry() for (resData in customWatchface.resDatas) { - val fileEntry = ZipEntry("${resData.key.fileName}.${resData.value.format.extension}") + val fileEntry = ZipEntry("${resData.key}.${resData.value.format.extension}") zipOutputStream.putNextEntry(fileEntry) zipOutputStream.write(resData.value.value) zipOutputStream.closeEntry() diff --git a/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt index 5c6ad810e5..d8bc43c362 100644 --- a/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt @@ -89,7 +89,7 @@ class CustomWatchfaceImportListActivity: TranslatedDaggerAppCompatActivity() { override fun onBindViewHolder(holder: CwfFileViewHolder, position: Int) { val customWatchfaceFile = customWatchfaceFileList[position] val metadata = customWatchfaceFile.metadata - val drawable = customWatchfaceFile.resDatas[ResFileMap.CUSTOM_WATCHFACE]?.toDrawable(resources) + val drawable = customWatchfaceFile.resDatas[ResFileMap.CUSTOM_WATCHFACE.fileName]?.toDrawable(resources) with(holder.customWatchfaceImportListItemBinding) { filelistName.text = rh.gs(info.nightscout.shared.R.string.metadata_wear_import_filename, metadata[CWF_FILENAME]) filelistName.tag = customWatchfaceFile diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/WearFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/WearFragment.kt index d0aebce9af..e9aa8f6987 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/WearFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/WearFragment.kt @@ -111,7 +111,7 @@ class WearFragment : DaggerFragment() { wearPlugin.savedCustomWatchface?.let { wearPlugin.checkCustomWatchfacePreferences() binding.customName.text = rh.gs(R.string.wear_custom_watchface, it.metadata[CwfMetadataKey.CWF_NAME]) - binding.coverChart.setImageDrawable(it.resDatas[ResFileMap.CUSTOM_WATCHFACE]?.toDrawable(resources)) + binding.coverChart.setImageDrawable(it.resDatas[ResFileMap.CUSTOM_WATCHFACE.fileName]?.toDrawable(resources)) binding.infosCustom.visibility = View.VISIBLE } ?:apply { binding.customName.text = rh.gs(R.string.wear_custom_watchface, "") diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/activities/CwfInfosActivity.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/activities/CwfInfosActivity.kt index 5b9404709d..ce414654ee 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/activities/CwfInfosActivity.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/activities/CwfInfosActivity.kt @@ -86,7 +86,7 @@ class CwfInfosActivity : TranslatedDaggerAppCompatActivity() { wearPlugin.savedCustomWatchface?.let { val cwfAuthorization = sp.getBoolean(info.nightscout.core.utils.R.string.key_wear_custom_watchface_autorization, false) val metadata = it.metadata - val drawable = it.resDatas[ResFileMap.CUSTOM_WATCHFACE]?.toDrawable(resources) + val drawable = it.resDatas[ResFileMap.CUSTOM_WATCHFACE.fileName]?.toDrawable(resources) binding.customWatchface.setImageDrawable(drawable) title = rh.gs(CwfMetadataKey.CWF_NAME.label, metadata[CwfMetadataKey.CWF_NAME]) metadata[CwfMetadataKey.CWF_AUTHOR_VERSION]?.let { authorVersion -> diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt index 4aab760bc1..08103d262e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt @@ -301,7 +301,7 @@ class CustomWatchface : BaseWatchFace() { val metadataMap = ZipWatchfaceFormat.loadMetadata(json) val drawableDataMap: CwfResDataMap = mutableMapOf() getResourceByteArray(info.nightscout.shared.R.drawable.watchface_custom)?.let { - drawableDataMap[ResFileMap.CUSTOM_WATCHFACE] = ResData(it, ResFormat.PNG) + drawableDataMap[ResFileMap.CUSTOM_WATCHFACE.fileName] = ResData(it, ResFormat.PNG) } return EventData.ActionSetCustomWatchface(CwfData(json.toString(4), metadataMap, drawableDataMap)) } @@ -489,10 +489,10 @@ class CustomWatchface : BaseWatchFace() { fun drawable(resources: Resources, drawableDataMap: CwfResDataMap, sgvLevel: Long): Drawable? = customDrawable?.let { cd -> when (sgvLevel) { - 1L -> { drawableDataMap[customHigh]?.toDrawable(resources) ?: drawableDataMap[cd]?.toDrawable(resources) } - 0L -> { drawableDataMap[cd]?.toDrawable(resources) } - -1L -> { drawableDataMap[customLow]?.toDrawable(resources) ?: drawableDataMap[cd]?.toDrawable(resources) } - else -> drawableDataMap[cd]?.toDrawable(resources) + 1L -> { customHigh?.let {drawableDataMap[customHigh.fileName]}?.toDrawable(resources) ?: drawableDataMap[cd.fileName]?.toDrawable(resources) } + 0L -> { drawableDataMap[cd.fileName]?.toDrawable(resources) } + -1L -> { customLow?.let {drawableDataMap[customLow.fileName]}?.toDrawable(resources) ?: drawableDataMap[cd.fileName]?.toDrawable(resources) } + else -> drawableDataMap[cd.fileName]?.toDrawable(resources) } } } @@ -514,7 +514,7 @@ private enum class TrendArrowMap(val symbol: String, @DrawableRes val icon: Int, fun drawable(direction: String?, resources: Resources, drawableDataMap: CwfResDataMap): Drawable { val arrow = values().firstOrNull { it.symbol == direction } ?:NONE - return drawableDataMap[arrow.customDrawable]?.toDrawable(resources) ?:resources.getDrawable(arrow.icon) + return arrow.customDrawable?. let {drawableDataMap[arrow.customDrawable.fileName]}?.toDrawable(resources) ?:resources.getDrawable(arrow.icon) } } @@ -532,36 +532,34 @@ private enum class GravityMap(val key: String, val gravity: Int) { } } -private enum class FontMap(val key: String, var font: Typeface, @FontRes val fontRessources: Int?, val customFont: ResFileMap?) { - SANS_SERIF(JsonKeyValues.SANS_SERIF.key, Typeface.SANS_SERIF, null, null), - DEFAULT(JsonKeyValues.DEFAULT.key, Typeface.DEFAULT, null, null), - DEFAULT_BOLD(JsonKeyValues.DEFAULT_BOLD.key, Typeface.DEFAULT_BOLD, null, null), - MONOSPACE(JsonKeyValues.MONOSPACE.key, Typeface.MONOSPACE, null, null), - SERIF(JsonKeyValues.SERIF.key, Typeface.SERIF, null, null), - ROBOTO_CONDENSED_BOLD(JsonKeyValues.ROBOTO_CONDENSED_BOLD.key, Typeface.DEFAULT, R.font.roboto_condensed_bold, null), - ROBOTO_CONDENSED_LIGHT(JsonKeyValues.ROBOTO_CONDENSED_LIGHT.key, Typeface.DEFAULT, R.font.roboto_condensed_light, null), - ROBOTO_CONDENSED_REGULAR(JsonKeyValues.ROBOTO_CONDENSED_REGULAR.key, Typeface.DEFAULT, R.font.roboto_condensed_regular, null), - ROBOTO_SLAB_LIGHT(JsonKeyValues.ROBOTO_SLAB_LIGHT.key, Typeface.DEFAULT, R.font.roboto_slab_light, null), - FONT1(JsonKeyValues.FONT1.key, Typeface.DEFAULT, null, ResFileMap.FONT1), - FONT2(JsonKeyValues.FONT2.key, Typeface.DEFAULT, null, ResFileMap.FONT2), - FONT3(JsonKeyValues.FONT3.key, Typeface.DEFAULT, null, ResFileMap.FONT3), - FONT4(JsonKeyValues.FONT4.key, Typeface.DEFAULT, null, ResFileMap.FONT4); +private enum class FontMap(val key: String, var font: Typeface, @FontRes val fontRessources: Int?) { + SANS_SERIF(JsonKeyValues.SANS_SERIF.key, Typeface.SANS_SERIF, null), + DEFAULT(JsonKeyValues.DEFAULT.key, Typeface.DEFAULT, null), + DEFAULT_BOLD(JsonKeyValues.DEFAULT_BOLD.key, Typeface.DEFAULT_BOLD, null), + MONOSPACE(JsonKeyValues.MONOSPACE.key, Typeface.MONOSPACE, null), + SERIF(JsonKeyValues.SERIF.key, Typeface.SERIF, null), + ROBOTO_CONDENSED_BOLD(JsonKeyValues.ROBOTO_CONDENSED_BOLD.key, Typeface.DEFAULT, R.font.roboto_condensed_bold), + ROBOTO_CONDENSED_LIGHT(JsonKeyValues.ROBOTO_CONDENSED_LIGHT.key, Typeface.DEFAULT, R.font.roboto_condensed_light), + ROBOTO_CONDENSED_REGULAR(JsonKeyValues.ROBOTO_CONDENSED_REGULAR.key, Typeface.DEFAULT, R.font.roboto_condensed_regular), + ROBOTO_SLAB_LIGHT(JsonKeyValues.ROBOTO_SLAB_LIGHT.key, Typeface.DEFAULT, R.font.roboto_slab_light); companion object { - fun init(context: Context, resDataMap: CwfResDataMap) = values().forEach { fontMap -> - fontMap.customFont?.let { customFont -> - fontMap.font = Typeface.DEFAULT - resDataMap[customFont]?.toTypeface()?.let { resData -> - fontMap.font = resData - } - } ?: run { - fontMap.font = fontMap.fontRessources?.let { fontResource -> + private val customFonts = mutableMapOf() + fun init(context: Context, resDataMap: CwfResDataMap) { + values().forEach { fontMap -> + customFonts[fontMap.key.lowercase()] = fontMap.fontRessources?.let { fontResource -> ResourcesCompat.getFont(context, fontResource) } ?: fontMap.font } + resDataMap.filter { (_, resData) -> + resData.format == ResFormat.TTF + }.forEach { (key, resData) -> + customFonts[key.lowercase()] = resData.toTypeface() ?:Typeface.DEFAULT + } } - fun font(key: String) = values().firstOrNull { it.key == key }?.font ?: DEFAULT.font + + fun font(key: String) = customFonts[key.lowercase()] ?: DEFAULT.font fun key() = DEFAULT.key } } From a9b6fdef270e9685a3454eada9fe91d68aa30664 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 9 Sep 2023 19:56:27 +0200 Subject: [PATCH 29/34] Wear CWF Cleanup unused properties --- .../rx/weardata/CustomWatchfaceFormat.kt | 110 ++++++++---------- 1 file changed, 51 insertions(+), 59 deletions(-) diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt index 6b104b1355..e2779484e0 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt @@ -202,67 +202,60 @@ enum class ViewKeys(val key: String, @StringRes val comment: Int) { COVER_PLATE("cover_plate", R.string.cwf_comment_cover_plate), HOUR_HAND("hour_hand", R.string.cwf_comment_hour_hand), MINUTE_HAND("minute_hand", R.string.cwf_comment_minute_hand), - SECOND_HAND("second_hand", R.string.cwf_comment_second_hand); + SECOND_HAND("second_hand", R.string.cwf_comment_second_hand) } -enum class JsonKeys(val key: String, val viewType: ViewType, @StringRes val comment: Int?) { - METADATA("metadata", ViewType.NONE, null), - ENABLESECOND("enableSecond", ViewType.NONE, null), - HIGHCOLOR("highColor", ViewType.NONE, null), - MIDCOLOR("midColor", ViewType.NONE, null), - LOWCOLOR("lowColor", ViewType.NONE, null), - LOWBATCOLOR("lowBatColor", ViewType.NONE, null), - CARBCOLOR("carbColor", ViewType.NONE, null), - BASALBACKGROUNDCOLOR("basalBackgroundColor", ViewType.NONE, null), - BASALCENTERCOLOR("basalCenterColor", ViewType.NONE, null), - GRIDCOLOR("gridColor", ViewType.NONE, null), - POINTSIZE("pointSize", ViewType.NONE, null), - WIDTH("width", ViewType.ALLVIEWS, null), - HEIGHT("height", ViewType.ALLVIEWS, null), - TOPMARGIN("topmargin", ViewType.ALLVIEWS, null), - LEFTMARGIN("leftmargin", ViewType.ALLVIEWS, null), - ROTATION("rotation", ViewType.TEXTVIEW, null), - VISIBILITY("visibility", ViewType.ALLVIEWS, null), - TEXTSIZE("textsize", ViewType.TEXTVIEW, null), - TEXTVALUE("textvalue", ViewType.TEXTVIEW, null), - GRAVITY("gravity", ViewType.TEXTVIEW, null), - FONT("font", ViewType.TEXTVIEW, null), - FONTSTYLE("fontStyle", ViewType.TEXTVIEW, null), - FONTCOLOR("fontColor", ViewType.TEXTVIEW, null), - COLOR("color", ViewType.IMAGEVIEW, null), - ALLCAPS("allCaps", ViewType.TEXTVIEW, null), - DAYNAMEFORMAT("dayNameFormat", ViewType.NONE, null), - MONTHFORMAT("monthFormat", ViewType.NONE, null) +enum class JsonKeys(val key: String) { + METADATA("metadata"), + ENABLESECOND("enableSecond"), + HIGHCOLOR("highColor"), + MIDCOLOR("midColor"), + LOWCOLOR("lowColor"), + LOWBATCOLOR("lowBatColor"), + CARBCOLOR("carbColor"), + BASALBACKGROUNDCOLOR("basalBackgroundColor"), + BASALCENTERCOLOR("basalCenterColor"), + GRIDCOLOR("gridColor"), + POINTSIZE("pointSize"), + WIDTH("width"), + HEIGHT("height"), + TOPMARGIN("topmargin"), + LEFTMARGIN("leftmargin"), + ROTATION("rotation"), + VISIBILITY("visibility"), + TEXTSIZE("textsize"), + TEXTVALUE("textvalue"), + GRAVITY("gravity"), + FONT("font"), + FONTSTYLE("fontStyle"), + FONTCOLOR("fontColor"), + COLOR("color"), + ALLCAPS("allCaps"), + DAYNAMEFORMAT("dayNameFormat"), + MONTHFORMAT("monthFormat") } -enum class JsonKeyValues(val key: String, val jsonKey: JsonKeys) { - GONE("gone", JsonKeys.VISIBILITY), - VISIBLE("visible", JsonKeys.VISIBILITY), - INVISIBLE("invisible", JsonKeys.VISIBILITY), - CENTER("center", JsonKeys.GRAVITY), - LEFT("left", JsonKeys.GRAVITY), - RIGHT("right", JsonKeys.GRAVITY), - SANS_SERIF("sans_serif", JsonKeys.FONT), - DEFAULT("default", JsonKeys.FONT), - DEFAULT_BOLD("default_bold", JsonKeys.FONT), - MONOSPACE("monospace", JsonKeys.FONT), - SERIF("serif", JsonKeys.FONT), - ROBOTO_CONDENSED_BOLD("roboto_condensed_bold", JsonKeys.FONT), - ROBOTO_CONDENSED_LIGHT("roboto_condensed_light", JsonKeys.FONT), - ROBOTO_CONDENSED_REGULAR("roboto_condensed_regular", JsonKeys.FONT), - ROBOTO_SLAB_LIGHT("roboto_slab_light", JsonKeys.FONT), - NORMAL("normal", JsonKeys.FONTSTYLE), - BOLD("bold", JsonKeys.FONTSTYLE), - BOLD_ITALIC("bold_italic", JsonKeys.FONTSTYLE), - ITALIC("italic", JsonKeys.FONTSTYLE), - BGCOLOR("bgColor", JsonKeys.COLOR) -} - -enum class ViewType(@StringRes val comment: Int?) { - NONE(null), - TEXTVIEW(null), - IMAGEVIEW(null), - ALLVIEWS(null) +enum class JsonKeyValues(val key: String) { + GONE("gone"), + VISIBLE("visible"), + INVISIBLE("invisible"), + CENTER("center"), + LEFT("left"), + RIGHT("right"), + SANS_SERIF("sans_serif"), + DEFAULT("default"), + DEFAULT_BOLD("default_bold"), + MONOSPACE("monospace"), + SERIF("serif"), + ROBOTO_CONDENSED_BOLD("roboto_condensed_bold"), + ROBOTO_CONDENSED_LIGHT("roboto_condensed_light"), + ROBOTO_CONDENSED_REGULAR("roboto_condensed_regular"), + ROBOTO_SLAB_LIGHT("roboto_slab_light"), + NORMAL("normal"), + BOLD("bold"), + BOLD_ITALIC("bold_italic"), + ITALIC("italic"), + BGCOLOR("bgColor") } class ZipWatchfaceFormat { @@ -324,7 +317,7 @@ class ZipWatchfaceFormat { try { val outputStream = FileOutputStream(file) val zipOutputStream = ZipOutputStream(BufferedOutputStream(outputStream)) - + val jsonEntry = ZipEntry(CWF_JSON_FILE) zipOutputStream.putNextEntry(jsonEntry) zipOutputStream.write(customWatchface.json.toByteArray()) @@ -355,5 +348,4 @@ class ZipWatchfaceFormat { return metadata } } - } \ No newline at end of file From e33358d46c415374aea1d3630a1c0b5902a7c53a Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 9 Sep 2023 23:15:28 +0200 Subject: [PATCH 30/34] Wear CWF Clean loaded font before loading --- .../java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt | 2 +- .../info/nightscout/androidaps/watchfaces/CustomWatchface.kt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt index e2779484e0..4be5b5e5a5 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt @@ -104,7 +104,7 @@ data class ResData(val value: ByteArray, val format: ResFormat) { return when (format) { ResFormat.TTF -> { // Workaround with temporary File, Typeface.createFromFileDescriptor(null, value, 0, value.size) more simple not available - File.createTempFile("temp", ".ttf").let { tempFile -> + File.createTempFile("temp", format.extension).let { tempFile -> FileOutputStream(tempFile).let { fileOutputStream -> fileOutputStream.write(value) fileOutputStream.close() diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt index 08103d262e..ca92b2c254 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt @@ -547,6 +547,7 @@ private enum class FontMap(val key: String, var font: Typeface, @FontRes val fon private val customFonts = mutableMapOf() fun init(context: Context, resDataMap: CwfResDataMap) { + customFonts.clear() values().forEach { fontMap -> customFonts[fontMap.key.lowercase()] = fontMap.fontRessources?.let { fontResource -> ResourcesCompat.getFont(context, fontResource) From d00c4e223eaf8fb6a369a381919055e9a3e06110 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 9 Sep 2023 23:21:54 +0200 Subject: [PATCH 31/34] Wear CWF Include otf format compatibility for fonts --- .../info/nightscout/rx/weardata/CustomWatchfaceFormat.kt | 5 +++-- .../info/nightscout/androidaps/watchfaces/CustomWatchface.kt | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt index 4be5b5e5a5..010c9ca095 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt @@ -63,7 +63,8 @@ enum class ResFormat(val extension: String) { SVG("svg"), JPG("jpg"), PNG("png"), - TTF("ttf"); + TTF("ttf"), + OTF("otf"); companion object { @@ -102,7 +103,7 @@ data class ResData(val value: ByteArray, val format: ResFormat) { fun toTypeface(): Typeface? { try { return when (format) { - ResFormat.TTF -> { + ResFormat.TTF, ResFormat.OTF -> { // Workaround with temporary File, Typeface.createFromFileDescriptor(null, value, 0, value.size) more simple not available File.createTempFile("temp", format.extension).let { tempFile -> FileOutputStream(tempFile).let { fileOutputStream -> diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt index ca92b2c254..e82642e0a1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt @@ -554,7 +554,7 @@ private enum class FontMap(val key: String, var font: Typeface, @FontRes val fon } ?: fontMap.font } resDataMap.filter { (_, resData) -> - resData.format == ResFormat.TTF + resData.format == ResFormat.TTF || resData.format == ResFormat.OTF }.forEach { (key, resData) -> customFonts[key.lowercase()] = resData.toTypeface() ?:Typeface.DEFAULT } From d487bb5038c3ca9b7691b015b349e5213a9fe9fa Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Sun, 10 Sep 2023 10:34:02 -0700 Subject: [PATCH 32/34] Drops hamcrest dependency Replaces hamcrest uses with truth. Fixes #2760 --- .../nightscout/core/utils/CryptoUtilTest.kt | 40 ++++++++++++++----- core/main/test_dependencies.gradle | 3 +- .../formats/EncryptedPrefsFormatTest.kt | 24 +++++------ 3 files changed, 43 insertions(+), 24 deletions(-) diff --git a/core/main/src/test/java/info/nightscout/core/utils/CryptoUtilTest.kt b/core/main/src/test/java/info/nightscout/core/utils/CryptoUtilTest.kt index e6ca023bc4..e57753fddb 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/CryptoUtilTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/CryptoUtilTest.kt @@ -1,9 +1,7 @@ package info.nightscout.core.utils +import com.google.common.truth.TruthJUnit.assume import info.nightscout.sharedtests.TestBase -import org.hamcrest.CoreMatchers.containsString -import org.hamcrest.CoreMatchers.not -import org.junit.Assume.assumeThat import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test @@ -11,9 +9,10 @@ import org.junit.jupiter.api.Test // https://stackoverflow.com/questions/47708951/can-aes-256-work-on-android-devices-with-api-level-26 // Java prior to Oracle Java 8u161 does not have policy for 256 bit AES - but Android support it // when test is run in Vanilla JVM without policy - Invalid key size exception is thrown -fun assumeAES256isSupported(cryptoUtil: CryptoUtil) { +private fun assumeAES256isSupported(cryptoUtil: CryptoUtil) { cryptoUtil.lastException?.message?.let { exceptionMessage -> - assumeThat("Upgrade your testing environment Java (OpenJDK or Java 8u161) and JAVA_HOME - AES 256 is supported by Android so this exception should not happen!", exceptionMessage, not(containsString("key size"))) + assume().withMessage("Upgrade your testing environment Java (OpenJDK or Java 8u161) and JAVA_HOME - AES 256 is supported by Android so this exception should not happen!") + .that(exceptionMessage).doesNotContain("key size") } } @@ -26,7 +25,8 @@ class CryptoUtilTest : TestBase() { fun testFixedSaltCrypto() { val salt = byteArrayOf( -33, -29, 16, -19, 99, -111, -3, 2, 116, 106, 47, 38, -54, 11, -77, 28, - 111, -15, -65, -110, 4, -32, -29, -70, -95, -88, -53, 19, 87, -103, 123, -15) + 111, -15, -65, -110, 4, -32, -29, -70, -95, -88, -53, 19, 87, -103, 123, -15 + ) val password = "thisIsFixedPassword" val payload = "FIXED-PAYLOAD" @@ -83,10 +83,30 @@ class CryptoUtilTest : TestBase() { Assertions.assertTrue(cryptoUtil.checkPassword("givenSecret", cryptoUtil.hashPassword("givenSecret"))) Assertions.assertFalse(cryptoUtil.checkPassword("givenSecret", cryptoUtil.hashPassword("otherSecret"))) - Assertions.assertTrue(cryptoUtil.checkPassword("givenHashToCheck", "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1")) - Assertions.assertFalse(cryptoUtil.checkPassword("givenMashToCheck", "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1")) - Assertions.assertFalse(cryptoUtil.checkPassword("givenHashToCheck", "hmac:0fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1")) - Assertions.assertFalse(cryptoUtil.checkPassword("givenHashToCheck", "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:b0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1")) + Assertions.assertTrue( + cryptoUtil.checkPassword( + "givenHashToCheck", + "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1" + ) + ) + Assertions.assertFalse( + cryptoUtil.checkPassword( + "givenMashToCheck", + "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1" + ) + ) + Assertions.assertFalse( + cryptoUtil.checkPassword( + "givenHashToCheck", + "hmac:0fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1" + ) + ) + Assertions.assertFalse( + cryptoUtil.checkPassword( + "givenHashToCheck", + "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:b0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1" + ) + ) } } diff --git a/core/main/test_dependencies.gradle b/core/main/test_dependencies.gradle index cce79fc6ba..b4f8cf5370 100644 --- a/core/main/test_dependencies.gradle +++ b/core/main/test_dependencies.gradle @@ -8,7 +8,6 @@ dependencies { testImplementation "joda-time:joda-time:$jodatime_version" testImplementation 'com.google.truth:truth:1.1.5' testImplementation "org.skyscreamer:jsonassert:1.5.0" - testImplementation "org.hamcrest:hamcrest-all:1.3" androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' androidTestImplementation "androidx.test.ext:junit-ktx:$androidx_junit_version" @@ -37,4 +36,4 @@ android { } } } -} \ No newline at end of file +} diff --git a/plugins/configuration/src/test/java/info/nightscout/configuration/maintenance/formats/EncryptedPrefsFormatTest.kt b/plugins/configuration/src/test/java/info/nightscout/configuration/maintenance/formats/EncryptedPrefsFormatTest.kt index f97b8fad23..bf76df1f30 100644 --- a/plugins/configuration/src/test/java/info/nightscout/configuration/maintenance/formats/EncryptedPrefsFormatTest.kt +++ b/plugins/configuration/src/test/java/info/nightscout/configuration/maintenance/formats/EncryptedPrefsFormatTest.kt @@ -1,5 +1,6 @@ package info.nightscout.configuration.maintenance.formats +import com.google.common.truth.TruthJUnit.assume import info.nightscout.core.utils.CryptoUtil import info.nightscout.interfaces.maintenance.PrefFormatError import info.nightscout.interfaces.maintenance.PrefMetadata @@ -9,8 +10,6 @@ import info.nightscout.interfaces.maintenance.PrefsMetadataKey import info.nightscout.interfaces.maintenance.PrefsStatus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.sharedtests.TestBase -import org.hamcrest.CoreMatchers -import org.junit.Assume import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @@ -19,6 +18,17 @@ import org.mockito.Mock import org.mockito.Mockito import java.io.File +// https://stackoverflow.com/questions/52344522/joseexception-couldnt-create-aes-gcm-nopadding-cipher-illegal-key-size +// https://stackoverflow.com/questions/47708951/can-aes-256-work-on-android-devices-with-api-level-26 +// Java prior to Oracle Java 8u161 does not have policy for 256 bit AES - but Android support it +// when test is run in Vanilla JVM without policy - Invalid key size exception is thrown +private fun assumeAES256isSupported(cryptoUtil: CryptoUtil) { + cryptoUtil.lastException?.message?.let { exceptionMessage -> + assume().withMessage("Upgrade your testing environment Java (OpenJDK or Java 8u161) and JAVA_HOME - AES 256 is supported by Android so this exception should not happen!") + .that(exceptionMessage).doesNotContain("key size") + } +} + @Suppress("SpellCheckingInspection") open class EncryptedPrefsFormatTest : TestBase() { @@ -27,16 +37,6 @@ open class EncryptedPrefsFormatTest : TestBase() { private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger) - // https://stackoverflow.com/questions/52344522/joseexception-couldnt-create-aes-gcm-nopadding-cipher-illegal-key-size - // https://stackoverflow.com/questions/47708951/can-aes-256-work-on-android-devices-with-api-level-26 - // Java prior to Oracle Java 8u161 does not have policy for 256 bit AES - but Android support it - // when test is run in Vanilla JVM without policy - Invalid key size exception is thrown - private fun assumeAES256isSupported(cryptoUtil: CryptoUtil) { - cryptoUtil.lastException?.message?.let { exceptionMessage -> - Assume.assumeThat("Upgrade your testing environment Java (OpenJDK or Java 8u161) and JAVA_HOME - AES 256 is supported by Android so this exception should not happen!", exceptionMessage, CoreMatchers.not(CoreMatchers.containsString("key size"))) - } - } - @BeforeEach fun mock() { Mockito.`when`(rh.gs(ArgumentMatchers.anyInt())).thenReturn("mock translation") From 9e24cc1607391e2714f9c031a1a497673d27fc0c Mon Sep 17 00:00:00 2001 From: Ryan Haining Date: Sun, 10 Sep 2023 13:36:30 -0700 Subject: [PATCH 33/34] Uses Fake instead of incomplete Mock for WearUtil Unblocks #2732 and #2733 --- .../nightscout/androidaps/WearTestBase.kt | 38 ++++--- .../interaction/utils/DisplayFormatTest.kt | 101 +++++++++--------- .../interaction/utils/WearUtilTest.kt | 36 +++---- .../testing/mockers/RawDataMocker.kt | 12 +-- .../testing/mockers/WearUtilMocker.kt | 43 -------- 5 files changed, 98 insertions(+), 132 deletions(-) delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt diff --git a/wear/src/test/java/info/nightscout/androidaps/WearTestBase.kt b/wear/src/test/java/info/nightscout/androidaps/WearTestBase.kt index 61b662d5b6..3b9c6ed7c9 100644 --- a/wear/src/test/java/info/nightscout/androidaps/WearTestBase.kt +++ b/wear/src/test/java/info/nightscout/androidaps/WearTestBase.kt @@ -2,10 +2,11 @@ package info.nightscout.androidaps import android.content.Context import android.content.SharedPreferences +import info.nightscout.androidaps.interaction.utils.Constants import info.nightscout.androidaps.interaction.utils.Persistence import info.nightscout.androidaps.interaction.utils.WearUtil -import info.nightscout.androidaps.testing.mockers.WearUtilMocker import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock +import info.nightscout.rx.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil import info.nightscout.sharedtests.TestBase @@ -13,24 +14,36 @@ import org.junit.jupiter.api.BeforeEach import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito -import org.mockito.Mockito.`when` + +class FakeWearUtil(context: Context, aapsLogger: AAPSLogger) : WearUtil(context, aapsLogger) { + private var clockMsDiff = 0L + + override fun timestamp(): Long = REF_NOW + clockMsDiff + + fun progressClock(byMilliseconds: Long) { + clockMsDiff += byMilliseconds + } + + companion object { + const val REF_NOW = 1572610530000L + } +} open class WearTestBase : TestBase() { @Mock lateinit var context: Context @Mock lateinit var sp: SP @Mock lateinit var dateUtil: DateUtil - @Mock lateinit var wearUtil: WearUtil + lateinit var fakeWearUtil: FakeWearUtil - //val wearUtil: WearUtil = Mockito.mock(WearUtil::class.java) - lateinit var wearUtilMocker: WearUtilMocker lateinit var persistence: Persistence private val mockedSharedPrefs: HashMap = HashMap() + @BeforeEach fun setup() { - wearUtilMocker = WearUtilMocker(wearUtil) + fakeWearUtil = FakeWearUtil(context, aapsLogger) Mockito.doAnswer { invocation -> val key = invocation.getArgument(0) if (mockedSharedPrefs.containsKey(key)) { @@ -42,12 +55,11 @@ open class WearTestBase : TestBase() { } }.`when`(context).getSharedPreferences(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()) - wearUtilMocker.prepareMockNoReal() - `when`(wearUtil.aapsLogger).thenReturn(aapsLogger) - `when`(wearUtil.context).thenReturn(context) - val rateLimits: MutableMap = HashMap() - `when`(wearUtil.rateLimits).thenReturn(rateLimits) persistence = Mockito.spy(Persistence(aapsLogger, dateUtil, sp)) - } -} \ No newline at end of file + + companion object { + fun backInTime(d: Int, h: Int, m: Int, s: Int): Long = + FakeWearUtil.REF_NOW - (Constants.DAY_IN_MS * d + Constants.HOUR_IN_MS * h + Constants.MINUTE_IN_MS * m + Constants.SECOND_IN_MS * s) + } +} diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt index bf21f9a3fa..6ce2cce75f 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt @@ -20,10 +20,9 @@ class DisplayFormatTest : WearTestBase() { @BeforeEach fun mock() { - rawDataMocker = RawDataMocker(wearUtil) - wearUtilMocker.prepareMock() + rawDataMocker = RawDataMocker() displayFormat = DisplayFormat() - displayFormat.wearUtil = wearUtil + displayFormat.wearUtil = fakeWearUtil displayFormat.sp = sp displayFormat.context = context Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(true) @@ -33,58 +32,58 @@ class DisplayFormatTest : WearTestBase() { } @Test fun shortTimeSinceTest() { - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 0)), "0'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 5)), "0'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 55)), "0'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 1, 0)), "1'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 1, 59)), "1'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 2, 0)), "2'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 3, 0)), "3'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 4, 0)), "4'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 10, 0)), "10'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 30, 0)), "30'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 59, 0)), "59'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 59, 59)), "59'") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 0, 0)), "1h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 30, 0)), "1h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 59, 59)), "1h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 2, 0, 0)), "2h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 3, 0, 0)), "3h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 4, 0, 0)), "4h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 5, 0, 0)), "5h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 12, 0, 0)), "12h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 18, 0, 0)), "18h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 23, 59, 59)), "23h") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 0, 0, 0)), "1d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 12, 0, 0)), "1d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 23, 59, 59)), "1d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(2, 0, 0, 0)), "2d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(3, 0, 0, 0)), "3d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(4, 0, 0, 0)), "4d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(5, 0, 0, 0)), "5d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(6, 0, 0, 0)), "6d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(6, 23, 59, 59)), "6d") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(7, 0, 0, 0)), "1w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(8, 0, 0, 0)), "1w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(9, 0, 0, 0)), "1w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(13, 23, 59, 59)), "1w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(14, 0, 0, 0)), "2w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(21, 0, 0, 0)), "3w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(28, 0, 0, 0)), "4w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(31, 0, 0, 0)), "4w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(32, 0, 0, 0)), "4w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(35, 0, 0, 0)), "5w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(100, 0, 0, 0)), "14w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(200, 0, 0, 0)), "28w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(365, 0, 0, 0)), "52w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(366, 0, 0, 0)), "52w") - Assertions.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(367, 0, 0, 0)), "52w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 0, 0)), "0'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 0, 5)), "0'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 0, 55)), "0'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 1, 0)), "1'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 1, 59)), "1'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 2, 0)), "2'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 3, 0)), "3'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 4, 0)), "4'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 10, 0)), "10'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 30, 0)), "30'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 59, 0)), "59'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 0, 59, 59)), "59'") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 1, 0, 0)), "1h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 1, 30, 0)), "1h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 1, 59, 59)), "1h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 2, 0, 0)), "2h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 3, 0, 0)), "3h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 4, 0, 0)), "4h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 5, 0, 0)), "5h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 12, 0, 0)), "12h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 18, 0, 0)), "18h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(0, 23, 59, 59)), "23h") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(1, 0, 0, 0)), "1d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(1, 12, 0, 0)), "1d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(1, 23, 59, 59)), "1d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(2, 0, 0, 0)), "2d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(3, 0, 0, 0)), "3d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(4, 0, 0, 0)), "4d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(5, 0, 0, 0)), "5d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(6, 0, 0, 0)), "6d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(6, 23, 59, 59)), "6d") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(7, 0, 0, 0)), "1w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(8, 0, 0, 0)), "1w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(9, 0, 0, 0)), "1w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(13, 23, 59, 59)), "1w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(14, 0, 0, 0)), "2w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(21, 0, 0, 0)), "3w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(28, 0, 0, 0)), "4w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(31, 0, 0, 0)), "4w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(32, 0, 0, 0)), "4w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(35, 0, 0, 0)), "5w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(100, 0, 0, 0)), "14w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(200, 0, 0, 0)), "28w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(365, 0, 0, 0)), "52w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(366, 0, 0, 0)), "52w") + Assertions.assertEquals(displayFormat.shortTimeSince(backInTime(367, 0, 0, 0)), "52w") } @Test fun shortTrendTest() { val raw = RawDisplayData() Assertions.assertEquals(displayFormat.shortTrend(raw), "-- Δ--") - raw.singleBg.timeStamp = wearUtilMocker.backInTime(0, 0, 2, 0) + raw.singleBg.timeStamp = backInTime(0, 0, 2, 0) Assertions.assertEquals(displayFormat.shortTrend(raw), "2' Δ--") Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(true) @@ -171,4 +170,4 @@ class DisplayFormatTest : WearTestBase() { Assertions.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("19(38)g")), Pair.create("19g", "38g")) Assertions.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("100(1)g")), Pair.create("100g", "1g")) } -} \ No newline at end of file +} diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt index 2afd43d7b2..3c88639184 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.interaction.utils import com.google.common.truth.Truth.assertThat +import info.nightscout.androidaps.FakeWearUtil import info.nightscout.androidaps.WearTestBase -import info.nightscout.androidaps.testing.mockers.WearUtilMocker import org.junit.jupiter.api.Test /** @@ -14,13 +14,13 @@ class WearUtilTest : WearTestBase() { @Test fun timestampAndTimeDiffsTest() { // smoke for mocks - since we freeze "now" to get stable tests - assertThat(wearUtil.timestamp()).isEqualTo(WearUtilMocker.REF_NOW) - assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW)).isEqualTo(0L) - assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW + 3456L)).isEqualTo(3456L) - assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW - 6294L)).isEqualTo(-6294L) - assertThat(wearUtil.msTill(WearUtilMocker.REF_NOW)).isEqualTo(0L) - assertThat(wearUtil.msSince(WearUtilMocker.REF_NOW + 3456L)).isEqualTo(-3456L) - assertThat(wearUtil.msSince(WearUtilMocker.REF_NOW - 6294L)).isEqualTo(6294L) + assertThat(fakeWearUtil.timestamp()).isEqualTo(FakeWearUtil.REF_NOW) + assertThat(fakeWearUtil.msTill(FakeWearUtil.REF_NOW)).isEqualTo(0L) + assertThat(fakeWearUtil.msTill(FakeWearUtil.REF_NOW + 3456L)).isEqualTo(3456L) + assertThat(fakeWearUtil.msTill(FakeWearUtil.REF_NOW - 6294L)).isEqualTo(-6294L) + assertThat(fakeWearUtil.msTill(FakeWearUtil.REF_NOW)).isEqualTo(0L) + assertThat(fakeWearUtil.msSince(FakeWearUtil.REF_NOW + 3456L)).isEqualTo(-3456L) + assertThat(fakeWearUtil.msSince(FakeWearUtil.REF_NOW - 6294L)).isEqualTo(6294L) } @Test fun joinSetTest() { @@ -33,7 +33,7 @@ class WearUtilTest : WearTestBase() { // THEN // we cannot guarantee order of items in joined string // but all items have to be there - assertThat(joined).hasLength(refSet.sumOf { it.length } + (refSet.size-1)) + assertThat(joined).hasLength(refSet.sumOf { it.length } + (refSet.size - 1)) assertThat("|$joined|").contains("|element1|") assertThat("|$joined|").contains("|second-elem|") assertThat("|$joined|").contains("|3rd|") @@ -47,7 +47,7 @@ class WearUtilTest : WearTestBase() { val set = persistence.explodeSet(serializedSet, ":") // THEN - assertThat(set).containsExactly( "element1", "second-elem", "3rd") + assertThat(set).containsExactly("element1", "second-elem", "3rd") } @Test fun explodeSetEmptyElemsTest() { @@ -69,7 +69,8 @@ class WearUtilTest : WearTestBase() { "3rd", "czwarty", "V", - "6") + "6" + ) // WHEN val joinedSet = persistence.joinSet(refSet, "#") @@ -97,14 +98,13 @@ class WearUtilTest : WearTestBase() { } */ @Test fun rateLimitTest() { - wearUtilMocker.prepareMockNoReal() // WHEN - val firstCall = wearUtil.isBelowRateLimit("test-limit", 3) - val callAfterward = wearUtil.isBelowRateLimit("test-limit", 3) - wearUtilMocker.progressClock(500L) - val callTooSoon = wearUtil.isBelowRateLimit("test-limit", 3) - wearUtilMocker.progressClock(3100L) - val callAfterRateLimit = wearUtil.isBelowRateLimit("test-limit", 3) + val firstCall = fakeWearUtil.isBelowRateLimit("test-limit", 3) + val callAfterward = fakeWearUtil.isBelowRateLimit("test-limit", 3) + fakeWearUtil.progressClock(500L) + val callTooSoon = fakeWearUtil.isBelowRateLimit("test-limit", 3) + fakeWearUtil.progressClock(3100L) + val callAfterRateLimit = fakeWearUtil.isBelowRateLimit("test-limit", 3) // THEN assertThat(firstCall).isTrue() diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt index 057d0614e3..b04cd1ad39 100644 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt @@ -1,14 +1,12 @@ package info.nightscout.androidaps.testing.mockers import info.nightscout.androidaps.data.RawDisplayData -import info.nightscout.androidaps.interaction.utils.WearUtil +import info.nightscout.androidaps.WearTestBase import info.nightscout.shared.SafeParse.stringToDouble import info.nightscout.rx.weardata.EventData import info.nightscout.rx.weardata.EventData.SingleBg -class RawDataMocker(wearUtil: WearUtil) { - - private val wearUtilMocker: WearUtilMocker = WearUtilMocker(wearUtil) +class RawDataMocker() { fun rawSgv(sgv: String?, m: Int, deltaString: String): RawDisplayData { val raw = RawDisplayData() @@ -25,7 +23,7 @@ class RawDataMocker(wearUtil: WearUtil) { } raw.singleBg = SingleBg( - wearUtilMocker.backInTime(0, 0, m, 0), + WearTestBase.backInTime(0, 0, m, 0), sgv!!, "", d, @@ -45,7 +43,7 @@ class RawDataMocker(wearUtil: WearUtil) { fun rawDelta(m: Int, delta: String): RawDisplayData { val raw = RawDisplayData() raw.singleBg = SingleBg( - wearUtilMocker.backInTime(0, 0, m, 0), + WearTestBase.backInTime(0, 0, m, 0), "", "", "", @@ -113,4 +111,4 @@ class RawDataMocker(wearUtil: WearUtil) { return raw } -} \ No newline at end of file +} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt deleted file mode 100644 index 4884c60e19..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt +++ /dev/null @@ -1,43 +0,0 @@ -package info.nightscout.androidaps.testing.mockers - -import info.nightscout.androidaps.interaction.utils.Constants -import info.nightscout.androidaps.interaction.utils.WearUtil -import info.nightscout.annotations.OpenForTesting -import org.mockito.ArgumentMatchers -import org.mockito.Mockito - -@OpenForTesting -class WearUtilMocker(private val wearUtil: WearUtil) { - - private var clockMsDiff = 0L - fun prepareMock() { - resetClock() - - // because we cleverly used timestamp() by implementation, we can mock it - // and control the time in tests - Mockito.`when`(wearUtil.timestamp()).thenReturn(REF_NOW + clockMsDiff) - } - - fun prepareMockNoReal() { - resetClock() - Mockito.doAnswer { REF_NOW + clockMsDiff }.`when`(wearUtil).timestamp() - Mockito.doReturn(null).`when`(wearUtil).getWakeLock(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()) - } - - private fun resetClock() { - clockMsDiff = 0L - } - - fun progressClock(byMilliseconds: Long) { - clockMsDiff += byMilliseconds - } - - fun backInTime(d: Int, h: Int, m: Int, s: Int): Long { - return REF_NOW - (Constants.DAY_IN_MS * d + Constants.HOUR_IN_MS * h + Constants.MINUTE_IN_MS * m + Constants.SECOND_IN_MS * s) - } - - companion object { - - const val REF_NOW = 1572610530000L - } -} \ No newline at end of file From 975a6c1fbe0e27c87e7c4421b3dc1b82aa9932bd Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 11 Sep 2023 10:51:53 +0200 Subject: [PATCH 34/34] New Crowdin updates (#2738) * Update source file strings.xml * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (Spanish) * New translations strings.xml (Bulgarian) * New translations strings.xml (Czech) * New translations strings.xml (German) * New translations strings.xml (Italian) * New translations strings.xml (Korean) * New translations strings.xml (Lithuanian) * New translations strings.xml (Dutch) * New translations strings.xml (Norwegian) * New translations strings.xml (Polish) * New translations strings.xml (Slovak) * New translations strings.xml (Swedish) * New translations strings.xml (Turkish) * New translations strings.xml (Portuguese, Brazilian) * Update source file strings.xml * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Hebrew) * New translations strings.xml (Lithuanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Lithuanian) * New translations strings.xml (Hebrew) * New translations strings.xml (Slovak) * New translations strings.xml (Dutch) * New translations strings.xml (Dutch) * New translations strings.xml (Czech) * New translations strings.xml (Dutch) * New translations strings.xml (Polish) * New translations strings.xml (Dutch) * New translations strings.xml (Turkish) * New translations strings.xml (Portuguese) * New translations strings.xml (Romanian) * New translations protection.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations strings.xml (Romanian) * New translations objectives.xml (Czech) * New translations strings.xml (Greek) * New translations strings.xml (Korean) * New translations strings.xml (Romanian) * New translations strings.xml (French) * New translations strings.xml (Spanish) * New translations strings.xml (Afrikaans) * New translations strings.xml (Bulgarian) * New translations strings.xml (Catalan) * New translations strings.xml (Czech) * New translations strings.xml (Danish) * New translations strings.xml (German) * New translations strings.xml (Greek) * New translations strings.xml (Hebrew) * New translations strings.xml (Hungarian) * New translations strings.xml (Italian) * New translations strings.xml (Korean) * New translations strings.xml (Lithuanian) * New translations strings.xml (Dutch) * New translations strings.xml (Norwegian) * New translations strings.xml (Polish) * New translations strings.xml (Portuguese) * New translations strings.xml (Russian) * New translations strings.xml (Slovak) * New translations strings.xml (Swedish) * New translations strings.xml (Turkish) * New translations strings.xml (Chinese Simplified) * New translations strings.xml (Portuguese, Brazilian) * Update source file strings.xml * Update source file strings.xml * New translations strings.xml (Czech) * New translations strings.xml (Hebrew) * New translations strings.xml (Norwegian) * New translations strings.xml (Slovak) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations exam.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Polish) * New translations strings.xml (Greek) * New translations strings.xml (Turkish) * New translations strings.xml (Greek) * New translations validator.xml (Greek) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Greek) * New translations strings.xml (Russian) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations protection.xml (Greek) * New translations exam.xml (Greek) * Update source file strings.xml * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Dutch) * New translations strings.xml (Polish) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Russian) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations validator.xml (Greek) * New translations strings.xml (Hebrew) * New translations strings.xml (Turkish) * New translations strings.xml (Norwegian) * New translations strings.xml (Portuguese) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (Spanish) * New translations strings.xml (Lithuanian) * New translations strings.xml (Spanish) * New translations strings.xml (Spanish) * New translations strings.xml (Spanish) * New translations strings.xml (Lithuanian) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Greek) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations objectives.xml (Russian) * New translations objectives.xml (Russian) * New translations strings.xml (Czech) --- .../src/main/res/values-el-rGR/strings.xml | 69 ++++ .../src/main/res/values-es-rES/strings.xml | 1 + .../src/main/res/values-fr-rFR/strings.xml | 1 + .../src/main/res/values-nl-rNL/strings.xml | 1 + .../src/main/res/values-pt-rBR/strings.xml | 1 + .../src/main/res/values-ru-rRU/strings.xml | 1 + app/src/main/res/values-el-rGR/strings.xml | 22 ++ app/src/main/res/values-ro-rRO/strings.xml | 8 + .../src/main/res/values-el-rGR/strings.xml | 4 +- .../src/main/res/values-el-rGR/strings.xml | 11 + .../src/main/res/values-el-rGR/protection.xml | 31 +- .../ui/src/main/res/values-el-rGR/strings.xml | 301 ++++++++++++++++++ .../ui/src/main/res/values-pt-rBR/strings.xml | 2 +- .../src/main/res/values-ro-rRO/protection.xml | 11 + .../ui/src/main/res/values-ro-rRO/strings.xml | 126 ++++++++ .../ui/src/main/res/values-ru-rRU/strings.xml | 4 + .../src/main/res/values-el-rGR/strings.xml | 8 +- .../src/main/res/values-el-rGR/validator.xml | 17 + .../src/main/res/values-ro-rRO/strings.xml | 12 + .../src/main/res/values-el-rGR/strings.xml | 12 +- .../src/main/res/values-el-rGR/strings.xml | 36 +++ .../src/main/res/values-pt-rBR/strings.xml | 34 +- .../src/main/res/values-ru-rRU/strings.xml | 8 +- .../src/main/res/values-el-rGR/strings.xml | 42 +++ .../src/main/res/values-ro-rRO/strings.xml | 10 + .../src/main/res/values-el-rGR/strings.xml | 8 + .../src/main/res/values-pt-rBR/strings.xml | 4 +- .../src/main/res/values-ro-rRO/strings.xml | 19 ++ .../src/main/res/values-ru-rRU/strings.xml | 2 + .../src/main/res/values-cs-rCZ/objectives.xml | 2 +- .../src/main/res/values-el-rGR/exam.xml | 1 + .../src/main/res/values-pt-rBR/exam.xml | 2 +- .../src/main/res/values-pt-rBR/strings.xml | 3 + .../src/main/res/values-ru-rRU/objectives.xml | 40 +-- .../src/main/res/values-ru-rRU/strings.xml | 10 +- .../src/main/res/values-ru-rRU/strings.xml | 6 +- .../src/main/res/values-af-rZA/strings.xml | 3 - .../src/main/res/values-bg-rBG/strings.xml | 3 - .../src/main/res/values-ca-rES/strings.xml | 3 - .../src/main/res/values-cs-rCZ/strings.xml | 3 - .../src/main/res/values-da-rDK/strings.xml | 3 - .../src/main/res/values-de-rDE/strings.xml | 3 - .../src/main/res/values-el-rGR/strings.xml | 3 - .../src/main/res/values-es-rES/strings.xml | 3 - .../src/main/res/values-fr-rFR/strings.xml | 3 - .../src/main/res/values-hu-rHU/strings.xml | 2 - .../src/main/res/values-it-rIT/strings.xml | 3 - .../src/main/res/values-iw-rIL/strings.xml | 3 - .../src/main/res/values-ko-rKR/strings.xml | 102 +++++- .../src/main/res/values-lt-rLT/strings.xml | 3 - .../src/main/res/values-nl-rNL/strings.xml | 7 +- .../src/main/res/values-no-rNO/strings.xml | 3 - .../src/main/res/values-pl-rPL/strings.xml | 3 - .../src/main/res/values-pt-rBR/strings.xml | 22 +- .../src/main/res/values-pt-rPT/strings.xml | 3 - .../src/main/res/values-ro-rRO/strings.xml | 3 - .../src/main/res/values-ru-rRU/strings.xml | 19 +- .../src/main/res/values-sk-rSK/strings.xml | 3 - .../src/main/res/values-sv-rSE/strings.xml | 3 - .../src/main/res/values-tr-rTR/strings.xml | 3 - .../src/main/res/values-zh-rCN/strings.xml | 3 - .../src/main/res/values-pt-rBR/strings.xml | 6 +- .../src/main/res/values-pt-rBR/strings.xml | 2 +- .../src/main/res/values-ro-rRO/strings.xml | 5 + .../src/main/res/values-ro-rRO/strings.xml | 4 +- .../src/main/res/values-ro-rRO/strings.xml | 2 + .../src/main/res/values-lt-rLT/strings.xml | 38 +-- .../src/main/res/values-ro-rRO/strings.xml | 1 + .../src/main/res/values-bg-rBG/strings.xml | 1 - .../src/main/res/values-cs-rCZ/strings.xml | 2 +- .../src/main/res/values-de-rDE/strings.xml | 1 - .../src/main/res/values-es-rES/strings.xml | 2 +- .../src/main/res/values-fr-rFR/strings.xml | 2 +- .../src/main/res/values-it-rIT/strings.xml | 1 - .../src/main/res/values-iw-rIL/strings.xml | 1 + .../src/main/res/values-ko-rKR/strings.xml | 109 +++++++ .../src/main/res/values-lt-rLT/strings.xml | 46 +-- .../src/main/res/values-nl-rNL/strings.xml | 2 +- .../src/main/res/values-no-rNO/strings.xml | 1 - .../src/main/res/values-pl-rPL/strings.xml | 2 +- .../src/main/res/values-pt-rBR/strings.xml | 1 - .../src/main/res/values-pt-rPT/strings.xml | 1 + .../src/main/res/values-sk-rSK/strings.xml | 2 +- .../src/main/res/values-sv-rSE/strings.xml | 1 - .../src/main/res/values-tr-rTR/strings.xml | 2 +- .../src/main/res/values-el-rGR/strings.xml | 80 +++++ .../src/main/res/values-es-rES/strings.xml | 5 + .../src/main/res/values-fr-rFR/strings.xml | 5 + .../src/main/res/values-iw-rIL/strings.xml | 3 + .../src/main/res/values-lt-rLT/strings.xml | 14 +- .../src/main/res/values-nl-rNL/strings.xml | 5 + .../src/main/res/values-ru-rRU/strings.xml | 5 + .../src/main/res/values-el-rGR/strings.xml | 4 + .../src/main/res/values-ro-rRO/strings.xml | 11 + .../src/main/res/values-ro-rRO/strings.xml | 28 ++ ui/src/main/res/values-el-rGR/strings.xml | 1 + ui/src/main/res/values-ro-rRO/strings.xml | 3 + wear/src/main/res/values-cs-rCZ/strings.xml | 6 + wear/src/main/res/values-el-rGR/strings.xml | 58 ++++ wear/src/main/res/values-es-rES/strings.xml | 6 + wear/src/main/res/values-fr-rFR/strings.xml | 6 + wear/src/main/res/values-iw-rIL/strings.xml | 6 + wear/src/main/res/values-ko-rKR/strings.xml | 60 ++++ wear/src/main/res/values-lt-rLT/strings.xml | 6 + wear/src/main/res/values-nl-rNL/strings.xml | 6 + wear/src/main/res/values-no-rNO/strings.xml | 6 + wear/src/main/res/values-pl-rPL/strings.xml | 6 + wear/src/main/res/values-pt-rPT/strings.xml | 5 + wear/src/main/res/values-ro-rRO/strings.xml | 33 ++ wear/src/main/res/values-ru-rRU/strings.xml | 5 + wear/src/main/res/values-sk-rSK/strings.xml | 1 + wear/src/main/res/values-tr-rTR/strings.xml | 6 + 112 files changed, 1491 insertions(+), 206 deletions(-) diff --git a/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml b/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml index 6e2511fd08..c9d67ec322 100644 --- a/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml +++ b/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml @@ -1,6 +1,13 @@ + %1$d λ πριν + %1$d λεπτά πριν + %1$.1f ω πριν + %1$.1f ημέρες πριν + %1$.0f ημέρες πριν + σε %1$.0f ημέρες + σε %1$.0f ημέρες h ημέρες ώρες @@ -15,10 +22,72 @@ ημέρες εβδομάδες m + ημ + Αργότερα σήμερα + Αύριο + Σήμερα + Χθες Σύνδεση για %1$d δευτερόλεπτα Δημιουργία σύνδεσης Συνδέθηκε Αποσυνδέεται + Αναμονή για αποσύνδεση + Δημιουργήθηκε: %1$s + Συντάκτης: %1$s + Όνομα: %1$s + Όνομα αρχείου: %1$s + Έκδοση πρόσθετου: %1$s + Όνομα: %1$s (%2$s) + Πληροφορίες: %1$s + Εμφάνιση IOB + Εμφάνιση λεπτομερούς IOB + Εμφάνιση COB + Εμφάνιση Διαφοράς + Εμφάνιση λεπτομερούς Διαφοράς + Εμφάνιση Μέσης Διαφοράς + Εμφάνιση Μπαταρίας Τηλεφώνου + Εμφάνιση Μπαταρίας Rig + Εμφάνιση Βασικού Ρυθμού + Εμφάνιση Κατάστασης Κυκλώματος + Εμφάνιση γλυκόζης αίματος + Εμφάνιση BGI + Εμφάνιση Βέλους Κατεύθυνσης + Εμφάνιση Πριν + Προεπιλεγμένη πρόσοψη ρολογιού, μπορείτε να κάνετε κλικ στο κουμπί ΕΞΑΓΩΓΗ ΠΡΟΣΟΨΗΣ για να δημιουργήσετε ένα πρότυπο + Προεπιλεγμένη πρόσοψη ρολογιού + Εικόνα φόντου + Γραφήματα (BG, βασικός, γραμμές πρόβλεψης...) + Εικόνα μπροστά από το γράφημα και πίσω από τα πεδία κειμένου + Ελεύθερο κείμενο 1 + Ελεύθερο κείμενο 2 + Ελεύθερο κείμενο 3 + Ελεύθερο κείμενο 4 + Ετικέτα IOB ή Άθροισμα IOB εάν είναι λεπτομερές + Άθροισμα IOB ή (Bolus_IOB|Basal_IOB) εάν είναι λεπτομερές + Ετικέτα COB + Τιμή COB + Βραχυπρόθεσμη διαφορά BG + Μέση διαφορά BG (15λεπτά) + Μπαταρία τηλεφώνου (%) + Μπαταρία συνολικού κυκλώματος (%) + Βασικός Ρυθμός + Τιμή BGI + Ώρα (ΩΩ:ΛΛ ή ΩΩ:ΜΜ:ΣΣ) + Ώρα (HH) + Λεπτό (MM) + Δευτερόλεπτο (SS) + ΠΜ ή ΜΜ + Όνομα της ημέρας της εβδομάδας + Ημέρα (DD) + Όνομα μήνα (σύντομο) + Κατάσταση κυκλώματος και πριν + Βέλος κατεύθυνσης + Λεπτά πριν από την τελευταία λήψη BG + Τιμή γλυκόζης αίματος + Εικόνα εξωφύλλου μπροστά από το κείμενο (κλήσεις...) + Εικόνα ώρας χεριού (Αναλογικό ρολόι) + Εικόνα λεπτού χεριού (Αναλογικό ρολόι) + Εικόνα δευτερολέπτου χεριού (Αναλογικό ρολόι) diff --git a/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml b/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml index 9762c43894..8f52bf8ca1 100644 --- a/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml +++ b/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml @@ -40,6 +40,7 @@ Nombre del archivo: %1$s Versión del plugin: %1$s Nombre: %1$s (%2$s) + Info: %1$s Mostrar IOB Mostrar IOB detallada Mostrar COB diff --git a/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml b/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml index a3a0d22cf4..d5b3b0ac07 100644 --- a/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml +++ b/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml @@ -40,6 +40,7 @@ Nom du fichier : %1$s Version du plugin : %1$s Nom : %1$s (%2$s) + Infos : %1$s Afficher IA Afficher IA détaillée Afficher GA diff --git a/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml b/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml index 3c80dd8877..3c56825f8e 100644 --- a/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml +++ b/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml @@ -40,6 +40,7 @@ Bestandsnaam: %1$s Plugin versie: %1$s Naam: %1$s (%2$s) + Info: %1$s Toon IOB Toon gedetailleerde IOB Toon COB diff --git a/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml b/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml index 932aee80a5..9f5d4585a4 100644 --- a/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml +++ b/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml @@ -40,6 +40,7 @@ Nome do arquivo: %1$s Versão do plugin: %1$s Nome: %1$s (%2$s) + Informações: %1$s Mostrar IA Mostrar detalhes da IA Mostrar CA diff --git a/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml b/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml index 5b863992db..3bbe6ac5ec 100644 --- a/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml +++ b/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml @@ -34,4 +34,5 @@ разъединение Ожидание разъединения + Отображать дельту diff --git a/app/src/main/res/values-el-rGR/strings.xml b/app/src/main/res/values-el-rGR/strings.xml index f55047d64d..dffce8a5a1 100644 --- a/app/src/main/res/values-el-rGR/strings.xml +++ b/app/src/main/res/values-el-rGR/strings.xml @@ -17,22 +17,44 @@ Σχετικά με Λείπει η άδεια κατάστασης τηλεφώνου Επιλογές συναγερμού + Δημιουργία ειδοποιήσεων από συναγερμούς του NS + Δημιουργία ειδοποιήσεων από ανακοινώσεις NS Οριακή τιμή για παλιά δεδομένα [min] Επείγουσα οριακή τιμή για παλιά δεδομένα [min] Ενεργοποιώντας το autosense θυμηθείτε να εισάγετε όλους τους υδατάνθρακες. Διαφορετικά, οι αποκλίσεις των υδατανθράκων θα εντοπιστούν λανθασμένα ως αλλαγή ευαισθησίας!! Δεν έχουν φορτωθεί όλα τα προφίλ! Οι τιμές δεν αποθηκεύτηκαν! ΜΗ ΕΓΚΥΡΟ + Σταδιακή αύξηση της έντασης για συναγερμούς και ειδοποιήσεις Τοπικές Ειδοποιήσεις Προειδοποίηση αν δεν ληφθούν δεδομένα μετρήσεων BG Προειδοποίηση αν η αντλία δεν είναι διαθέσιμη Όριο για μη διαθεσιμότητα της αντλίας [λεπτά] + Ειδοποίηση εάν απαιτούνται υδατάνθρακες Άνοιγμα μενού πλοήγησης Κλείσιμο μενού πλοήγησης + Αφαίρεση αντικειμένου + Ταξινόμηση στοιχείων Ελλιπή δεδομένα θεραπείας Μια θεραπεία (ινσουλίνη: %1$.2f, υδατάνθρακες: %2$d, στο: %3$s) δεν μπορεί να προστεθεί στις θεραπείες. Παρακαλούμε ελέγξτε και προσθέστε χειροκίνητα μια εγγραφή ανάλογα με την περίπτωση. eCarbs: %1$d g (%2$d h), καθυστέρηση: %3$d m == ∑ %1$s U Μονάδες + Εμφάνιση αφαιρεμένων + Εκκαθάριση ουράς? Όλα τα δεδομένα στην ουρά θα χαθούν! + Μενού διαγράμματος + Η εξουσιοδότηση απέτυχε + Αδυναμία δημιουργίας προφίλ. Το προφίλ δεν είναι έγκυρο. + Κατάργηση φίλτρου + Υποδόριος καθετήρας + Διεύθυνση E-mail + Αφαίρεση αναγνώσεων γλυκόζης αίματος BG + Η ταυτοποίηση δεν έχει οριστεί στη λειτουργία προγραμματισμού + διάλογος + Άγνωστη εντολή ενέργειας: + Αφαίρεση επιλεγμένων στοιχείων + Επιλέχθηκε %1$d + Ταξινόμηση + Αναζήτηση diff --git a/app/src/main/res/values-ro-rRO/strings.xml b/app/src/main/res/values-ro-rRO/strings.xml index 8946287a42..50a678632d 100644 --- a/app/src/main/res/values-ro-rRO/strings.xml +++ b/app/src/main/res/values-ro-rRO/strings.xml @@ -33,6 +33,8 @@ Alertează dacă sunt necesari carbohidrați Afișare navigație Închidere navigație + Elimină obiecte + Sortează obiecte Date incomplete despre tratament Un tratament (insulină: %1$.2f, carbohidrați: %2$d, la: %3$s) nu a putut fi înregistrat. Reverificați și apoi adăugați manual înregistrarea corectă. eCarbohidrați: %1$d g (%2$d h), întârziere: %3$d m @@ -46,7 +48,13 @@ Șterge filtru Canula Adresă de e-mail + Eliminați valorile glicemiei Identificarea nu este setată în modul dezvoltator + dialog + Comandă de acțiune necunoscută: + Șterge obiectele selectate + %1$d selectat(e) Sortează + Caută diff --git a/core/graph/src/main/res/values-el-rGR/strings.xml b/core/graph/src/main/res/values-el-rGR/strings.xml index 3ea04e700d..ddc4b0eb74 100644 --- a/core/graph/src/main/res/values-el-rGR/strings.xml +++ b/core/graph/src/main/res/values-el-rGR/strings.xml @@ -1,2 +1,4 @@ - + + %1$d g + diff --git a/core/interfaces/src/main/res/values-el-rGR/strings.xml b/core/interfaces/src/main/res/values-el-rGR/strings.xml index 5e798c0d22..662f08c236 100644 --- a/core/interfaces/src/main/res/values-el-rGR/strings.xml +++ b/core/interfaces/src/main/res/values-el-rGR/strings.xml @@ -1,9 +1,20 @@ + Μορφή αρχείου + Δημιουργήθηκε στις + Έκδοση AAPS + Δημιουργία Παραλλαγής + Εξαγωγή ονόματος συσκευής ασθενούς + Εξαγωγή μοντέλου συσκευής + Κρυπτογράφηση αρχείων + Νέα κρυπτογραφημένη μορφή + Νέα μορφή εντοπισμού σφαλμάτων (μη κρυπτογραφημένη) + Άγνωστη μορφή εξαγωγής * Υποστηρίζονται μόνο διακριτές τιμές και όχι εύρος τιμών για βασικό/bolus στην εικονική αντλία. + Ο οδηγός της αντλίας άλλαξε. %1$.1f U %1$.2f U diff --git a/core/ui/src/main/res/values-el-rGR/protection.xml b/core/ui/src/main/res/values-el-rGR/protection.xml index 3ea04e700d..d9606c64ed 100644 --- a/core/ui/src/main/res/values-el-rGR/protection.xml +++ b/core/ui/src/main/res/values-el-rGR/protection.xml @@ -1,2 +1,31 @@ - + + Απαιτείται πιστοποίηση + Τοποθετήστε το δάχτυλό σας στον αναγνώστη δακτυλικών αποτυπωμάτων για να επαληθεύσετε την ταυτότητά σας + Προστασία ρυθμίσεων + Προστασία εφαρμογής + Προστασία Bolus + Κωδικός πρόσβασης στις ρυθμίσεις + PIN Ρυθμίσεων + Κωδικός πρόσβασης Εφαρμογής + PIN Εφαρμογής + Κωδικός πρόσβασης για Bolus + Bolus PIN + Διατήρηση κωδικού πρόσβασης και PIN [s] + Χρόνος πριν ο κωδικός πρόσβασης ή το PIN πρέπει να εισαχθεί + Βιομετρικά + Προσαρμοσμένος κωδικός + Προσαρμοσμένο PIN + Καμία προστασία + Μη Ασφαλής Επανάκληση + Για να είναι αποτελεσματική, η βιομετρική προστασία, χρειάζεται να οριστεί ένας κωδικός master για δυνατότητα επανάκλησης.\n\nΠαρακαλώ ρυθμίστε ένα κωδικό master! + Ο κωδικός ορίστηκε! + Το PIN ορίστηκε! + Ο κωδικός δεν ορίστηκε + Το PIN δεν ορίστηκε + Ο κωδικός δεν άλλαξε + Το PIN δεν άλλαξε + Το PIN διαγράφηκε! + Εισάγετε τον κωδικό εδώ + Εισάγετε το PIN εδώ + diff --git a/core/ui/src/main/res/values-el-rGR/strings.xml b/core/ui/src/main/res/values-el-rGR/strings.xml index 35b1328778..f557f140cc 100644 --- a/core/ui/src/main/res/values-el-rGR/strings.xml +++ b/core/ui/src/main/res/values-el-rGR/strings.xml @@ -2,8 +2,10 @@ Ανανέωση + Σφάλμα Το Βασικό προφίλ στην αντλία ενημερώθηκε Μη έγκυρα δεδομένα + Έγχυση %1$.2f U Εφαρμόστηκαν Περιορισμοί! Συνολική IOB: TT @@ -12,6 +14,7 @@ %1$.2f U/h Η αντλία δεν έχει ρυθμιστεί, δεν ορίστηκε προφίλ! Αποτυχία αναβάθμισης βασικού προφίλ + Δόση Bolus %1$.2f U χορηγήθηκε επιτυχώς Διαβάζεται από την αντλία μη έγκυρος βασικός ρυθμός Περιορίζεται η IOB σε %1$.1f U λόγω %2$s ΤΟ ΚΥΚΛΩΜΑ ΑΠΕΝΕΡΓΟΠΟΙΗΘΗΚΕ ΑΠΟ ΠΕΡΙΟΡΙΣΜΟΥΣ @@ -29,27 +32,38 @@ Χρήστης Αποτέλεσμα Ρυθμίσεις + Ενδείξεις κατάστασης Ανέβασμα δεδομένων BG στο NS Ινσουλίνη n/a + Κύριος κωδικός + Εξαγωγή καταχωρήσεων χρήστη σε Excel (csv) Επιβεβαίωση Αντλία Χαμένες μετρήσεις BG IOB: + Σίγαση για 5 λεπτά Σίγαση Επιτυχία + Ρυθμίσεις για Προχωρημένους Σφάλμα έγχυσης εκτεταμένου bolus + Λειτουργία APS Εκτεταμένο bolus Παύση TDD σύνολο Πρόκειται να εγχυθούν %1$.2f μονάδες Αναμονή για αντλία + Το AAPS ξεκίνησε %1$+.2f U + %1$d g %1$.2f h + %1$d λεπτά Βήματα Περιμένετε… Stop Υδατάνθρακες + Μη έγκυρο προφίλ! + ΔΕΝ ΟΡΙΣΤΗΚΕ ΠΡΟΦΙΛ ]]> Ημερομηνία Μονάδες @@ -58,8 +72,13 @@ ISF Βασικός Ρυθμός Στόχος + Διάρκεια Δράσης Ινσουλίνης + Αναλογία Ινσουλίνης προς Υδατάνθρακες + Συντελεστής Ευαισθησίας στην Ινσουλίνης Βασικός Ρυθμός + Στόχος Γλυκόζης Αίματος g + % Bluetooth BT Watchdog Απενεργοποιεί το bluetooth του τηλεφώνου για ένα δευτερόλεπτο αν δεν είναι δυνατή η σύνδεση με την αντλία. Αυτό μπορεί να βοηθήσει σε ορισμένα τηλέφωνα όπου το bluetooth παγώνει. @@ -84,41 +103,78 @@ Όνομα: Χρόνος WiFi SSID + Φόρτωση… Σημειώσεις Διαγραφή + Προσθήκη νέου + Προσθήκη νέου πάνω + Τα δεδομένα προέρχονται από διαφορετική αντλία. Αλλάξτε τον οδηγό της αντλίας για να επαναφέρετε την κατάσταση της αντλίας. BG Καλιμπράρισμα + Εκτέλεση συναγερμού σε %1$d λεπτά Το Bolus ανέφερε ένα σφάλμα. Ελέγξτε χειροκίνητα την ποσότητα που έχει πραγματικά χορηγηθεί + Υπενθύμιση Bolus Διάρκεια g Η αντλία είναι σε παύση Δεν έχει ρυθμιστεί Κύκλωμα σε αναστολή + Βέλος τάσης + Auto sens + req + ταχεία πτώση + πτώση + αργή πτώση + σταθερό + αργή αύξηση + αύξηση + ταχεία αύξηση + κανένα άγνωστο υψηλό + εντός στόχου χαμηλό + Μέση + TIR ]]> ΜΕΤΑΚΙΝΗΣΗ Ενεργοποίηση προφίλ επαναφορά Η αλλαγή προφίλ λείπει. Αλλάξτε το προφίλ ή πατήστε \"Ενεργοποίηση Προφίλ\" στο Τοπικό Προφίλ. Προφίλ + Επιλέξτε για αφαίρεση + Είστε βέβαιοι ότι θέλετε να καταργήσετε %1$d στοιχεία Θεραπεία + Δημιουργία νέου προφίλ από αυτό το προφίλ; Ρυθμίσεις Γρήγορου Οδηγού Γραφική 15min COB Bolus IOB Βασική ΙΟΒ ΜΗ ΕΓΚΥΡΟ + Σύνδεση + Πλήρωση/Γέμισμα Ινσουλίνη Λήξη προσ. στόχου Κλειστό Κύκλωμα Ανοιχτό Κύκλωμα Αναστολή Χαμηλής Γλυκόζης + DIA + IC + ISF + Απέτυχε η Ακύρωση Προσωρινού Ρυθμού + Η ακύρωση της εκτεταμένης δόσης bolus απέτυχε + Φόρτωση κατάστασης αντλίας στο NS ή στο Tidepool + Απενεργοποιημένο/Αναστολή κυκλώματος + Ενεργή Ινσουλίνη (IOB) Λάθος κωδικός + Λάθος PIN + Οι κωδικοί δεν ταιριάζουν + Τα PINs δεν ταιριάζουν Οι τιμές του βασικού ρυθμού δεν αντιστοιχούν σε ώρες: %1$s + Η τιμή του βασικού αντικαταστάθηκε από την ελάχιστη υποστηριζόμενη τιμή: %1$s Η τιμή του βασικού αντικαταστάθηκε από την μέγιστη υποστηριζόμενη τιμή: %1$s /U U/h @@ -126,6 +182,7 @@ Έναρξη προφίλ %1$d%% για %2$d λεπτά + Ακύρωση προσωρινού βασικού ρυθμού Αφήστε τον προσωρινό ρυθμό ενεργό Τιμή Διάρκεια @@ -134,14 +191,25 @@ Μη έγκυρο προφίλ: %1$s + %1$d λεπτά Φροντίδα Έλεγχος BG + Χειροκίνητη εισαγωγή γλυκόζης αίματος ή βαθμονόμηση Ανακοίνωση Σημείωση Ερώτηση Άσκηση + Ανακοίνωση : %1$s + Σημείωση: %1$s + Ερώτηση : %1$s + Άσκηση : %1$s + Αλλαγή σημείου αντλίας + Εισαγωγή Αισθητήρα CGM Έναρξη Αισθητήρα CGM + Διακοπή Αισθητήρα CGM + Ειδοποίηση D.A.D. + Αλλαγή Αμπούλας Ινσουλίνης Αλλαγή Προφίλ Bolus για σνακ Bolus Γεύματος @@ -151,6 +219,10 @@ Τέλος Προσ Ρυθμού Διόρθωση Υδατανθράκων OpenAPS εκτός σύνδεσης + Αλλαγή Μπαταρίας Αντλίας + Προσωρινός στόχος + Τιμή Προσωρινού στόχου + Ακύρωση προσωρινού στόχου Οδηγός Bolus Δάκτυλο Αισθητήρας @@ -163,6 +235,8 @@ Αυτοματισμός Προσαρμογή Κύκλωμα + NS + Εγγραφή Ο χρόνος σύνδεσης έληξε @@ -173,7 +247,9 @@ Περιμένετε για αποτέλεσμα SMB + %1$d g επιπλέον υδατάνθρακες απαιτούνται μέσα σε %2$d λεπτά + Άθροισμα TDD Εκθετικά Σταθμισμένο TDD Βασικός Ρυθμός Bolus @@ -182,35 +258,236 @@ # Ημέρες Βάρος Πιθανώς ανακριβής όταν χρησιμοποιείτε bolus για πλήρωση/γέμισμα! + Παλιά δεδομένα, παρακαλώ πατήστε \"ΕΠΑΝΑΦΟΡΤΩΣΗ\" Συνολικός Βασικός Ρυθμός TBB * 2 + Ανίχνευση χρόνου + BOLUS + ΥΠΟΛΟΓΙΣΤΗΣ BOLUS + ΣΥΜΒΟΥΛΟΣ BOLUS + ΕΚΤΕΤΑΜΕΝΟ BOLUS + SUPERBOLUS TBR ΥΔΑΤΑΝΘΡΑΚΕΣ + ΕΚΤΕΤΑΜΕΝΟΙ ΥΔΑΤΑΝΘΡΑΚΕΣ + ΠΡΟΣΩΡΙΝΟΣ ΒΑΣΙΚΟΣ + ΠΡΟΣΩΡΙΝΟΣ ΣΤΟΧΟΣ + ΝΕΟ ΠΡΟΦΙΛ + ΚΛΩΝΟΠΟΙΗΣΗ ΠΡΟΦΙΛ + ΑΠΟΘΗΚΕΥΣΗ ΠΡΟΦΙΛ + ΕΝΑΛΛΑΓΗ ΠΡΟΦΙΛ + ΚΛΩΝΟΠΟΙΗΣΗ ΕΝΑΛΛΑΓΗΣ ΠΡΟΦΙΛ + ΛΕΙΤΟΥΡΓΙΑ ΚΛΕΙΣΤΟΥ ΚΥΚΛΩΜΑΤΟΣ + ΛΕΙΤΟΥΡΓΙΑ ΚΥΚΛΩΜΑΤΟΣ LGS + ΛΕΙΤΟΥΡΓΙΑ ΑΝΟΙΚΤΟΥ ΚΥΚΛΩΜΑΤΟΣ + ΑΠΕΝΕΡΓΟΠΟΙΗΣΗ ΚΥΚΛΩΜΑΤΟΣ + ΕΝΕΡΓΟΠΟΙΗΣΗ ΚΥΚΛΩΜΑΤΟΣ + ΕΝΑΝΑΣΥΝΔΕΣΗ + ΑΠΟΣΥΝΔΕΣΗ + ΕΠΑΝΑΦΟΡΑ + ΑΝΑΣΤΟΛΗ + ΑΝΤΛΙΑ HW ΕΠΙΤΡΕΠΕΤΑΙ + ΚΑΘΑΡΙΣΜΟΣ ΚΛΕΙΔΙΩΝ ΖΕΥΓΟΠΟΙΗΣΗΣ + ΑΠΟΔΟΧΗ ΠΡΟΣΩΡΙΝΟΥ ΒΑΣΙΚΟΥ + ΑΚΥΡΩΣΗ ΠΡΟΣΩΡΙΝΟΥ ΒΑΣΙΚΟΥ + ΑΚΥΡΩΣΗ BOLUS + ΑΚΥΡΩΣΗ ΕΚΤΕΤΑΜΕΝΟΥ BOLUS + ΑΚΥΡΩΣΗ ΠΡΟΣΩΡΙΝΟΥ ΣΤΟΧΟΥ + CAREPORTAL + ΑΛΛΑΓΗ ΣΗΜΕΙΟΥ + ΑΛΛΑΓΗ ΔΕΞΑΜΕΝΗΣ + ΒΑΘΜΟΝΟΜΗΣΗ + ΠΡΩΤΕΥΟΝ BOLUS + ΘΕΡΑΠΕΙΑ + ΑΝΑΝΕΩΣΗ CAREPORTAL NS + ΑΝΑΝΕΩΣΗ ΑΛΛΑΓΗΣ ΠΡΟΦΙΛ NS + ΑΝΑΝΕΩΣΗ ΘΕΡΑΠΕΙΩΝ NS + ΑΝΑΝΕΩΣΗ ΠΡΟΣΩΡΙΝΟΥ ΣΤΟΧΟΥ NS + ΑΥΤΟΜΑΤΙΣΜΟΣ ΑΦΑΙΡΕΘΗΚΕ + ΜΕΤΡΗΣΗ ΓΛΥΚΟΖΗΣ ΑΙΜΑΤΟΣ ΑΦΑΙΡΕΘΗΚΕ + CAREPORTAL ΑΦΑΙΡΕΘΗΚΕ + BOLUS ΑΦΑΙΡΕΘΗΚΕ + ΥΔΑΤΑΝΘΡΑΚΕΣ ΑΦΑΙΡΕΘΗΚΑΝ + ΠΡΟΣΩΡΙΝΟΣ ΒΑΣΙΚΟΣ ΑΦΑΙΡΕΘΗΚΕ + ΕΚΤΕΤΑΜΕΝΟ BOLUS ΑΦΑΙΡΕΘΗΚΕ + ΤΡΟΦΗ + ΑΦΑΙΡΕΣΗ ΤΡΟΦΗΣ + ΑΦΑΙΡΕΣΗ ΠΡΟΦΙΛ + ΑΦΑΙΡΕΣΗ ΑΛΛΑΓΗΣ ΠΡΟΦΙΛ + ΑΦΑΙΡΕΣΗ ΕΠΑΝΕΝΑΡΞΗΣ ΓΕΓΟΝΟΤΩΝ + ΑΦΑΙΡΕΣΗ ΘΕΡΑΠΕΙΩΝ + ΠΡΟΣΩΡΙΝΟΣ ΒΑΣΙΚΟΣ ΑΦΑΙΡΕΘΗΚΕ + ΠΑΥΣΗ NS + ΑΠΟΚΑΤΑΣΤΑΣΗ NS + ΕΚΚΑΘΑΡΙΣΗ ΟΥΡΑΣ NS + ΑΝΤΙΓΡΑΦΗ ΡΥΘΜΙΣΕΩΝ NS + ΠΑΡΑΘΥΡΟ ΣΦΑΛΜΑΤΟΣ ΟΚ + ΠΑΡΑΘΥΡΟ ΣΦΑΛΜΑΤΟΣ ΣΙΓΑΣΗ + ΠΑΡΑΘΥΡΟ ΣΦΑΛΜΑΤΟΣ ΣΙΓΑΣΗ 5ΛΕΠΤΑ + ΕΝΑΡΞΗ ΣΤΟΧΟΥ + ΠΑΡΑΛΗΨΗ ΣΤΟΧΟΥ + ΕΠΑΝΑΦΟΡΑ ΣΤΑΤΙΣΤΙΚΩΝ + ΔΙΑΓΡΑΦΗ ΚΑΤΑΓΡΑΦΩΝ + ΔΙΑΓΡΑΦΗ ΜΕΛΛΟΝΤΙΚΩΝ ΘΕΡΑΠΕΙΩΝ + Διαγραφή μελλοντικών θεραπειών + ΕΞΑΓΩΓΗ ΡΥΘΜΙΣΕΩΝ + ΕΙΣΑΓΩΓΗ ΡΥΘΜΙΣΕΩΝ + ΕΠΑΝΑΦΟΡΑ ΒΑΣΕΩΝ ΔΕΔΟΜΕΝΩΝ + ΕΚΚΑΘΑΡΙΣΗ ΒΑΣΕΩΝ ΔΕΔΟΜΕΝΩΝ + ΕΞΑΓΩΓΗ ΒΑΣΕΩΝ ΔΕΔΟΜΕΝΩΝ + ΕΙΣΑΓΩΓΗ ΒΑΣΕΩΝ ΔΕΔΟΜΕΝΩΝ + ΕΞΑΓΩΓΗ OTP + ΕΠΑΝΑΦΟΡΑ OTP + ΔΙΑΚΟΠΗ SMS + ΕΞΑΓΩΓΗ ΕΓΓΡΑΦΩΝ ΧΡΗΣΤΗ + ΕΝΑΡΞΗ AAPS + ΕΞΟΔΟΣ ΑΠΟ AAPS + ΕΝΕΡΓΟΠΟΙΗΣΗ ΠΡΟΣΘΕΤΟΥ + ΑΠΕΝΕΡΓΟΠΟΙΗΣΗ ΠΡΟΣΘΕΤΟΥ + ΑΓΝΩΣΤΟ + Συμβολοσειρά + Πηγή + Μετατόπιση UTC Ενέργεια + Χρονοσήμανση + Χωρίς Μονάδα + ΤΟ ΚΥΚΛΩΜΑ ΑΛΛΑΞΕ + ΤΟ ΚΥΚΛΩΜΑ ΑΦΑΙΡΕΘΗΚΕ + ΑΛΛΟ + Χαμηλός στόχος προφίλ + Υψηλός στόχος προφίλ + Κάτω τιμή προσωρινού στόχου + Πάνω τιμή προσωρινού στόχου + Τιμή προσωρινού στόχου + Τιμή DIA του προφίλ + Τιμή ευαισθησίας προφίλ + Μέγιστη τιμή βασικού ρυθμού προφίλ + Τρέχουσα τιμή βασικού + Τιμή αναλογίας υδατανθράκων προφίλ Το %1$.2f περιορίζεται σε %2$.2f + » Το%1$s« είναι εκτός ορίων + Η τιμή »%1$s« %2$.2f είναι εκτός ορίων + Τιμή Βασικού ρυθμού + BOLUS %1$.2f U + ΥΔΑΤΑΝΘΡΑΚΕΣ %1$d g + ΕΚΤΕΤΑΜΕΝΟ BOLUS %1$.2f U %2$d λεπτά + ΦΟΡΤΩΣΗ ΓΕΓΟΝΟΤΩΝ + ΕΚΚΑΘΑΡΙΣΗ ΣΥΝΑΓΕΡΜΩΝ + ΑΠΕΝΕΡΓΟΠΟΙΗΣΗ + ΧΡΟΝΟΣ ΕΝΗΜΕΡΩΣΗΣ + ΦΟΡΤΩΣΗ ΙΣΤΟΡΙΚΟΥ %1$d + ΦΟΡΤΩΣΗ ΤΩΝ TDD + ΟΡΙΣΜΟΣ ΠΡΟΦΙΛ + ΟΡΙΣΜΟΣ ΡΥΘΜΙΣΕΩΝ ΧΡΗΣΤΗ + SMB BOLUS %1$.2f U + ΕΝΑΡΞΗ ΑΝΤΛΙΑΣ + ΔΙΑΚΟΠΗ ΑΝΤΛΙΑΣ + ΠΡΟΣΩΡΙΝΟΣ ΒΑΣΙΚΟΣ ΡΥΘΜΟΣ %1$.2f U/h %2$d λεπτά + ΠΡΟΣΩΡΙΝΟΣ ΒΑΣΙΚΟΣ ΡΥΘΜΟΣ %1$d%% %2$d λεπτά + ΟΡΙΣΜΟΣ INSIGHT TBR ΜΕΣΩ ΕΙΔΟΠΟΙΗΣΗΣ + ΑΝΑΓΝΩΣΗ ΚΑΤΑΣΤΑΣΗΣ %1$s + KeepAlive. Κατάσταση ξεπερασμένη. + KeepAlive. Βασικός ρυθμός πεπερασμένος. SMS %1$.0f%% Βασικός Ρυθμός Βασικός Ρυθμός % + αρχείο χρήστης + Autotune + Βοήθεια για πιθανές προσαρμογές του προφίλ (ISF, αναλογία υδατανθράκων και βασικοί ρυθμοί) + AT + Ρυθμίσεις Autotune + Αυτοματισμός Εναλλαγής Προφίλ + Αν ενεργοποιηθεί, το Autotune θα ενημερώνει αυτόματα και θα αλλάζει το προεπιλεγμένο Προφίλ μετά τον υπολογισμό από έναν κανόνα αυτοματισμού. + Κατηγοριοποίηση του UAM ως βασικού + Ενεργοποιήστε μόνο αν έχετε εισαγάγει αξιόπιστα όλους τους υδατάνθρακες που καταναλώνονται, με αυτή την επιλογή ξαφνικές αυξήσεις που εμφανίζονται θα χρησιμοποιηθούν από το Autotune για να προτείνουν αλλαγές στο βασικό ρυθμό. + Συντονισμός καμπύλης ινσουλίνης + Ενεργοποιήστε μόνο αν χρησιμοποιείτε free peak. Αυτή η επιλογή θα συντονίσει τις διάρκειες των peak και DIA + Αριθμός ημερών δεδομένων + Εφαρμόστε το μέσο αποτέλεσμα σε κιρκαδικό IC/ISF + Το Autotune δεν θα συντονίσει τις κιρκαδικές παραλλαγές, αυτή η επιλογή ισχύει μόνο για του μέσο συντονισμό του IC και ISF στο κιρκαδικό προφίλ εισόδου σας + Συμπερίληψη περισσότερων πληροφοριών καταγραφής για τον εντοπισμό σφαλμάτων + Ενεργοποιήστε μόνο αν ζητηθεί από τον προγραματιστή η αποστολή περισσότερων πληροφοριών καταγραφής για να βοηθήσει στην αποσφαλμάτωση του προσθέτου Autotune + Προεπιλεγμένος αριθμός ημερών δεδομένων προς επεξεργασία από το Autotune (έως 30) + Συντονισμένο + Προφίλ : + Ημέρες συντονισμού: + Τελευταίος Υπολογισμός : + Προειδοποίηση : + Επιλέξτε προφίλ για συντονισμό + Το επιλεγμένο προφίλ έχει τιμές IC %1$d. Το Autotune θα χρησιμοποιήσει %2$.2f g/U + Το επιλεγμένο προφίλ έχει τιμές ISF %1$d. Το Autotune θα χρησιμοποιήσει %2$.1f %3$s/U + Σφάλμα στα εισαχθέντα δεδομένα, προσπαθήστε να εκτελέσετε ξανά το autotune ή μειώστε τον αριθμό των ημερών + Σφάλμα στα εισαχθέντα δεδομένα , αυξήστε τον αριθμό των ημερών + Ο υπολογισμός Autotune ξεκίνησε, παρακαλώ να είστε υπομονετικοί + Ελέγξτε προσεκτικά τα αποτελέσματα πριν τα χρησιμοποιήσετε! + Ημέρα μερικού αποτελέσματος %1$d / %2$d ρυθμίστηκε Αποτέλεσμα: %1$s + Παράμετρος + % Χαμένες + Προφίλ Autotune %1$s + Εκτέλεση Autotune + Έλεγχος προφίλ εισόδου + Σύγκριση προφίλ + Αντιγραφή στο τοπικό προφίλ + Ενημέρωση προφίλ εισόδου + Επαναφορά προφίλ εισόδου + Δημιουργία ενός νέου τοπικού προφίλ από αυτό το Προφίλ Autotune; + Ενημέρωση του προφίλ %1$s με το Προφίλ Autotune; + Επαναφορά προφίλ %1$s με Προφίλ Εισαγωγής; + Μη έγκυρο προφίλ + Το Autotune έτρεξε χωρίς αλλαγή προφίλ + Το Autotune έτρεξε έγινε αυτόματη αλλαγή προφίλ + Σφάλμα κατά την τελευταία εκτέλεση του Autotune + Εντοπίστηκε μια άλλη εκτέλεση του Autotune, η εκτέλεση ακυρώθηκε Χρησιμοποιήστε ειδοποιήσεις συστήματος για ειδοποιήσεις και συναγερμούς Συναγερμός έκτακτης ανάγκης Πληροφορίες + Σύμβουλος Bolus + Έχετε υπεργλυκαιμία. Αντί να φάτε τώρα συνιστάτε να περιμένετε μια καλύτερη γλυκαιμία. Θέλετε να κάνετε ένα διορθωτικό bolus τώρα και να γίνει υπενθύμιση όταν έρθει η ώρα να φάτε; Σε αυτή την περίπτωση δε θα καταγραφούν καθόλου υδατάνθρακες και θα πρέπει να χρησιμοποιήσετε τον οδηγό ξανά μετά την υπενθύμιση. + COB vs IOB (ενεργοί υδατάνθρακες vs ενεργή ινσουλίνη) !!!!! Μικρή απορρόφηση υδατανθράκων ανιχνεύτηκε: %2$d%% της ώρας. Τσεκάρετε τους υπολογισμούς σας. COB μπορεί να υπερεκτιμήθηκε και να δόθηκε περισσότερη ινσουλίνη!!!!!]]> Χορήγηση του αποτελέσματος αυτού του μέρους του υπολογισμού bolus [%] + Χρονικό όριο παλιάς γλυκαιμίας [min] + Ορίστηκε περιορισμός Bolus: %1$.2f U σε %2$.2f U + Το Bolus μόνο θα καταγραφεί (δε θα χορηγηθεί από την αντλία) + Εκτέλεση συναγερμού όταν έρθει η ώρα να φάτε Δεν έχει επιλεγεί καμία ενέργεια, δεν υπάρχει τίποτα να κάνει + Δεν υπάρχει πρόσφατή γλυκόζη αίματος για να γίνει υπολογισμός! + Δεν ορίστηκε ενεργό προφίλ! + Άγνωστο COB! Λείπει Η ανάγνωση γλυκόζης αίματος ή έγινε πρόσφατα επανεκκίνηση της εφαρμογής; + Παραβίαση περιορισμού υδατανθράκων! + Υπολογισμός (IC: %1$.1f, ISF: %2$.1f) + Υδατάνθρακες: %1$.2fU + COB: %1$.0fg %2$.2fU + BG: %1$.2fU + IOB: %1$.2fU + Superbolus: %1$.2fU + Τάση 15\': %1$.2fU + Ποσοστό: %1$.2fU x %2$d%% ≈ %3$.2fU + Παραβίαση περιορισμού ινσουλίνης!\nΔεν μπορούν να χορηγηθούν %1$.2fU + Προσωρινός Στόχος: %1$s + %1$s σε %2$s + Δεν υπάρχει διαθέσιμη αντλία! + Γρήγορος Οδηγός + Παιδί Έφηβος Ενήλικας + Ενήλικας με ανοχή στην ινσουλίνη Κύηση + Παρακαλώ επιλέξτε τύπο ασθενούς για να ορισθούν τα όρια ασφαλείας + Μέγιστο επιτρεπτό bolus[U] + Μέγιστο επιτρεπτό υδατανθράκων [g] + Τύπος ασθενή Ξεκλείδωμα ρυθμίσεων @@ -224,14 +501,23 @@ Serial number Αποσυνδέθηκε Συνδέεται + Πατήθηκε σύνδεση στην αντλία %1$.0f / %2$d U Μονάδες ανά ημέρα + Εικονίδιο αντλίας Δείτε το προφίλ + Ιστορικό αντλίας + Στατιστικά + Αλλαγή οδηγού αντλίας. + Η συσκευή άλλαξε + Bolus OK Σφάλμα παράδοσης Προσ Ρυθμού Μη ορισμένο Αντλία απασχολημένη Λάθος σύνδεσης αντλίας Ανάγνωση ιστορικού αντλίας + Ο κωδικός εκκαθαρίστηκε! + Σύζευξη Παραμετροποίηση... Ο μέγιστος βασικός ρυθμός περιορίζεται σε %1$.2f U/h λόγω ότι %2$s @@ -242,6 +528,7 @@ Επιβεβαίωση + Μήνυμα ΟΚ Ακύρωση ΑΠΟΡΡΙΨΗ @@ -251,12 +538,20 @@ Θα σας ζητηθεί ο βασικός κωδικός πρόσβασης, ο οποίος είναι απαραίτητος για την αποκωδικοποίηση των εισαγώμενων προτιμήσεων. + μείωση %1$s κατά %2$s + αύξηση %1$s κατά %2$s + Συμπληρώθηκε το επιτρεπόμενο όριο + %1$dh %2$dm Ώρα Συμβάντος + Η εφαρμογή χρειάζεται άδεια Bluetooth + Αίτημα χρήστη + Αντλία σε ζεύξη Χαμηλή ενέργεια Bluetooth δεν υποστηρίζεται. + Το Bluetooth Low Energy δεν υποστηρίζεται ή η συσκευή δεν είναι συνδεδεμένη. Bluetooth μη ενεργοποιημένο. Τοποθεσία μη ενεργοποιημένη Για την εύρεση Bluetooth σε νεότερες συσκευές, η τοποθεσία πρέπει να είναι ενεργοποιημένη. Το AAPS δεν παρακολουθεί την τοποθεσία σας και μπορεί να απενεργοποιηθεί μετά την επιτυχή σύζευξη. @@ -265,6 +560,9 @@ Απουσία δικαιωμάτων SMS + Μην σκοτώσεις την εφαρμογή μου; + Η μεταφόρτωση των αρχείων καταγραφής σφαλμάτων απενεργοποιήθηκε! + \n\nΤεκμηρίωση:\nhttps://wiki.aaps.app\n\nFacebook:\nhttps://www.facebook.com/groups/AndroidAPSUsers %1$d ημέρες %1$d ημέρες @@ -278,4 +576,7 @@ %1$d λεπτά + Θέλετε να καθαρίσετε τη βάση δεδομένων;\nΑυτή η ενέργεια θα αφαιρέσει την παρακολούθηση των αλλαγών και ιστορικά δεδομένα παλαιότερα από 3 μήνες. + Θέλετε να εκκαθαρίσετε τη βάση δεδομένων;\nΑυτή η ενέργεια θα αφαιρέσει την παρακολούθηση των αλλαγών και ιστορικά δεδομένα παλαιότερα από 3 μήνες.\nΚάνοντας αυτό θα επιταχυνθεί δραματικά ο πλήρης συγχρονισμός. + Έγινε εκκαθάριση των καταχωρήσεων diff --git a/core/ui/src/main/res/values-pt-rBR/strings.xml b/core/ui/src/main/res/values-pt-rBR/strings.xml index 0bcec6ecf6..969bbf4574 100644 --- a/core/ui/src/main/res/values-pt-rBR/strings.xml +++ b/core/ui/src/main/res/values-pt-rBR/strings.xml @@ -139,7 +139,7 @@ ]]> REMOVER Ativar perfil - repor + redefinir TrocaPerfil em falta. Por favor faça uma troca de perfil ou pressione \"Ativar Perfil\" em PerfilLocal. Perfil Selecione para remover diff --git a/core/ui/src/main/res/values-ro-rRO/protection.xml b/core/ui/src/main/res/values-ro-rRO/protection.xml index 1629e2929f..815134d738 100644 --- a/core/ui/src/main/res/values-ro-rRO/protection.xml +++ b/core/ui/src/main/res/values-ro-rRO/protection.xml @@ -6,15 +6,26 @@ Protecție aplicație Protecție bolus Parolă setări + Setări PIN Parolă aplicație + PIN Aplicație Parolă bolus + PIN Bolus + Reținerea parolei și a PIN-ului [s] + Timpul până la introducerea parolei sau a PIN-ului Biometric Parolă personalizată + PIN particularizat Fără protecţie Trecere la modul nesecurizat biometric Pentru a fi eficientă, protecţia biometrică are nevoie de o parolă principală pentru regresie.\n\nVă rugăm să setaţi o parolă principală! Parola a fost setată! + PIN setat! Parola nu a fost setată + Cod PIN nesetat Parola nu a fost modificată + PIN nemodificat + PIN șters! Introduceți parola aici + Introduceți codul PIN aici diff --git a/core/ui/src/main/res/values-ro-rRO/strings.xml b/core/ui/src/main/res/values-ro-rRO/strings.xml index 245c00c587..10b5661322 100644 --- a/core/ui/src/main/res/values-ro-rRO/strings.xml +++ b/core/ui/src/main/res/values-ro-rRO/strings.xml @@ -14,6 +14,7 @@ %1$.2f U/h Pompa nu este inițializată, profilul nu este setat! Actualizarea profilului bazalei a eșuat + Bolusul de %1$.2fU a fost livrat cu succes Nu s-a citit o rată bazală validă din pompă Se limitează IOB la %1$.1f U datorită %2$s BUCLĂ DEZACTIVATĂ DATORITĂ CONSTRÂNGERILOR @@ -44,12 +45,15 @@ Dezactivează pentru 5 minute Liniște Succes + Setări avansate Eroare de livrare a bolusului extins + Mod APS Bolus extins Suspendat Total TDD Se vor livra %1$.2fU Se așteaptă pompa + AAPS pornit %1$+.2f U %1$d g %1$.2f h @@ -58,6 +62,8 @@ Așteptați… Stop Carbohidrați + Profil invalid! + NICIUN PROFIL SETAT ]]> Data Unități @@ -66,7 +72,11 @@ ISF Bazală Țintă + Durata de Acțiune a Insulinei (DIA) + Rația insulină pt. carbohidraţi (IC sau ICR) + Factorul de sensibilitate la insulină (ISF) Rată bazală + Glicemie țintă g % Bluetooth @@ -96,6 +106,8 @@ Se încarcă… Note Șterge + Adăugare nouă + Adăugare nouă deasupra Datele vin de la o pompa diferita. Schimba driver-ul de pompa pentru a reseta starea pompei. Gl Calibrare @@ -108,10 +120,19 @@ Nu este configurat Buclă suspendată Săgeată tendinţă + Auto sens req + în scădere rapidă + în scădere + în scădere lentă + stabilă + în creștere lentă + în creștere + în creștere rapidă nimic necunoscută hiper + în țintă hipo Medie Timp în țintă @@ -121,6 +142,7 @@ resetare Lipsă SchimbareProfil. Efectuați o schimbare de profil sau apăsați \"Activare profil\" în ProfilulLocal. Profil + Selectează pentru ștergere Sigur vrei să elimini %1$d element(e) Tratament Creați un profil nou din acest profil? @@ -131,6 +153,7 @@ IOB bazală INVALID Autentificare + Amorsare/Umplere Insulină Oprește o țintă temporară Buclă închisă @@ -139,13 +162,19 @@ DIA IC ISF + Anularea ratei bazale temporare a eșuat + Anularea bolusului extins a eșuat + Trimitere status către NS sau Tidepool Buclă dezactivată/suspendată Insulină activă (IOB) Parola greșită + PIN greșit Parolele nu corespund + PIN-urile nu se potrivesc Valori bazale nesincronizate cu ora: %1$s + Valoarea bazalei a fost înlocuită cu valoarea minimă posibilă: %1$s Valoarea bazalei a fost înlocuită cu valoarea maximă posibilă: %1$s /U U/h @@ -153,6 +182,7 @@ Utilizează profilul %1$d%% pentru %2$d min + Anulare rată bazală temporară Lasă să funcționeze bazala temporară Rată Durată @@ -174,9 +204,12 @@ Notă: %1$s Întrebare : %1$s Exercițiu fizic: %1$s + Schimbare canulă/loc infuzie + Inserare senzor Start senzor Stop senzor CGM Alertă D.A.D. + Schimbare cartuș insulină Schimbare de profil Bolus Gustare Bolus Masă @@ -186,6 +219,8 @@ Sfârșit bazală temporară Corecție de carbohidrați OpenAPS Offline + Schimbare baterie pompă + Ţintă temporară Valoare țintă temporară Oprire ţintă temporară Asistent bolusare @@ -212,7 +247,9 @@ Se așteaptă rezultatul SMB + %1$d g carbohidrați suplimentari necesari în %2$d minute + TDD cumulată TDD estimat exponențial Bazală Bolus @@ -221,6 +258,7 @@ # Zile Greutate Posibil fără acuratețe bună dacă folosiți bolus de insulină pentru amorsare/umplere! + Date vechi, te rog apasă \"REÎNCĂRCARE\" Total bazală implicită TBB * 2 @@ -293,9 +331,11 @@ RESET STATISTICI STERGERE JURNAL STERGERE TRATAMENTE VIITOARE + Șterge tratamentele viitoare EXPORT SETARI IMPORT SETARI RESETARE BAZE DE DATE + CURĂȚĂ BAZELE DE DATE EXPORT BAZE DE DATE IMPORT BAZE DE DATE EXPORT OTP @@ -336,6 +376,9 @@ CARB %1$d g BOLUS EXTINS %1$.2f U %2$d min ÎNCARCA EVENIMENTE + ȘTERGE ALARMELE + DEZACTIVEAZĂ + ACTUALIZEAZĂ ORA ÎNCARCA ISTORICUL %1$d ÎNCARCA TDD-uri SETARE PROFIL @@ -353,25 +396,99 @@ %1$.0f%% Rate bazale Bazală % + fişier utilizator + Autotune + Ajutor în scopul potențialelor ajustări ale profilului (ISF, IC și ratele bazale) + AT + Setări Autotune + Automatizare schimbare profil + Dacă este activată, Autotune va actualiza automat profilul și va comuta la profilul nou în baza unui calcul făcut cu regula de automatizare. + Clasifică UAM ca bazală + Activează numai dacă ai introdus valori corecte de carbohidrați consumați. Cu această opțiune, creșterile bruște detectate de Autotune vor fi utilizate pentru a recomanda schimbări de rată bazală. + Ajustați curba insulinei + Activați doar dacă folosiți vârf liber. Această opțiune va regla durata vârfului și a DIA + Număr de zile de date + Aplică rezultatul mediu în circadian IC/ISF + Autotune nu va corecta variațiile circadiene. Această opțiune aplică o reglare medie a IC și ISF la profilul circadian înregistrat + Include mai multe informaţii de jurnal pentru depanare + Activați numai dacă se solicită de către dezvoltator pentru a trimite mai multe informații în jurnal pentru a ajuta la depanarea pluginului Autotune + Numărul implicit de zile de date pentru a fi procesate automat (până la 30) + Ajustat + Profil : + Zilele de reglare: + Ultima executare : + Atenție : + Selectați profilul pentru reglare + Profilul selectat are %1$d valori IC. Autotune va utiliza %2$.2f g/U + Profilul selectat are %1$d valori ISF. Autotune va folosi %2$.1f %3$s/U + Eroare în datele introduse, încercați să rulați din nou automat sau să reduceți numărul de zile + Eroare în datele de introducere, mărește numărul de zile + Calcularea automată a început, vă rugăm să aveți răbdare + Verificați cu atenție rezultatele înainte de a le utiliza! + Rezultatul parțial din ziua %1$d / %2$d ajustat Rezultat: %1$s + Param + % Lipsă + Autotune profilul %1$s + Rulează Autotune + Verificați profilul de intrare Compară profilurile + Copiați în profilul local + Actualizați profilul de intrare + Reveniţi la profilul de intrare + Creați un profil local nou din acest profil Autotune? + Actualizați profilul %1$s cu Profil Autotune? + Reveniți la profilul %1$s cu profilul de intrare? + Profil invalid + Autotune a rulat fără schimbarea profilului + Autotune a rulat și profilul a fost automat schimbat + Eroare în timpul ultimei rulări Autotune + O altă rulare Autotune este detectată, rularea este anulată Se folosesc notificările sistemului pentru alerte și notificări Alarmă urgentă INFO + Consilier bolus + Ai glicemia crescută. În loc să mănânci acum, este recomandat să aştepţi o glicemie mai bună. Vrei să faci un bolus de corecție acum și să îți reamintesc când este timpul să mănânci? În acest caz, niciun carbohidrat nu va fi înregistrat și trebuie să utilizezi din nou calculatorul de vbolus când îți voi reaminti. COB vs IOB !!!!! A fost detectată o absorbție lentă a carbohidraților: %2$d%% din timp. Reverificați calculele. COB poate fi supraestimat, astfel că este posibilă administrarea de mai multă insulină !!!!!]]> Livrați doar partea aceasta din rezultatul sugerat de wizard [%] + Prag de timp pentru vechimea glicemiei [min] + Este aplicatâ limitarea bolusului %1$.2f U la %2$.2f U + Bolusul va fi doar consemnat (nu va fi livrat de pompă) Rulează alarma când este timpul să mănânci Nicio acțiune selectată, nu se va întâmpla nimic + Nicio glicemie recentă pe care să se bazeze calculul! + Niciun profil activ stabilit! + COB necunoscut! Lipsesc datele de glicemie sau aplicația a fost repornită de curând? + Limite carbohidrați încălcate! + Calc (IC: %1$.1f, ISF: %2$.1f) + Carbohidrați: %1$.2fU + COB: %1$.0fg %2$.2fU + Glicemie: %1$.2fU + IOB: %1$.2fU + Superbolus: %1$.2fU + Tendința la 15\': %1$.2fU + Procentaj: %1$.2fU x %2$d%% ≈ %3$.2fU + Încălcare constrângere insulină!\nNu se pot livra %1$.2fU + BazalaT.: %1$s + Între %1$s și %2$s + Nicio pompă disponibilă! + Asistent Rapid + Copil Adolescent Adult + Adult cu rezistență la insulină Sarcină + Te rog confirmă tipul de pacient pentru a stabili limitele de siguranță + Bolus maxim admis [U] + Carbohidrați admiși maxim [g] + Tip de pacient Deblochează setările @@ -422,6 +539,9 @@ Vi se va solicita parola principală, care este necesară pentru a decripta setările importate. + scădere %1$s cu %2$s + creștere %1$s cu %2$s + S-a atins limita permisă %1$dh %2$dm Ora evenimentului @@ -441,6 +561,9 @@ Lipsesc permisiunile de SMS + Nu-mi opri aplicația? + Încărcarea jurnalelor de erori este dezactivata! + \n\nDocumentation:\nhttps://wiki.aaps.app\n\nFacebook:\nhttps://www.facebook.com/groups/AndroidAPSUsers %1$d zi %1$d zile @@ -457,4 +580,7 @@ %1$d minute + Doriți să curățați baza de date?\nAceasta va elimina schimbările înregistrate și datele istorice mai vechi de 3 luni. + Doriți să curățați baza de date?\nAceasta va elimina schimbările înregistrate și datele istorice mai vechi de 3 luni.\nFăcând acest lucru, veți accelera foarte mult sincronizarea completă. + Înregistrări șterse diff --git a/core/ui/src/main/res/values-ru-rRU/strings.xml b/core/ui/src/main/res/values-ru-rRU/strings.xml index 6fd3660f69..a88b826b8b 100644 --- a/core/ui/src/main/res/values-ru-rRU/strings.xml +++ b/core/ui/src/main/res/values-ru-rRU/strings.xml @@ -376,6 +376,9 @@ УГЛ %1$d г Пролонгированный болюс %1$.2f ед %2$d мин ЗАГРУЗИТЬ СОБЫТИЯ + ОЧИСТИТЬ ОПОВЕЩЕНИЯ + ДЕАКТИВИРОВАТЬ + ВРЕМЯ ОБНОВЛЕНИЯ ЗАГРУЗИТЬ ИСТОРИЮ %1$d ЗАГРУЗИТЬ СУТ ДОЗЫ ЗАДАТЬ ПРОФИЛЬ @@ -421,6 +424,7 @@ Выбранный профиль имеет %1$d значений IC. Автоматически будет использоваться %2$.2f г/ед Выбранный профиль имеет %1$d значений ISF. Автоматически будет использоваться %2$.1f%3$s/ед Ошибка ввода данных, попробуйте запустить снова autotune или уменьшить количество дней + Ошибка в данных, увеличьте количество дней Идет настройка автоматизации, ждите Перед использованием внимательно проверьте результаты! Частичный результат дня %1$d / %2$d с отладкой diff --git a/core/utils/src/main/res/values-el-rGR/strings.xml b/core/utils/src/main/res/values-el-rGR/strings.xml index 3ea04e700d..763ea6bd89 100644 --- a/core/utils/src/main/res/values-el-rGR/strings.xml +++ b/core/utils/src/main/res/values-el-rGR/strings.xml @@ -1,2 +1,8 @@ - + + Επιλέχθηκε %1$d + Αφαίρεση Στοιχείων + Ταξινόμηση Στοιχείων + Αφαίρεση Επιλεγμένων Στοιχείων + Ταξινόμηση + diff --git a/core/validators/src/main/res/values-el-rGR/validator.xml b/core/validators/src/main/res/values-el-rGR/validator.xml index 2dad0d3f66..d8e1e4614c 100644 --- a/core/validators/src/main/res/values-el-rGR/validator.xml +++ b/core/validators/src/main/res/values-el-rGR/validator.xml @@ -2,6 +2,23 @@ Μόνο αριθμητικά ψηφία επιτρέπονται. Μόνο αριθμητικά ψηφία μέσα στο εύρος %1$s - %2$s επιτρέπονται. + Αυτό το πεδίο δεν μπορεί να περιέχει ειδικούς χαρακτήρες + Επιτρέπονται μόνο τυπικά γράμματα Το πεδίο αυτό δεν πρέπει να είναι κενό + Μη έγκυρη διεύθυνση ηλεκτρονικού ταχυδρομείου + Μη έγκυρος αριθμός πιστωτικής κάρτας Μη έγκυρος αριθμός τηλεφώνου + Μη έγκυρο όνομα τομέα + Μη έγκυρη διεύθυνση IP + Μη έγκυρη διεύθυνση Web + Μη έγκυρο όνομα ή επώνυμο. + Μη έγκυρο πλήρες όνομα. + Μη έγκυρη μορφοποίηση + Πρέπει να περιέχει 4 ψηφία + Πρέπει να περιέχει 6 ψηφία + Πρέπει να είναι 12 χαρακτήρες από τους ABCDEF0123456789 + Πρέπει να είναι 8 χαρακτήρες από τους ABCDEF0123456789 + Πρέπει να είναι 4 χαρακτήρες από τους ABCDEF0123456789 + Μη ελάχιστο μήκος + Το Pin πρέπει να είναι 3 έως 6 ψηφία, όχι ίδια μεταξύ τους ή σε σειρά diff --git a/implementation/src/main/res/values-ro-rRO/strings.xml b/implementation/src/main/res/values-ro-rRO/strings.xml index 452d886ceb..bab104c221 100644 --- a/implementation/src/main/res/values-ro-rRO/strings.xml +++ b/implementation/src/main/res/values-ro-rRO/strings.xml @@ -4,9 +4,21 @@ Se execută comanda chiar acum Valoarea bazalei este sub minimul permis. Profilul nu este setat! Permisiune + %1$s necesită excluderea din lista de optimizare a bateriei pentru o funcționare corespunzătoare Aplicația are nevoie sa acceseze locația pentru scanare Bluetooth și identificare WiFi Aplicația are nevoie de permisiunea de a accesa unitatea de stocare pentru a scrie fișierele registru și pentru a exporta setările + Foarte scăzută Hipo Hiper + Foarte mare + Sub + În țintă + Mai sus + HbA1c: + DST: %1$s + Detaliere 14 zile + TIR ziua + TIR noapte + Carbohidrați diff --git a/insight/src/main/res/values-el-rGR/strings.xml b/insight/src/main/res/values-el-rGR/strings.xml index 7bc6dd58de..a7f21ea36a 100644 --- a/insight/src/main/res/values-el-rGR/strings.xml +++ b/insight/src/main/res/values-el-rGR/strings.xml @@ -19,14 +19,20 @@ %1$d%% για %2$d / %3$d λεπτά Συνδυαστικό bolus %1$.2f / %2$.2f U για %3$d λεπτά + Τελευταία Δόση Bolus Αναζήτηση συσκευών… Σύζευξη ολοκληρώθηκε Ταιριάζουν οι εμφανιζόμενοι κωδικοί με αυτούς της αντλίας; Σύζευξη Insight Accu-Chek Insight %1$s: %2$s - Σωληνάκι αλλάχθηκε + Σωληνάκι αλλάχτηκε Sight + Ειδοποιήσεις Αντλίας Insight + Απενεργοποίηση δονήσεων κατά τη χειροκίνητη δόση bolus + Για Δόση bolus και εκτεταμένη Δόση bolus (διαθέσιμο μόνο με firmware 3.x) + Απενεργοποίηση δονήσεων κατά την αυτόματη δόση bolus + Για SMB(SuperMicroBolus) και προσωρινό βασικό ρυθμό με προσομοίωση TBR (διατίθεται μόνο με firmware Insight 3.x) Τέλος χρόνου κατά τη διάρκεια handshake - επαναφορά bluetooth Η αντλία σταμάτησε Η αντλία ξεκίνησε @@ -35,8 +41,9 @@ Εκτεταμένο: %1$.2f / %2$.2f U για %3$d λεπτά Συνδυαστικό: %1$.2f / %2$.2f U για %3$d λεπτά TDD: %1$.2f + Υπόλοιπο μονάδων:%1$.2fU Μπατ.:%1$d%% - Απελευθέρωση έκδοση λογισμικού + Έκδοση λογισμικού Έκδοση λογισμικού επεξεργαστή UI Έκδοση λογισμικού επεξεργαστή PC Έκδοση λογισμικού επεξεργαστή MD tel @@ -59,4 +66,5 @@ Ελάχ. διάρκεια αποκατάστασης [s] Συναγερμός αντλίας Πληροφορίεςσύζευξης + Κουμπί Ανανέωσης Insight diff --git a/plugins/aps/src/main/res/values-el-rGR/strings.xml b/plugins/aps/src/main/res/values-el-rGR/strings.xml index 82cb6671e7..7ab8b16f8a 100644 --- a/plugins/aps/src/main/res/values-el-rGR/strings.xml +++ b/plugins/aps/src/main/res/values-el-rGR/strings.xml @@ -1,10 +1,19 @@ + Ρύθμιση ευαισθησίας και γλυκόζης αίματος + DynamicISF Συντελεστής Προσαρμογής % + Συντελεστής Προσαρμογής για το DynamicISF. Ρυθμίστε περισσότερο από 100% για πιο επιθετικές διορθωτικές δόσεις και λιγότερο από 100% για λιγότερο επιθετικές διορθώσεις. Ο υψηλός προσωρινός στόχος ανεβάζει την ευαισθησία = 100]]> Ο χαμηλός προσωρινός στόχος μειώνει την ευαισθησία OpenAPS SMB + Δυναμική ISF + Πόσο συχνά τα SMBs θα χορηγούνται σε λεπτά + Η αντίσταση στην ινσουλίνη μειώνει τον στόχο + Όταν ανιχνευθεί αντίσταση, μειώστε το στόχο γλυκόζης + Η ευαισθησία αυξάνει τον στόχο + Όταν ανιχνευθεί ευαισθησία, αυξήστε το στόχο γλυκόζης Προσθήκη απενεργοποιημένη Μη διαθέσιμα δεδομένα γλυκόζης Μη διαθέσιμα δεδομένα autosens @@ -60,7 +69,14 @@ Ενεργοποίηση SMB με προσωρινούς στόχους Ενεργοποίηση του SMB όταν υπάρχει ενεργός προσωρινός στόχος (τρώω σύντομα, άσκηση) Ενεργοποίηση SMB με υψηλούς προσωρινούς στόχους + Ενεργοποίηση SMB όταν υπάρχει ενεργός υψηλός προσωρινός στόχος (άσκηση, πάνω από 100 mg/dl ή 5.5 mmol/l) Τα μέγιστα λεπτά του βασικού ρυθμού που περιορίζουν το SMB να + Μέγιστη διάρκεια UAM SMB (λεπτά) + Μέγιστα λεπτά βασικού ρυθμού που περιορίζουν το SMB για UAM + Ελάχιστοι Υδατάνθρακες που Απαιτούνται Για Πρόταση + Ελάχιστα γραμμάρια υδατανθράκων για την εμφάνιση μιας ειδοποίησης πρότασης υδατανθράκων. Δε θα εμφανιστούν ειδοποιήσεις για προτάσεις υδατανθράκων κάτω από αυτόν τον αριθμό. + Η τιμή BG κάτω από την οποία αναστέλλεται η ινσουλίνη. Η προεπιλεγμένη τιμή χρησιμοποιεί τυποποιημένο μοντέλο στόχου. Ο χρήστης μπορεί να ορίσει τιμή μεταξύ 60mg/dl (3. mmol/l) και 100mg/dl (5.5mmol/l). Τιμές κάτω των 65/3.6 έχουν ως αποτέλεσμα τη χρήση προκαθορισμένου μοντέλου + Η τιμή BG κάτω από την οποία γίνεται αναστολή λόγω χαμηλής γλυκόζης Αυξείστε την μέγιστη βασική τιμή, επειδή η ρύθμιση είναι χαμηλότερη από τη μέγιστη βασική στο προφίλ σας πολλαπλασιαστής μέγιστου βασικού πολλαπλασιαστής ημερήσιου μέγιστου βασικού @@ -72,10 +88,30 @@ μέγιστη τιμή στις Επιλογές σταθερό όριο + Κορυφή + Εκτέλεση τώρα Ένα bolus παραδόθηκε μέσα στα τελευταία 3 λεπτά, παράκαμψη SMB + Η αντλία δεν αρχικοποιήθηκε! ΚΥΚΛΩΜΑ Ενεργοποιήστε ή απενεργοποιήστε την εφαρμογή που ενεργοποιεί το κύκλωμα. + ΔΕΝ ΕΠΙΛΕΧΘΗΚΕ APS Ή ΔΕΝ ΕΓΙΝΕ ΠΑΡΟΧΗ ΑΠΟΤΕΛΕΣΜΑΤΟΣ + Παράβλεψη για 5 λεπτά + Παράβλεψη για 15 λεπτά + Παράβλεψη για 30 λεπτά + Προτεινόμενοι Υδατάνθρακες + Νέα διαθέσιμη πρόταση Ο βασικός ρυθμός ορίστηκε σωστά + Τελευταία εκτέλεση APS + Αίτημα + Μετά από επεξεργασμένους περιορισμούς + Χρόνος αιτήματος προσωρινού βασικού + Χρόνος εκτέλεσης προσωρινού βασικού + Προσωρινός ρυθμός καθορισμένος από την αντλία + Χρόνος αιτήματος SMB + Χρόνος εκτέλεσης SMB + SMB καθορισμένο από την αντλία + Ελάχιστο αίτημα για αλλαγή [%] + Το Ανοιχτό κύκλωμα θα εμφανίσει νέο μήνυμα αλλαγής μόνο αν η αλλαγή είναι μεγαλύτερη από αυτήν την τιμή σε %. Προεπιλεγμένη τιμή 20% diff --git a/plugins/aps/src/main/res/values-pt-rBR/strings.xml b/plugins/aps/src/main/res/values-pt-rBR/strings.xml index ebdbab02ba..e7fbbf68c3 100644 --- a/plugins/aps/src/main/res/values-pt-rBR/strings.xml +++ b/plugins/aps/src/main/res/values-pt-rBR/strings.xml @@ -9,7 +9,7 @@ SMB OpenAPS FSI Dinâmico - Com que frequência em min os SMBs serão dados + Com que frequência em minutos os SMBs serão aplicados Resistência reduz alvo Quando a resistência for detectada, diminui o alvo de glicose Sensibilidade aumenta o alvo @@ -39,42 +39,42 @@ Dados Autosens Script debug Usar função Autosens - Max U/h em que uma Basal temporária pode ser definida - Este valor é chamado max basal no contexto do OpenAPS + Máximo em U/h em que uma basal temporária pode ser definida + O valor definido será o máximo de unidades de basal por hora que o aaps poderá chegar Basal Máxima IOB que OpenAPS pode dar [U] - Este valor é denominado Max IOB em contexto OpenAPS \nEste é o valor máximo de insulina em [U] que APS pode dar de uma vez. + Este valor é chamado Max IOB em contexto OpenAPS \nEste é o valor máximo de insulina em [U] que aaps pode deixar ativo de uma vez. Valor padrão: true\nÉ usado para permitir que autosens possa ajustar os valores alvo de glucose no sangue (BG), além de ISF e basais. Autosens também ajusta os alvos - Valor padrão: 3.0 para assitência avançada de refeições (AAR) ou 8.0 para super micro bolus (SMB). Esta é a configuração padrão para o calculo de quanto varia a cada 5 min a glicemia (BG) devido à absorção de carboidratos. O padrão é 3mg/dl/5min. Isso afeta a rapidez com que decaem os carboidratos ativos (CA) e quanta absorção de carboidrato será considerada no cálculo da previsão de glicemia futura, tornando possível notar que glicemia está baixando mais do que o esperado ou não subindo como esperado. - Valor padrão: 3 Por segurança é o valor limite estabelecido por OpenAPS. O que faz é limitar a basal a x3 a basal mázima. Se necessário modificar este valor, por favor ter em conta que os dados apontam para que os limites de segurança sejam - 3 x max diario ou 4x valor atual (qual seja menor) como valores máximos. - Valor padrão: 4 Esta é a outra parte dos valores limites de segurança - 3 x max diário ou 4x valor actual - do OpenAPS. Isto define que não importa o valor da basal máxima definido na bomba, o valor máximo da basal temporária não pode ser maior que 4 x o valor da basal definida na bomba. O objetivo é evitar que sejam determinadas basais temporárias muito elevadas antes que se perceba como o algoritmo funciona. 4x é um valor que a maior parte das pessoas nunca necessitará de alterar pois o mais provável é necessitar de alterar outras definições para não necessitar de \"ultrapassar\" este limite de segurança. + Valor padrão: 3.0 para assitência avançada de refeições (AAR) ou 8.0 para super micro bolus (SMB). Esta é uma configuração para o impacto de absorção de carboidratos por 5 minutos. O padrão é uma expectativa de 3 mg/dl/5min. Isso afeta a velocidade com que os CA são decaídos e a quantidade de absorção de carboidratos assumida ao calcular a glicemia futura prevista, quando a glicemia está caindo mais do que o esperado ou não está subindo tanto quanto o esperado. + Valor padrão: 3 Esta é uma chave de segurança OpenAPS. O que isso faz é limitar seus basais para serem 3x (neste caso) sua maior taxa basal. Provavelmente você não precisará alterar isso, mas você deve estar ciente de que é o que se discute sobre \"3x máximo diário; 4x atual\" para chaves de segurança. + Valor padrão: 4 Esta é a outra metade da chave OpenAPS de segurança, e a outra metade de \"3x diário máximo; 4x atual\" das tampas de segurança. Isso significa que o seu basal, independentemente do nível máximo de basal definido na bomba, não pode ser maior do que este número vezes o nível atual do seu basal. Isso é para evitar que as pessoas entrem em território perigoso, definindo basais excessivamente altos antes de entender como funciona o algoritmo. Novamente, o padrão é 4x; a maioria das pessoas nunca precisará ajustar isso e, em vez disso, precisará ajustar outras configurações se sentirem que estão \"batendo\" nessa tampa de segurança. Valor padrão: 2\nBolus Snooze (pausa após bolus) é executado depois de realizar um bolus por refeição Desta maneira o algoritmo não irá contrariar com temporárias baixas logo depois da refeição. O valor padrão é 2; Então uma duração de ação da insulina (DIA) de 5h significa que o Bolus Snooze irá ser gradualmente reduzido ao longo de 2,5 horas = 5/2 = DIA/Valor padrão. Atenção!\n Normalmente não é necessário modificar os valores abaixo. Por favor PRESSIONE AQUI e LEIA o texto para garantir que ENTENDE as consequências antes de alterar qualquer um destes valores. Usar sempre delta médio curto em vez de delta simples Útil quando há ruído nos dados das fontes sem filtro como o xDrip. Multiplicador máx. diário de segurança Multiplicador actual de segurança basal - Máximo total de IOB OpenAPS não pode superar [U] + Máximo total de insulina ativa no OpenAPS não pode superar [U] Este valor é chamado de Max IOB em contexto de OpenAPS\nOpenAPS não adicionará mais insulina se o IOB atual for maior que este valor - Ativar UAM + Ativar refeição não anunciada Ativar SMB - Use Super Micro Boluses em vez de basal temp para uma ação mais rápida - Detecção de refeições não Introduzidas - SMB sempre activado + Usar Super Micro Bolus (SMB) em vez de basal temporária para resposta mais rápida + Detecção de refeições não anunciadas + SMB sempre ativo SMB sempre activo independentemente dos bolus. Possível apenas quando o medidor tive um bom filtro de dados como o G5 - Ativar SMB após carbos + Ativar SMB após refeição SMB activo por 6h após carbs, mesmo com 0 COB. Possível apenas quando o medidor tive um bom filtro de dados como o G5 Ativar SMB com COB - Ativar SMB quando houver COB ativo. + Ativar SMB quando houver carboidratos ativos. SMB activo com valores alvo temporários SMB activo quando há valor alvo temporário activo (exercício, etc) SMB activo com alvos temporários elevados Ativar SMB quando tiver um alvo temporário alto ativo (exercício, acima de 100 mg/dl ou 5,5 mmol/l) Limite de minutos de basal para SMB UAM SMB máx minutos - Max minutos de basal para limitar SMB para UAM - Limite mínimo de carboidratos necessários para sugerir - Mínimo de gramas de carboidratos requeridos para exibir uma alerta de sugestão de carboidratos. Sugestões de carboidratos abaixo deste número não ativarão uma notificação. + Máximo de minutos de basal para usar o SMB em RNA + Qual o mínimo de carboidratos necessários para correção para gerar um alerta + Gramas mínimas de carboidratos para exibir um alerta de sugestão de carboidratos. Sugestões de carboidratos abaixo deste número não acionarão uma notificação. Valor a partir do qual a insulina é suspensa. O valor padrão usa como base o alvo padrão. O usuário pode definir o valor entre 60mg/dl (3.3mmol/l) e 100mg/dl(5.5 mmol/l). Valores abaixo de 65/3.6 resulta em uso do modelo padrão. Nível de glicose (BG) está abaixo do ponto em que ocorre a suspensão causada por hipoglicemia. Aumentar o valor máximo de basal porque a configuração é inferior à sua basal máxima no perfil diff --git a/plugins/aps/src/main/res/values-ru-rRU/strings.xml b/plugins/aps/src/main/res/values-ru-rRU/strings.xml index e7010a0597..bc444e6cb6 100644 --- a/plugins/aps/src/main/res/values-ru-rRU/strings.xml +++ b/plugins/aps/src/main/res/values-ru-rRU/strings.xml @@ -3,13 +3,13 @@ Настроить чувствительность относительно ГК Коэффициент регулировки динамического диапазона чувствительности ISF % Коэффициент корректировки динамического диапазона чувствительности ISF. Установите более 100% для агрессивных доз коррекции и менее 100% для менее агрессивной коррекции. - Высокая врем. цель temptarget повышает чувствительность + Высокая ВЦ повышает чувствительность = 100]]> - Низкая временная цель temptarget снижает чувствительность + Низкая ВЦ снижает чувствительность = 100]]> - Супер микро болюс OpenAPS + OpenAPS СМБ Динамический ISF - Как часто SMB будут подаваться в минутах + Как часто СМБ будут подаваться в минутах Сопротивляемость понижает цель При обнаружении сопротивляемости целевой уровень гликемии понижается Чувствительность поднимает цель diff --git a/plugins/automation/src/main/res/values-el-rGR/strings.xml b/plugins/automation/src/main/res/values-el-rGR/strings.xml index 3639370d1a..88d9d33b6f 100644 --- a/plugins/automation/src/main/res/values-el-rGR/strings.xml +++ b/plugins/automation/src/main/res/values-el-rGR/strings.xml @@ -6,6 +6,7 @@ Παρακαλώ εισάγετε όνομα εργασίας. Προσδιορίστε τουλάχιστον ένα σύστημα ενεργοποίηση. Προσδιορίστε τουλάχιστον μία ενέργεια. + Συναγερμός: %1$s Συναγερμός: Μην: Ήδη ενεργοποιημένο @@ -19,10 +20,12 @@ Τελευταία σύνδεση με αντλία Τελευταία σύνδεση με αντλία [λεπτά πριν] Τελευταία σύνδεση με αντλία %1$s %2$s λεπτά πριν + Ήδη καθορισμένο Προφίλ ποσοστό Έναρξη προφίλ %1$d%% Ποσοστό [%]: Στείλτε SMS: %1$s + Αποστολή SMS σε όλους τους αριθμούς Στείλτε SMS με κείμενο Έναρξη προσ. στόχου είναι λιγότερο από @@ -34,6 +37,9 @@ Γλυκόζη δεν είναι διαθέσιμη Γλυκόζη %1$s %2$.0f %3$s Γλυκόζη %1$s %2$.1f %3$s + Δεν υπάρχει Προσωρινός Στόχος + Προσωρινός Στόχος %1$s %2$.0f %3$s + Προσωρινός Στόχος %1$s %2$.1f %3$s Προφίλ %% %1$s %2$d ΙΟΒ %1$s %2$.1f ή @@ -43,10 +49,17 @@ Χρήση τοποθεσίας GPS Χρήση προσαρμοσμένης τοποθεσίας Υπηρεσίες τοποθεσίας + Κατά τη σύνδεση + Κατά την αποσύνδεση Βραχυπρόθεσμος Μέσος Όρος Μακροπρόθεσμος Μέσος Όρος Διαφορά %1$s %2$s + Όταν + Όταν βρίσκεστε εντός της περιοχής + Όταν βρίσκεστε εκτός της περιοχής + Όταν εισέρχεστε στην περιοχή που ονομάζεται + Όταν φεύγετε από την περιοχή που ονομάζεται Εύρος χρόνου Ο χρόνος είναι μεταξύ %1$s και %2$s Ανάμεσα @@ -61,6 +74,8 @@ Προσθ Αντιγραφή Προσ. στόχος %1$s + Σύνδεση Bluetooth στη συσκευή %1$s %2$s + Σύνδεση σε συσκευή Bluetooth WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -72,10 +87,13 @@ Lat: Lon: Γλυκόζη [%1$s]: + Στόχος [%1$s]: Τελευταίο Bolus Τελευταίο bolus %1$s %2$s λεπτά πριν COB COB %1$s %2$.0f + Καρδιακός ρυθμός + ΚΡ %1$s %2$.0f ΙΟΒ [U]: Αποστ [m]: Χρόνος επαναλαμβανόμενων @@ -85,8 +103,32 @@ Ενέργεια: Όνομα εργασίας Επεξεργασία + Επιλέξτε έναν τύπο δράσης + Επιλέξτε έναν τύπο ενεργοποίησης + Επιλέξτε έναν τύπο λειτουργίας Ενεργοποιήσεις: Προϋποθέσεις: + Συμβάν αυτοματισμού + Αναδιάταξη + Ενέργεια χρήστη + Αφαίρεση αυτοματισμού + Ταξινόμηση αυτοματισμού + Αφαίρεση επιλεγμένων στοιχείων + Επιλέχθηκαν %1$d + Αυτοματισμός συστήματος + Εκτέλεση αυτοματισμών + Προσθήκη κανόνα + Διακοπή επεξεργασίας + Δ + Τρ + Τε + Πε + Πα + Σ + Κ + Ώρα για φαγητόt!\nΤρέξτε τον οδηγό Bolus και κάντε υπολογίστε ξανά. + Ώρα για bolus!\nΤρέξτε τον οδηγό Bolus και κάντε υπολογισμό ξανά. + Σφάλμα κατά τη ρύθμιση μελλοντικού συναγερμού diff --git a/plugins/automation/src/main/res/values-ro-rRO/strings.xml b/plugins/automation/src/main/res/values-ro-rRO/strings.xml index fc3fd75f29..b4b8ad01fa 100644 --- a/plugins/automation/src/main/res/values-ro-rRO/strings.xml +++ b/plugins/automation/src/main/res/values-ro-rRO/strings.xml @@ -92,6 +92,8 @@ Ultimul bolus acum %1$s %2$s min COB COB %1$s %2$.0f + Ritm cardiac + HR %1$s %2$.0f IOB [U]: Dist [m]: Timp recurent @@ -111,6 +113,12 @@ Acțiunea utilizatorului Elimină automatizarea Sortează automatizarea + Ștergeți obiectele selectate + %1$d selectat(e) + Automatizare sistem + Rulează automatizările + Adaugă regulă + Oprire procesare L Ma @@ -120,5 +128,7 @@ S D + E timpul pentru a mânca!\nRulează asistentul de bolusare și refă calculele. Timpul sa faci bolus!\nRuleaza Calculatorul de Bolus pentru a face calculele din nou. + Eroare la setarea alarmei viitoare diff --git a/plugins/configuration/src/main/res/values-el-rGR/strings.xml b/plugins/configuration/src/main/res/values-el-rGR/strings.xml index bb330cd935..77203526c4 100644 --- a/plugins/configuration/src/main/res/values-el-rGR/strings.xml +++ b/plugins/configuration/src/main/res/values-el-rGR/strings.xml @@ -1,10 +1,12 @@ Μονάδες + Επιλέξτε τις μονάδες μέτρησης στις οποίες θέλετε να εμφανίζονται οι τιμές Επόμενο Προηγ Οδηγός εγκατάστασης ΤΕΛΟΣ + Καλώς ήρθατε Καλώς ήρθατε στον οδηγό εγκατάστασης. Θα σας καθοδηγήσει μέσα από το πρόγραμμα εγκατάστασης\n Άδεια χρήσης τελικού χρήστη ΔΕΝ ΠΡΕΠΕΙ ΝΑ ΧΡΗΣΙΜΟΠΟΙΗΘΕΙ ΓΙΑ ΝΑ ΚΑΝΕΤΕ ΙΑΤΡΙΚΗ ΑΠΟΦΑΣΗ. ΔΕΝ ΥΠΑΡΧΕΙ ΕΓΓΥΗΣΗ ΓΙΑ ΤΟ ΠΡΟΓΡΑΜΜΑ, ΣΤΟ ΒΑΘΜΟ ΠΟΥ ΕΠΙΤΡΕΠΕΤΑΙ ΑΠΟ ΤΟ ΕΦΑΡΜΟΣΤΕΟ ΔΙΚΑΙΟ. ΕΚΤΟΣ ΟΠΟΙΑΣΔΗΠΟΤΕ ΔΙΑΒΑΘΜΙΣΜΕΝΗ ΚΑΤΑ ΤΗΝ ΕΓΓΡΑΦΗ ΤΩΝ ΚΑΤΟΧΟΙ ΠΝΕΥΜΑΤΙΚΩΝ ΔΙΚΑΙΩΜΑΤΩΝ ΚΑΙ/Ή ΑΛΛΑ ΜΕΡΗ ΠΑΡΕΧΟΝΤΑΙ ΤΟ ΠΡΟΓΡΑΜΜΑ \"ΩΣ ΕΧΕΙ\" ΧΩΡΙΣ ΕΓΓΥΗΣΗ ΟΠΟΙΟΥΔΗΠΟΤΕ ΕΙΔΟΥΣ, ΕΞΑΙΡΟΥΜΕΝΕΣ Ή ΣΙΩΠΗΡΕΣ, ΣΥΜΠΕΡΙΛΑΜΒΑΝΟΜΕΝΩΝ, ΕΝΔΕΙΚΤΙΚΑ, ΤΩΝ ΣΙΩΠΗΡΩΝ ΕΓΓΥΗΣΕΩΝ ΕΜΠΟΡΕΥΣΙΜΟΤΗΤΑΣ ΚΑΙ ΚΑΤΑΛΛΗΛΟΤΗΤΑΣ ΓΙΑ ΣΥΓΚΕΚΡΙΜΕΝΟ ΣΚΟΠΟ. Ο ΟΛΟΚΛΗΡΩΜΕΝΟΣ ΚΙΝΔΥΝΟΣ ΟΣΟΝ ΑΦΟΡΑ ΤΗΝ ΠΟΙΟΤΗΤΑ ΚΑΙ ΤΗΝ ΑΠΟΔΟΣΗ ΤΟΥ ΠΡΟΓΡΑΜΜΑΤΟΣ ΕΙΝΑΙ ΔΙΚΟ ΣΑΣ. ΕΑΝ ΤΟ ΠΡΟΓΡΑΜΜΑ ΔΕΝ ΕΙΝΑΙ ΕΛΑΤΤΩΜΑΤΙΚΟ, ΠΡΕΠΕΙ ΝΑ ΕΞΕΤΑΣΤΕ ΤΟ ΚΟΣΤΟΣ ΟΛΩΝ ΤΩΝ ΑΠΑΡΑΙΤΗΤΩΝ ΣΥΝΤΗΡΗΣΕΩΝ, ΕΠΙΣΚΕΥΩΝ Ή ΔΙΟΡΘΩΣΕΩΝ. @@ -12,6 +14,7 @@ Ρυθμίσεις Εμφάνισης ΧΑΜΗΛΟ σημείο ΥΨΗΛΟ σημείο + Χαμηλότερη τιμή της περιοχής εντός στόχου (μόνο εμφάνιση) Άδεια Ζητείστε άδεια Βρέθηκαν αποθηκευμένες ρυθμίσεις @@ -91,6 +94,11 @@ Επαναφορά Βάσεων Δεδομένων Επαναφορά προεπιλογών + Σφάλμα αποκρυπτογράφησης, ο παρεχόμενος κωδικός πρόσβασης δεν είναι έγκυρος ή το αρχείο ρυθμίσεων τροποποιήθηκε! Μπορεί να συμβεί ότι το εισαγόμενο αρχείο εξήχθη με διαφορετικό Κύριο κωδικό πρόσβασης. + Λείπει η διαμόρφωση κρυπτογράφησης, η μορφή των ρυθμίσεων δεν είναι έγκυρη! + Μη υποστηριζόμενο ή μη καθορισμένος αλγόριθμος κρυπτογράφησης! + Επιλογή προσαρμοσμένης όψης ρολογιου + Παρακαλώ κάντε επανεκίνηση στο τηλέφώνο ή restart στο AndroidAPS από τις Ρυθμίσεις Συστήματος, \nδιαφορετικά το AndroidAPS δεν θα έχει καταγραφή (επαληθεύστε ότι οι αλγόριθμοι δουλεύουν σωστά)! diff --git a/plugins/configuration/src/main/res/values-pt-rBR/strings.xml b/plugins/configuration/src/main/res/values-pt-rBR/strings.xml index 065cd26563..f285917b4b 100644 --- a/plugins/configuration/src/main/res/values-pt-rBR/strings.xml +++ b/plugins/configuration/src/main/res/values-pt-rBR/strings.xml @@ -47,7 +47,7 @@ Ler estado Escolha de Dados Envio Fabric - Permitir que seja enviado automaticamente à equipa de desenvolvimento o report de crashes e das funções utilizadas, utilizando o serviço fabric.io. + Permitir que relatórios de falha automatizados e dados de uso de recursos sejam enviados aos desenvolvedores através do serviço fabric.io. Esta identificação será anexada aos relatórios de erro para podermos contatá-lo em casos de urgência. É opcional. Identificação (e-mail, apelido FB ou Discord, etc) Pedido @@ -127,7 +127,7 @@ Definições de registo Adicionais Redefinir banco de dados - Repor definições por defeito + Redefinir para padrões exportado %1$s atrás exportado em %1$s diff --git a/plugins/configuration/src/main/res/values-ro-rRO/strings.xml b/plugins/configuration/src/main/res/values-ro-rRO/strings.xml index 1a619e1546..c5c9bb45d1 100644 --- a/plugins/configuration/src/main/res/values-ro-rRO/strings.xml +++ b/plugins/configuration/src/main/res/values-ro-rRO/strings.xml @@ -6,6 +6,7 @@ Anterior Asistent de configurare TERMINARE + Bun venit Ați pornit asistentul pentru setări. Acesta vă va ajuta pentru configurarea setărilor\n Licență utilizator final NU FOLOSIȚI PENTRU LUAREA DE DECIZII MEDICALE. NU EXISTĂ RĂSPUNDERE LEGALĂ SAU GARANȚIE PENTRU ACEST PROGRAM, ÎN LIMITA APLICABILĂ A LEGII. CU EXCEPTIA CAZURILOR SPECIAL MENȚIONATE, AUTORUL ȘI/SAU ALTE PERSOANE IMPLICATE PUN LA DISPOZIȚIE ACEST PROGRAM FĂRĂ NICIO GARANȚIE, IMPLICITĂ SAU EXPLICITĂ, INCLUZÂND, DAR FĂRĂ A SE LIMITA LA, GARANȚIILE LEGATE DE VĂNZAREA SAU POTRIVIREA PENTRU UN ANUME SCOP. ÎNTREGUL RISC LEGAT DE CALITATEA ȘI PERFORMANȚA ACESTUI PROGRAM CAD ÎN RESPONSABILITATEA DUMNEAVOASTRĂ. DACĂ PROGRAMUL SE DOVEDEȘTE A FI DEFECT, DUMNEAVOASTRĂ VĂ ASUMAȚI ÎNTREAGA RĂSPUNDERE, PRECUM ȘI TOATE COSTURILE LEGATE DE SERVICE, REPARAȚII SAU CORECȚII. @@ -20,10 +21,12 @@ Aplicația are nevoie sa acceseze locația pentru scanare Bluetooth și identificare WiFi Aplicația are nevoie de permisiunea de a accesa unitatea de stocare pentru a scrie fișierele registru și pentru a exporta setările Solicitați permisiunea + %1$s necesită excluderea din lista de optimizare a bateriei pentru o funcționare corespunzătoare Au fost găsite setări stocate Parola master (principală) este folosită pentru criptarea copiilor de rezervă și pentru a suprascrie securitatea în aplicație. Rețineți-o sau păstrați-o într-un loc sigur. Parola principală curentă Folosește valorile corespunzătoarea celor mai mari mese pe care le ai de obicei\n + Sincronizează datele în cloud. Puteți sări peste această parte acum, dar nu veți putea trece de obiective până când nu veți configura un cont Nightscout sau Tidepool. Stare: Numele pacientului Vă rugăm să furnizați numele sau porecla pacientului pentru a diferenția între configurări @@ -33,7 +36,9 @@ Profil Schimbă profilul Ignoră asistentul pentru setări + Apăsați butonul pentru a permite AndroidAPS să sugereze/facă schimbări ale bazalei Pluginul Sensibilitate este folosit pentru estimarea sensibilității și calcularea COB. Pentru mai multe info vizitați: + https://wiki.aaps.app/en/latest/Configuration/Sensitivity-detection-and-COB.html Alegeți unul dintre algoritmii disponibili. Algoritmii sunt aranjați de la cel mai vechi spre cel mai nou. Algoritmii mai noi sunt, de obicei, mai puternici și mai agresivi. De aceeea, dacă sunteți la început, ar fi indicat să porniți cu AMA și nu cu cel mai nou. Este important să parcurgeți documentația OpenAPS și să îl configurați corect înainte de a folosi aplicația. Vă rugăm configuraţi RileyLink mai jos. După selectarea unui RileyLink, va fi posibil să continuaţi setarea odată ce starea RieyLink este \"Connected\". Acest lucru ar putea dura un minut.\n Notă: Puteți continua configurarea imediat ce pompa a fost inițializată.\n @@ -48,24 +53,35 @@ Cerință Mod APS Modul APS preferat + Eroare în solicitarea permisiunilor Acest dispozitiv nu permite folosirea excluderii din lista de optimizare a bateriei - se poate să întâmpinați probleme de performanță. Configurator Pompă + Ce pompă dorești să folosești cu AAPS? Profil + Care profil ar trebui să fie folosit de AAPS? APS Ce algoritm APS doriți să decidă ajustările de insulină? General Există pluginuri generale pe care le-ați putea găsi utile. Sincronizare + Plugin-uri de încărcare și sincronizare date. Ce constrângeri sunt aplicate? Buclă + Utilizaţi acest lucru pentru a activa integrarea buclei AAPS. Ce tip de insulină folosiți? Sursă glicemie + De unde ar trebui AAPS să primească datele? + Uniformizare + Alege algoritmul de uniformizare Detectare sensibilitate Ce algoritm de detecție a sensibilității doriți să folosiți? CONF Folosit pentru configurarea facilităţilor active + Atenție: Dacă activați și conectați o pompă fizică, AAPS va copia setările ratei bazale din profilul din aplicație în pompă. Profilul existent în pompă va fi suprascris cu cel din AAPS. Asigurați-vă că sunt corecte setările ratei bazale în profilul din AAPS. Dacă aveți dubii sau nu doriți suprascrierea setărilor bazalelor existente în pompă, apăsați butonul de anulare și repetați acțiunea mai târziu. + Deschideți setările + Versiunea AAPSClient nu se potrivește cu versiunea AAPS. Vă rugăm să actualizați. Preferințe Vi se va solicita parola principală, care va fi utilizată pentru criptare la exportarea setărilor. @@ -98,6 +114,7 @@ Mentenanță MENTN Pune la dispoziție funcții pentru mentenanță (ex: trimitere de loguri, ștergere de loguri). + Curățarea bazei de date Sigur resetați bazele de date? Setări de întreținere Destinatar email @@ -136,5 +153,7 @@ Lipseşte configuraţia de criptare, formatul setărilor este invalid! Algoritm de criptare nesuportat sau nespecificat! + Selectare aspect ceas personalizat + Restartați telefonul sau reporniți aplicația AAPS din System Settings \naltfel AAPS nu va putea înregistra loguri (importante pentru verificarea corectitudinii funcționării algoritmilor)! diff --git a/plugins/configuration/src/main/res/values-ru-rRU/strings.xml b/plugins/configuration/src/main/res/values-ru-rRU/strings.xml index 2d4a8d2c81..c994bab7eb 100644 --- a/plugins/configuration/src/main/res/values-ru-rRU/strings.xml +++ b/plugins/configuration/src/main/res/values-ru-rRU/strings.xml @@ -6,6 +6,7 @@ Назад Мастер настройки ГОТОВО + Добро пожаловать Добро пожаловать в мастер установки лицензионное соглашение с пользователем НЕ ДОЛЖНО ИСПОЛЬЗОВАТЬСЯ ДЛЯ ПРИНЯТИЯ МЕДИЦИНСКИХ РЕШЕНИЙ. ПРОГРАММА НЕ ДАЕТ ГАРАНТИЙ В РАМКАХ СУЩЕСТВУЮЩЕГО ЗАКОНОДАТЕЛЬСТВА. ПРЕДОСТАВЛЯЕТСЯ \"КАК ЕСТЬ\" БЕЗ ЯВНЫХ ИЛИ СКРЫТЫХ ГАРАНТИЙ ВКЛЮЧАЯ НО НЕ ОГРАНИЧИВАЯСЬ ВОЗМОЖНОСТЬЮ КОММЕРЧЕСКОГО ИСПОЛЬЗОВАНИ ИЛИ СООТВЕТСТВИЯ КАКИМ-ЛИБО ЦЕЛЯМ. ВСЕ РИСКИ ЛОЖАТСЯ НА ВАС. В СЛУЧАЕ НЕРАБОТОСПОСОБНОСТИ ПРОГРАММЫ ВЫ НЕСЕТЕ ВСЕ РАСХОДЫ СВЯЗАННЫЕ С ОБСЛУЖИВАНИЕМ РЕМОНТОМ ИЛИ КОРРЕКТИРОВКОЙ. @@ -152,6 +153,7 @@ Отсутствует конфигурация шифрования, формат параметров недопустим! Неподдерживаемый или не прописанный алгоритм шифрования! + Выберите пользовательский циферблат Перезагрузите телефон или перезапустите AAPS из системных настроек \n иначе AAPS не будет вести лог (важно для отслеживания и проверки алгоритмов)! diff --git a/plugins/constraints/src/main/res/values-cs-rCZ/objectives.xml b/plugins/constraints/src/main/res/values-cs-rCZ/objectives.xml index a85937d688..7022deb872 100644 --- a/plugins/constraints/src/main/res/values-cs-rCZ/objectives.xml +++ b/plugins/constraints/src/main/res/values-cs-rCZ/objectives.xml @@ -27,7 +27,7 @@ Přečíst si dokumentaci a zvýšit maximání IOB, aby mohlo SMB fungovat. Pro začátek se dá použít velikost běžného bolusu + 3x maximální denní bazál Použití SMB je vaším cílem. Oref1 algoritmus byl navržen tak, aby vám pomohl i s vašimi bolusy. Neměli byste dávat úplný bolus pro vaše jídlo, ale jen jeho část a nechtat AAPS v případě potřeby dát zbytek. Takto máte větší rezervu pro špatně vypočtené sacharidy. Věděli jste, že můžete nastavit procento bolusové kalkulačky pro snížení velikosti bolusu? Povolit další funkce pro každodenní používání, jako je například Dynamic sensitivity plugin - Ujistěte se, že SMB funguje správně. Povolte DynamicISF plugin a určte vhodnou kalibraci pro vaše tělo. Je vhodné začít s hodnotou nižší než 100% z důvodu bezpečnosti. + Ujistěte se, že SMB funguje správně. Povolte DynamicISF plugin a určete vhodnou kalibraci pro své tělo. Z důvodu bezpečnosti je vhodné začít s hodnotou nižší než 100 %. Modul dynamické citlivosti citlivosti je založen na myšlence, že celkový příjem inzulinu a aktuální hladiny glykémie ovlivňují skutečnou citlivost. DynamicISF plugin může pro vás upravit faktor citlivosti inzulínu (ISF) používaný algoritmem. Povolení automatizace Přečtěte si na wiki, jak automatizace funguje. Nejdříve nastavte pouze jednoduchá pravidla. Namísto provádění akcí nechte AAPS zobrazovat pouze oznámení. Pokud jste si jistí, že je automatizace spouštěna v pravý čas, můžete oznámení nahradit prováděním akce. (https://wiki.aaps.app/cs/latest/Usage/Automation.html) diff --git a/plugins/constraints/src/main/res/values-el-rGR/exam.xml b/plugins/constraints/src/main/res/values-el-rGR/exam.xml index cd59b556b3..d9c2609f14 100644 --- a/plugins/constraints/src/main/res/values-el-rGR/exam.xml +++ b/plugins/constraints/src/main/res/values-el-rGR/exam.xml @@ -4,6 +4,7 @@ Ποιο προφίλ μπορεί να χρησιμοποιηθεί και να διαμορφωθεί χωρίς σύνδεση; Θέμα: Προφίλ Εκτός Σύνδεσης Το προφίλ NS μπορεί να χρησιμοποιηθεί, αλλά όχι να ρυθμιστεί. + Αποτρέπει το AAPS από το να υπολογίσει την ινσουλίνη που δεν χορηγήθηκε ενώ η αντλία είναι φυσικά αποσυνδεδεμένη. Τι πρέπει να κάνετε αν τα δεδομένα του CGM έχουν θόρυβο; Λαμβάνω ινσουλίνη όταν το κύκλωμα είναι απενεργοποιημένο/αναστολή; Ναι, ο βασικός ρυθμός συνεχίζει να χορηγείται. diff --git a/plugins/constraints/src/main/res/values-pt-rBR/exam.xml b/plugins/constraints/src/main/res/values-pt-rBR/exam.xml index 3f95ba3741..6ed513aa3b 100644 --- a/plugins/constraints/src/main/res/values-pt-rBR/exam.xml +++ b/plugins/constraints/src/main/res/values-pt-rBR/exam.xml @@ -1,6 +1,6 @@ - O que é verdade sobre o DAI? + O que é verdadeiro sobre o DAI? Duração da Atividade da Insulina (DAI) Você deve definir o valor para a DAI no seu perfil. A menor duração permitida é de 5 horas. diff --git a/plugins/constraints/src/main/res/values-pt-rBR/strings.xml b/plugins/constraints/src/main/res/values-pt-rBR/strings.xml index ee4fd0239b..65f5dcc99c 100644 --- a/plugins/constraints/src/main/res/values-pt-rBR/strings.xml +++ b/plugins/constraints/src/main/res/values-pt-rBR/strings.xml @@ -10,6 +10,7 @@ versão antiga versão muito antiga Aplicativo expirado + A nova versão não foi verificada por pelo menos %1$d dias! Voltar ao LGS após %2$d dias, o loop será desativado após %3$d dias. Restaure a conectividade de internet! Detectamos que você está executando uma versão inválida. \"Loop\" desativado! Versão %1$s disponível A versão %1$s expira em %2$s @@ -47,4 +48,6 @@ Deseja reiniciar o objetivo? Pode perder seu progresso. Próxima Anterior + Redefinir estado terminado + Redefinir estado terminado diff --git a/plugins/constraints/src/main/res/values-ru-rRU/objectives.xml b/plugins/constraints/src/main/res/values-ru-rRU/objectives.xml index 4c7881c0f1..b5e60af15b 100644 --- a/plugins/constraints/src/main/res/values-ru-rRU/objectives.xml +++ b/plugins/constraints/src/main/res/values-ru-rRU/objectives.xml @@ -6,25 +6,25 @@ Цель %1$d не начата Цель %1$d не завершена Настройка интеграции с Nightscout, анализ базала и коэффициентов - Убедитесь, что данные о гликемии и подаваемом AAPSом инсулине отображаются в Nightscout и актуальны - Вы сделали базовую настройку экосистемы AAPS. Nightscout не нужен для работы AAPS, но может быть полезен для отчетов и мониторинга других пациентов. Необходимости в постоянном подключении к NS нет, если вы используете NS только для себя. Вы можете установить загрузку, например, только на домашний wifi, чтобы сэкономить заряд батареи. - Старт незамкнутого цикла - Начинайте работу в режиме незамкнутого цикла и ручной подстройки величины временного базала. Установите и применяйте временные цели и временные цели по умолчанию (напр. углеводы при нагрузке или купировании гипо) - Открытый цикл может быть использован для получения рекомендаций, если у вас нет совместимой помпы или если вы не готовы закрыть цикл. - Глубже понимаем работу системы в режиме незамкнутого цикла, включая ее рекомендации по временным базалам + Убедитесь, что значения ГК и данные об инсулине передаются в Nightscout и соответствуют данным в помпе + Вы сделали базовую настройку экосистемы AAPS. Nightscout не нужен для работы AAPS, но может быть полезен для отчетов и мониторинга других пациентов. Необходимости в постоянном подключении к NS нет, если вы используете NS только для себя. Вы можете установить загрузку в NS только через домашний wifi, чтобы сэкономить заряд батареи. + Запуск открытого цикла + Используйте режим Открытого цикла на протяжении нескольких дней и вручную выставляйте временные цели. Настройте ВЦ по умолчанию (ВЦ для Нагрузки, Гипо, Ожидания приема пищи) и используйте их. + Открытый цикл может быть использован для получения рекомендаций по терапии, если у вас нет совместимой помпы или если вы не готовы закрыть цикл. + Глубже понимаем работу открытого цикла, включая рекомендации по ВБС На основе накопленного опыта, определяем максимальную величину базала и задаем ее в помпе и в настройки AndroidAPS Примите меры предосторожности и корректируйте, если необходимо, параметры безопасности. - Начинаем замыкать цикл с прекращением подачи инсулина при низком значении ГК (режим Low Glucose Suspend) - Работа в замкнутом цикле с макс активным инсулином IOB = 0 на протяжении нескольких дней избегая событий типа приостановка на низких ГК Low Suspend + Начинаем замыкать цикл с прекращением подачи инсулина при низких значениях ГК (режим Low Glucose Suspend) + Работа в замкнутом цикле с maxIOB = 0 на протяжении нескольких дней. Старайтесь избегать низкой ГК, чтобы не вызывать события приостановки подачи инсулина на низких сахарах. Установка MaxIOB на нуль предотвращает гипо и не добавит инсулина выше базальной скорости (за исключением отрицательных значений IOB) - Настройка замкнутого цикла с поднятием макс величины IOB выше 0 и постепенным понижением целевой ГК - Работа несколько дней и по кр мере одну ночь без срабатывания оповещений о низкой ГК + Настройка замкнутого цикла с поднятием величины maxIOB выше 0 и постепенным понижением целевой ГК + Использовать систему на протяжении нескольких дней и по крайней мере 1 ночь без срабатывания оповещений о низкой ГК Обновляйте MaxIOB по мере взросления ребенка. Не допускайте, чтобы система подавала больше инсулина, чем вы можете покрыть едой = действительно, плохая идея выставлять высокие значения. Настраиваем базал и коэффициенты с последующей активацией auto-sens 1 неделя успешной дневной работы с регулярным введением углеводов - Если результаты autosense не колеблются около 100%, то возможно ваш профиль неверный. - Активация таких доп функций для дневного времени как супер микро болюс SMB - Прочтите статью wiki и увеличивайте maxIOB так, чтобы SMB заработал как положено! Для начала рассчитайте maxIOB как средний болюс на еду + макс. суточная базальная скорость*3 + Если результаты расчетов auto-sense не колеблются около 100%, то, возможно, ваш профиль неверный. + Активация в дневное время дополнительных функций, таких как СМБ + Прочтите статью wiki и увеличьте maxIOB, чтобы SMB заработал как положено! Для начала рассчитайте maxIOB = средний болюс на еду + макс. суточная базальная скорость*3 Ваша цель - это использование СМБ. Алгоритм Oref1 предназначен также, чтобы помочь вам с болюсами. Вы не должны подавать полный болюс на еду, а только часть его, предоставив AAPS подать при необходимости остальную часть болюса. Таким образом вы можете иметь большее пространство для ошибки в подсчетах углеводов. Вы знаете, что можно установить проценты для уменьшения размера болюса? Включение автоматизации Прочтите документацию по автоматизации. Настройте свои первые простые правила. Вместо действия позвольте AAPS только выводить уведомления. Если вы уверены, что автоматизация инициируется в нужное время, замените уведомление реальными действиями. (https://wiki.aaps.app/en/latest/Usage/Automation.html) @@ -35,20 +35,20 @@ Выполнено: %1$s Научитесь контролировать AAPS Выполняйте различные действия в AAPS - Вы узнали, как работать с основами AAPS. Главные элементы управления находятся на экране Обзора, доступном по нажатию или долгому нажатию, больше элементов управления на вкладке Действия. Следует научится, как поместить экран расширения (плагина) в верхнее прокручиваемое меню или оставить его в левом верхнем списке включённых расширений. + Вы узнали основы работы с AAPS. Главные элементы управления системой расположены на экране Начало и доступны по короткому или длинному нажатию на них, еще больше элементов управления расположены на вкладке Действия. Следует научится, как расположить экран расширения (плагина) в верхнее прокручиваемое меню вкладок или оставить его в левом списке включённых расширений. Установите профиль 90% на 10 мин (Долгое нажатие на имя профиля на главном экране) - Имитация душа. Отключите помпу на 1ч (Долгое нажатие на Открытый цикл Open Loop) + Имитация душа. Отключите помпу на 1 час (Долгое нажатие на Открытый цикл Open Loop) ... и обратное подключение таким же способом Создайте настраиваемую временную цель длительностью 10 мин. (Долгое нажатие на текущую цель) - В Конфигураторе активируйте модуль Действия Actions, сделав его видимым и показав содержимое верхнего меню - Просмотр содержимого модуля Цикл Loop + В Конфигураторе активируйте модуль Действия Actions, сделав его видимым и показав содержимое через верхнее меню + Просмотр содержимого модуля Замкнутый цикл Применить функцию масштабирования по долгому нажатию на диаграмму ГК Подтвердите ваши знания - Изучите вопросы. Вам дано четыре возможных ответа на каждый вопрос. Может быть более одного правильного ответа. Проверьте все правильные ответы и подтвердите выбор. + Изучите вопросы. Вам дано четыре возможных варианта ответа на каждый вопрос. Правильных ответов может быть более одного. Отметьте все, которые считаете правильными, и нажмите ПОДТВЕРДИТЬ. Вам не нужно быть программистом, но вам понадобится свой сайт Nightscout для прохождения целей, совместимая помпа и компьютер для сборки AAPS и обновлений. AAPS может работать в автономном режиме. Следует пересмотреть и обновить профиль. Лучший профиль = лучшие результаты. - Продолжительность действия инсулина DIA в AAPS имеет иное значение (время до полного поглощения инсулина), чем в классической помповой терапии (время до поглощения основной массы инсулина). + DIA в AAPS имеет иное значение (время до полного поглощения инсулина), чем в классической помповой терапии (время до поглощения основной массы инсулина). Вы изучили понятие чувствительность к инсулину ISF и то, как она влияет на коррекцию ГК. Вы изучили понятие углеводный коэффициент IC и то, как он влияет на количество инсулина, необходимого для покрытия углеводов. Временная цель Гипо используется только для предотвращения чрезмерной коррекции после гипо, когда накапливается отрицательный IOB. Необходимо принять дополнительные меры, чтобы предотвратить ситуацию в будущем. @@ -74,7 +74,7 @@ Следующий незавершенный Код запроса: %1$s (отметьте все правильные ответы) - https://wiki.aaps.app/en/latest/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath + https://wiki.aaps.app/ru/latest/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath https://wiki.aaps.app/en/latest/Getting-Started/Screenshots.html#the-homescreen https://wiki.aaps.app/en/latest/Configuration/Config-Builder.html https://wiki.aaps.app/en/latest/Getting-Started/Screenshots.html#the-homescreen diff --git a/plugins/constraints/src/main/res/values-ru-rRU/strings.xml b/plugins/constraints/src/main/res/values-ru-rRU/strings.xml index 2198c9e2f8..eff4a0b05a 100644 --- a/plugins/constraints/src/main/res/values-ru-rRU/strings.xml +++ b/plugins/constraints/src/main/res/values-ru-rRU/strings.xml @@ -3,7 +3,7 @@ Переход на летнее/зимнее время через 24 часа или менее - Изменение сезонного времени произошло меньше 3 часов назад-Закрытый цикл выключен + Переход на зимнее/летнее время произошел менее 3 часов назад - Закрытый цикл выключен Освободите по крайней мере %1$d MB из внутренней памяти! Цикл остановлен! @@ -22,13 +22,13 @@ Неменяющиеся данные. Принимаю за неверные Ограничиваю пролонгированный болюс до %1$.1f ед. из-за %2$s - Ограничение углеводов до %1$d г. из-за %2$s + Ограничение углеводов до %1$d г из-за %2$s Помпа не рассчитана на подачу временного базала Режим замкнутого цикла отключен в настройках Работает версия разработчика. Замкнутый цикл отключен. Замкнутый цикл отключен из-за работы Пролонгированного Болюса Опция супер микро болюс всегда и после углеводов отключена т. к. активный источник ГК не поддерживает комплексное фильтрование - В режиме незамкнутого цикла open loop супер микро болюс SMB не допускается + СМБ не работают в режиме открытого цикла максимальное значение в настройках жесткий предел Безопасность терапии @@ -36,7 +36,7 @@ Завершено, отлично! Не завершено Прошло времени - Максимум активного инсулина IOB установлен правильно + Максимальное значение IOB установлено правильно ГК доступна из выбранного источника Служба синхронизации имеет разрешение на запись Цикл активирован @@ -44,7 +44,7 @@ Режим замкнутого цикла включен ЦЕЛИ Обучающая программа - Хотите сбросить начатую цель? Можете потерять достигнутое. + Хотите сбросить начатую цель? Вы можете потерять весь прогресс по ней. Далее Назад diff --git a/plugins/insulin/src/main/res/values-ru-rRU/strings.xml b/plugins/insulin/src/main/res/values-ru-rRU/strings.xml index 34cce261e1..729eb53786 100644 --- a/plugins/insulin/src/main/res/values-ru-rRU/strings.xml +++ b/plugins/insulin/src/main/res/values-ru-rRU/strings.xml @@ -1,9 +1,9 @@ - Lyumjev + Люмжев Предустановки для Humalog и Novorapid / Novolog - Предустановки для Fiasp + Предустановки для Фиаспа Предустановки для Lyumjev Позволяет самостоятельно задавать пик активности инсулина - только для опытных пользователей ИНС @@ -13,6 +13,6 @@ Быстро действующий Oref Сверхбыстрый Oref Значение времени действия инс %1$f слишком мало - применено %2$f! - Новорапид, Хумалог + Новорапид, Новолог, Хумалог Фиасп diff --git a/plugins/main/src/main/res/values-af-rZA/strings.xml b/plugins/main/src/main/res/values-af-rZA/strings.xml index 0b94479cae..12d888af2c 100644 --- a/plugins/main/src/main/res/values-af-rZA/strings.xml +++ b/plugins/main/src/main/res/values-af-rZA/strings.xml @@ -152,12 +152,9 @@ Kontroles van horlosie Stel tydeleike doelwitte en behandelings vanaf horlosie. Berekeninge is ingesluit in die ghoeroe verslag: - Vertooninstellings Algemene instellings Vermeld op SMB Wys SMB op horlosie soos \'n standaard bolus. - Wys die voorspellings op die horlosie. - Projeksies Stuur alle Data weer Oop instellings op Wear diff --git a/plugins/main/src/main/res/values-bg-rBG/strings.xml b/plugins/main/src/main/res/values-bg-rBG/strings.xml index 092ae77d3e..dbbd65c5da 100644 --- a/plugins/main/src/main/res/values-bg-rBG/strings.xml +++ b/plugins/main/src/main/res/values-bg-rBG/strings.xml @@ -308,12 +308,9 @@ Контролиране от часовник Задаване временни цели и въвеждане Лечения от часовник Android wear Изчисления, включени в резултата на съветника: - Настройки за визуализация Основни настройки Уведомяване при SMB Покажи SMB на часовника като стандартен болус. - Показвай прогнозините КЗ на часовника. - Прогнозни КЗ Настройки на Watchface Разрешаване на персонализиран Watchface Разрешете заредения Watchface да променя и заключва определени настройки за екрана на часовника, за да съответстват на дизайна diff --git a/plugins/main/src/main/res/values-ca-rES/strings.xml b/plugins/main/src/main/res/values-ca-rES/strings.xml index 1b4ffc183e..c90209f159 100644 --- a/plugins/main/src/main/res/values-ca-rES/strings.xml +++ b/plugins/main/src/main/res/values-ca-rES/strings.xml @@ -257,12 +257,9 @@ Control des de rellotge Marcar objectius temporals i introduir tractaments des del rellotge. Càlculs inclosos al resultat de l\'assistent: - Configuració pantalla Configuració general Avís d\'SMB Mostrar SMB al rellotge com un bolus estàndard. - Mostrar prediccions al rellotge. - Prediccions Reenviar totes les dades Obrir Configuració a Wear diff --git a/plugins/main/src/main/res/values-cs-rCZ/strings.xml b/plugins/main/src/main/res/values-cs-rCZ/strings.xml index aa40d5df75..f882884bc4 100644 --- a/plugins/main/src/main/res/values-cs-rCZ/strings.xml +++ b/plugins/main/src/main/res/values-cs-rCZ/strings.xml @@ -308,12 +308,9 @@ Řízení z hodinek Wear Nastavování dočasných cílů a vkládání ošetření na hodinkách Wear. Kalkulace použité ve výsledku wizardu: - Nastavení zobrazení Základní nastavení Oznámení při SMB Ukazovat SMB na hodinkách jako normální bolus. - Zobrazovat predikce na hodinkách. - Predikce Nastavení vlastního ciferníku Autorizace vlastního ciferníku Autorizujte načtený vlastní ciferník, aby se změnila a uzamkla některá nastavení hodinek tak, aby vyhovovala designu ciferníku diff --git a/plugins/main/src/main/res/values-da-rDK/strings.xml b/plugins/main/src/main/res/values-da-rDK/strings.xml index b5ca41c7a3..2828b0f607 100644 --- a/plugins/main/src/main/res/values-da-rDK/strings.xml +++ b/plugins/main/src/main/res/values-da-rDK/strings.xml @@ -293,12 +293,9 @@ Kontrolleringer fra Ur Sæt midlertidige mål og indtast behandlinger fra uret. Beregninger inkluderet i guide resultatet: - Visningsindstillinger Generelle indstillinger Giv besked ved SMB Vis SMB på uret som en standard bolus. - Vis forudsigelser på urskiven. - Forudsigelser Send alle data igen Åbn indstillinger på ur diff --git a/plugins/main/src/main/res/values-de-rDE/strings.xml b/plugins/main/src/main/res/values-de-rDE/strings.xml index 7f054677d1..a67be3ac51 100644 --- a/plugins/main/src/main/res/values-de-rDE/strings.xml +++ b/plugins/main/src/main/res/values-de-rDE/strings.xml @@ -310,12 +310,9 @@ Unerwartetes Verhalten. Steuerung durch die Uhr Setze temporäre Ziele und Behandlungen mit der Uhr Berechnungen, die im Assistenten berücksichtigt werden: - Anzeigeeinstellungen Allgemeine Einstellungen Bei SMB benachrichtigen Zeige SMB auf der Uhr wie einen normalen Bolus an. - Zeige Vorhersagen auf dem Watchface. - Vorhersagen Benutzerdefinierte Watchface Einstellungen Benutzerdefinierte Watchface Autorisierung Autorisiere geladene benutzerdefinierte Watchface zum Ändern und Sperren einiger Watchscreen-Einstellungen für das Design der Uhr diff --git a/plugins/main/src/main/res/values-el-rGR/strings.xml b/plugins/main/src/main/res/values-el-rGR/strings.xml index b1eebaf868..e6ab4db0b0 100644 --- a/plugins/main/src/main/res/values-el-rGR/strings.xml +++ b/plugins/main/src/main/res/values-el-rGR/strings.xml @@ -192,12 +192,9 @@ Έλεγχος από ρολόι Ρυθμίστε Στόχους-Προσ Ρυθμού και βάλτε Θεραπείες από το ρολόι. Υπολογισμοί που περιλαμβάνονται στο αποτέλεσμα του γρήγορου οδηγού: - Ρυθμίσεις Εμφάνισης Γενικές Ρυθμίσεις Ειδοποίηση στο SMB Εμφάνιση SMB στο ρολόι όπως ένα τυπικό bolus. - Προβολή πρόβλεψης στο ρολόι. - Προβλέψεις Ξαναστείλτε όλα τα Δεδομένα Ρυθμίσεις στο Wear diff --git a/plugins/main/src/main/res/values-es-rES/strings.xml b/plugins/main/src/main/res/values-es-rES/strings.xml index c9c7341dc0..337a45a066 100644 --- a/plugins/main/src/main/res/values-es-rES/strings.xml +++ b/plugins/main/src/main/res/values-es-rES/strings.xml @@ -309,12 +309,9 @@ Control desde el reloj Establece objetivos temporales (OT) y añade tratamientos desde el reloj Cálculos incluidos en el resultado del asistente: - Ajustes de pantalla Configuración general Notificar los SMB Mostrar los SMB en el reloj como un bolo estándar - Mostrar las predicciones en la esfera - Predicciones Configuración personalizada de esferas Autorización de esferas personalizadas Autorizar a la esfera personalizada a cambiar y bloquear algunos ajustes de la pantalla del reloj, para que se adapten al diseño de la esfera diff --git a/plugins/main/src/main/res/values-fr-rFR/strings.xml b/plugins/main/src/main/res/values-fr-rFR/strings.xml index f9b75aca01..89c03319af 100644 --- a/plugins/main/src/main/res/values-fr-rFR/strings.xml +++ b/plugins/main/src/main/res/values-fr-rFR/strings.xml @@ -308,12 +308,9 @@ Commandes depuis la montre Définir les Cibles Temp et entrer les Traitements depuis la montre. Calculs inclus dans le résultat de l’Assistant : - Parametres d\'affichage Paramètres généraux Notifier en cas de SMB Afficher SMB sur la montre comme un bolus standard. - Affichez les prédictions sur l\'écran de la montre. - Prédictions Paramètres du Cadran Personnalisé Autorisation du Cadran Personnalisé Autoriser le cadran perso chargé à modifier et bloquer certains paramètres d\'affichage de la montre pour un affichage correct du cadran diff --git a/plugins/main/src/main/res/values-hu-rHU/strings.xml b/plugins/main/src/main/res/values-hu-rHU/strings.xml index f9dd4b801c..7eab29908e 100644 --- a/plugins/main/src/main/res/values-hu-rHU/strings.xml +++ b/plugins/main/src/main/res/values-hu-rHU/strings.xml @@ -55,9 +55,7 @@ Wear beállítások - Megjelenítési beállítások Általános beállítások - Előrejelzések RÉGI ADAT diff --git a/plugins/main/src/main/res/values-it-rIT/strings.xml b/plugins/main/src/main/res/values-it-rIT/strings.xml index 47fa995a90..4d8c46cd22 100644 --- a/plugins/main/src/main/res/values-it-rIT/strings.xml +++ b/plugins/main/src/main/res/values-it-rIT/strings.xml @@ -308,12 +308,9 @@ Controlli da smartwatch Imposta Temp-Target e inserisci trattamenti dallo smartwatch. Calcoli inclusi nel risultato del Calcolatore: - Impostazioni di visualizzazione Impostazioni generali Notifica SMB Mostra SMB sullo smartwatch come un bolo standard. - Mostra le predizioni sulla watchface. - Predizioni Impostazioni watchface personalizzata Autorizzazione watchface personalizzata Autorizza la watchface personalizzata caricata a cambiare e bloccare alcune delle impostazioni di visualizzazione dell\'orologio per adattarsi al design della watchface diff --git a/plugins/main/src/main/res/values-iw-rIL/strings.xml b/plugins/main/src/main/res/values-iw-rIL/strings.xml index e7637f8f4c..df6a3fefec 100644 --- a/plugins/main/src/main/res/values-iw-rIL/strings.xml +++ b/plugins/main/src/main/res/values-iw-rIL/strings.xml @@ -309,12 +309,9 @@ שליטה מהשעון הגדירו ערכי מטרה זמניים וציינו טיפולים מהשעון. חישובים הכלולים בתוצאת האשף: - הגדרות תצוגה הגדרות כלליות דיווח על SMB הצג SMB על השעון כמו בולוס סטנדרטי. - הראה את התחזיות על לוח השעון. - חיזוי הגדרות פני שעון מותאמים אישית אישור פני שעון מותאמים אישית פני שעון מותאמים אישית: %1$s diff --git a/plugins/main/src/main/res/values-ko-rKR/strings.xml b/plugins/main/src/main/res/values-ko-rKR/strings.xml index 2a130688ce..a84a53a388 100644 --- a/plugins/main/src/main/res/values-ko-rKR/strings.xml +++ b/plugins/main/src/main/res/values-ko-rKR/strings.xml @@ -3,6 +3,7 @@ SMS 통신기 SMS + SMS 명령을 사용하여 AAPS를 원격 제어합니다. 인증 어플에서: %1$s 뒤에 PIN 암호 끝에 더해지는 자동형성 PIN 부가적인 숫자를 생성되는 일회성 비밀번호 끝에 더하고 기억해야 함. @@ -18,9 +19,15 @@ OTP 비밀번호의 클립보드 복사를 원하는 것이 확실합니까?\n\n 이는 인증 어플이 QRCode를 스캐닝하는데 문제가 있을 때, 비밀번호 수동 입력을 원할 때, 또는 공용 어플 사용 시에 하드웨어 OTP 암호 설정을 원할 때에만 필요합니다. OTP 비밀번호 (Base32 포맷)가 클립보드에 내보내져서 복사되었습니다. 인증 어플 또는 하드웨어 OTP burner에 붙여넣기 하십시오! 1. 인증어플 설치하기 + 2. AAPS OTP 코드를 설정하기 위한 코드 스캔하기 3. 일회성 비밀번호 테스트 인증 초기화 각각의 팔로워 폰에 RFC 6238 TOTP 암호를 사용하는 인증 어플을 설치합니다. 대중적인 무료 어플은 다음과 같습니다:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator. + 인증을 초기화하면 이미 저장된 모든 인증자는 무효화됩니다. 다시 설정해야 합니다! + 확인 + 잘못된 크기! + 잘못된 암호 + 잘못된 OTP 잘못된 코드입니다. 명령이 취소됩니다. 직전의 펌프 통신 종료를 기다리는 동안 타임 아웃 허가된 전화번호 @@ -85,6 +92,9 @@ 잘못된 메시지 내용 허용되지 않는 펌프 이벤트가 발생하면 SMS를 보내기 허용되지 않는 펌프 기록 + Loop 모드를 LGS(저혈당 방지) 로 변경하려면 %1$s 를 입력하고 답장하세요 + Loop 모드를 Closed loop로 변경하려면 %1$s 를 입력하고 답장하세요 + 현재 loop 모드: %1$s 잘못된 형식 BG: Last BG: @@ -97,6 +107,7 @@ 상태를 읽지 못했습니다. 프로파일 변경 생성됨 TBR 기간은 %1$d분의 배수가 되어야 하고 0보다 커야 함. + 일회용 암호 설정을 위한 QR 코드 Loop 중지됨 음식 @@ -111,16 +122,33 @@ 하위 분류 계산기 + 시스템 테마를 따르거나 어두운 색 또는 밝은 색 선택하기 + 앱 색 구성 + 어두운 테마 + 밝은 테마 + 장치 테마 사용하기 프로파일 LP 오프라인에서 사용 가능한 프로파일을 정의하십시오. + 목록에 새로운 것 추가하기 프로파일을 변경하고 현재 프로파일에 대한 변경 사항을 버리시겠습니까? 우선 현재 변경사항을을 저장하거나 재설정하세요 현재 프로파일을 삭제 하시겠습니까? 단위: + 프로파일 이름 없음 + IC 값 오류 + Basal 값 오류 + 목표 값 오류 + ISF 값 오류 + 일부 프로파일 이름에 점을 포함하고 있습니다.\nNS에서 지원하지 않습니다.\n프로파일은 NS에 업로드되지 않습니다. + NS에서 잘못된 프로파일 %1$s이 허용되지 않습니다 + 보기 에러 + 편집할 프로파일 선택하기 프로파일명: + 새로운 프로파일 추가하기 + 현재 프로파일 제거하기 현재 프로파일을 삭제 하시겠습니까 DIA TARG @@ -141,8 +169,13 @@ 펌프 배터리 캐뉼라 확장 Bolus 기능을 사용하는 동안에는 Closed Loop 모드가 중지됩니다. 정말 원하십니까? + 캐뉼라 사용기간 + 패치 펌프 사용기간 + 패치 펌프 홈화면에 상태 표시등 보여주기 + 캐뉼라 사용기간 경고 기준[h] + 캐뉼라 사용기간 위험 기준[h] 인슐린 사용 기간 경고 기준 [h] 인슐린 사용 기간 위험 기준 [h] 센서 사용 기간 경고 기준 [h] @@ -159,12 +192,17 @@ 그래프 인슐린 차트 메뉴 + 혈당의 질 + 혈당 + 만료됨 새 임시Basal 적용: CGM 현재 Loop 상태와 기본 기능 버튼을 표시합니다. 버튼 + xDrip+에 보정값을 전송하거나, 개방 BYODA 보정창을 엽니다 + xDrip+ 또는 BYODA을 열거나 뒤로가기 버튼을 누르면 AAPS로 돌아갑니다 Dexcom 앱이 설치되지 않았습니다. Dexcom앱을 지원가능한 버전으로 업데이트하세요. CGM앱을 실행할 수 없습니다. 앱이 설치되어 있는지 확인하세요. @@ -173,6 +211,7 @@ 입력값을 변경하세요! OpenAPS 업로더 + BG 데이터 상태 빠른마법사 설정 화면을 켜진 상태로 유지 안드로이드의 화면이 꺼지는 것을 방지합니다. 전원이 공급되어 있지 않으면 전력소모가 큽니다. @@ -204,13 +243,18 @@ 탭 이름 단축 관리창에 노트 영역 보여주기 Bolus 마법사는 계산을 수행하지만 계산된 인슐린의 이 부분만 주입됩니다. SMB 알고리즘에 유용합니다. + 혈당증이 다음보다 오래된 경우 총 bolus (100%) 주입하기 Bolus advisor 활성화 혈당이 높을 때 wizard 결과 대신 reminder를 사용하여 나중에 식사하기 (pre-bolus) 마법사에서 Superbolus 활성화하기 마법사에서 Superbolus 기능을 활성화합니다. 어떤 기능인지 확실히 알기전까지 활성화 하지 마세요. 제대로 알지 못하고 사용하면 일슐린이 과다 주입될 수 있습니다! + bolus 알림 활성화하기 + 나중에 마법사를 통해 bolus 주입을 위해 알림을 사용합니다.(\"post-bolus\"). + %s 실행? 예측 관리 + 심장 박동수 편차 기울기 활동 BG impact @@ -228,7 +272,9 @@ ABS DEVSLOPE TREAT + HR 민감도 + 그래프 범위 그래프 기본 스킨 @@ -241,20 +287,70 @@ 예상치 못한 상황 보고를 위해 오늘의 로그 파일을 개발자에게 전송합니다. WEAR + WearOS 시계를 사용하여 AAPS를 모니터링하고 제어합니다. + (열결된 워치가 없습니다) + 펌프 상태 + Loop 상태 + 계산. 마법사:\n인슐린:%1$.2fU\n탄수화물: %2$dg + 선택한 빠른 마법사를 더 이상 사용할 수 없습니다, 타일을 새로고침 하십시오 + 빠른 마법사: %1$s\n인슐린: %2$.2fU\n탄수화물: %3$dg + 임시 목표 알 수 없는 사전 설정: %1$s + 임시-목표 실행을 취소하시겠습니까? + 워치와 폰과 다른 단위입니다! + 제로-임시-목표- 임시-목표 실행을 취소하시겠습니까? + 최소-BG 범위가 넘었습니다! + 최대-BG 범위가 넘었습니다! + 임시 목표:\n최소: %1$s\n최대: %2$s\n기간: %3$s + 임시 목표:\n목표: %1$s\n기간: %2$s + 임시 목표:\n이유: %1$s\n목표: %2$s\n기간: %3$s 성공하지 못했습니다. 폰을 확인하세요 워치 설정 워치로 제어하기 임시목표와 관리입력을 워치로 설정합니다. 마법사 결과에 사용 된 계산: - 화면 설정 일반 설정 SMB 알림 일반 Bolus처럼 워치에 SMB 표시 - 워치페이스에서 예측치를 보여줍니다. - 예측 + 사용자 지정- 워치 페이스 설정 + 사용자 지정 워치 페이스 승인 + 로드된 사용자 지정 워치 페이스를 승인하여 워치 페이스 디자인에 맞게 일부 시계 화면의 설정을 변경하고 잠급니다 + 사용자 지정 워치 페이스: %1$s + 워치 페이스 로딩하기 + 워치 페이스 정보 + 템플릿 내보내기 + 사용자 지정 워치 페이스 템플릿 내보내기 모든 데이터 다시 보내기 워치에서 설정 열기 + 워치 페이스에 의해 잠긴 선호 목록 + 워치 페이스에 필요한 선호 목록 + 워치 페이스에 포함된 필드 목록 Loop가 어떤 작동하는지에 대한 간략한 개요를 연속 알림으로 보여줍니다. 오래된 데이터 + 펌프에서 데이터를 가져오려고 합니다. + TDD: 여전히 오래된 데이터입니다! 펌프에서 로드할 수 없습니다. + g + h + 활성화된 프로파일 스위치가 없습니다! + 프로파일:\n\n시간 변화: %1$d\n백분율: %2$d%%\" + %1$.2fU %1$.0f%% + 프로파일이 로딩되지 않았습니다 + APS 모드에서만 이용 가능합니다! + 지난 결과를 이용할 수 없습니다! + CLOSED LOOP + OPEN LOOP + LOOP 비활성화 + APS + 마지막 실행 + 마지막 실행 + 오늘 + 몸무게 + 목표는 APS 모드에서만 적용 가능합니다! + 기록이 없습니다! + U + 임시 목표 + 까지 + 기본 범위 + 목표 + 비율: %1$.2fU/h (%2$.2f%%) \n기간%3$d 분 diff --git a/plugins/main/src/main/res/values-lt-rLT/strings.xml b/plugins/main/src/main/res/values-lt-rLT/strings.xml index 46110dca52..515d7269a6 100644 --- a/plugins/main/src/main/res/values-lt-rLT/strings.xml +++ b/plugins/main/src/main/res/values-lt-rLT/strings.xml @@ -308,12 +308,9 @@ Laikrodžio valdikliai Nustatyti Laikinus Tikslus ir įvesti terapinius įrašus iš laikrodžio. Skaičiavimai, įtraukti į Patarėjo rezultatą: - Ekrano nustatymai Bendrieji nustatymai Pranešti apie SMB Rodyti SMB laikrodyje kaip standartinį bolusą. - Rodyti prognozes laikrodyje. - Prognozė Pasirinktiniai laikrodžio ekrano nustatymai Pasirinktinė laikrodžio ekrano autorizacija Leisti įkeltam pasirinktiniam ekranui keisti ir užrakinti kai kuriuos laikrodžio nustatymus, kad jie atitiktų ekrano dizainą diff --git a/plugins/main/src/main/res/values-nl-rNL/strings.xml b/plugins/main/src/main/res/values-nl-rNL/strings.xml index 8405582da9..9980851ab3 100644 --- a/plugins/main/src/main/res/values-nl-rNL/strings.xml +++ b/plugins/main/src/main/res/values-nl-rNL/strings.xml @@ -24,6 +24,10 @@ Reset Authentificatie Installeer de Authenticator-app op elke volger telefoon die RFC 6238 TOTP tokens ondersteunt. Populaire gratis apps zijn:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator Door de authenticator opnieuw in te stellen maakt u alle reeds aangemaakte authenticatoren ongeldig. U moet ze opnieuw instellen! + OK + ONGELDIGE LENGTE! + FOUTIEVE PIN + FOUTIEVE OTP Verkeerde code. Opdracht geannuleerd. Time-out tijdens het wachten op het voltooien van de vorige pomp communicatie Geautoriseerde telefoon nummers @@ -304,12 +308,9 @@ Bedieningen via horloge Stel tijdelijke doelen en bolussen in vanop je horloge. Berekeningen inclusief in het resultaat van de wizard - Scherm instellingen Algemene instellingen Waarschuw bij SMB Toon SMB op horloge zoals gewone bolussen. - Toon de voorspellingen op het horloge. - Voorspellingen Aanpasbare Wijzerplaat Instellingen Aanpasbare Wijzerplaat Autorisatie Sta geladen aanpasbare wijzerplaat toe om sommige weergave-instellingen van horloge te wijzigen en te vergrendelen voor het ontwerp van de wijzerplaat diff --git a/plugins/main/src/main/res/values-no-rNO/strings.xml b/plugins/main/src/main/res/values-no-rNO/strings.xml index 76cc5ac513..ed654f7943 100644 --- a/plugins/main/src/main/res/values-no-rNO/strings.xml +++ b/plugins/main/src/main/res/values-no-rNO/strings.xml @@ -308,12 +308,9 @@ Kontroller fra klokke Sett midl. mål og angi behandlinger fra klokken. Beregninger inkludert i resultatet fra veiviseren: - Visningsinnstillinger Generelle innstillinger Varsle ved SMB Vis SMB på klokken som en standard bolus. - Vis blodsukkerprognoser på klokken. - Prognoser Innstillinger for tilpasset klokkebakgrunn Godkjenning for tilpasset klokkebakgrunn Godkjenne at tilpasset klokkebakgrunn endrer AAPS- og klokkeinnstillinger i henhold til klokkebakgrunnens design diff --git a/plugins/main/src/main/res/values-pl-rPL/strings.xml b/plugins/main/src/main/res/values-pl-rPL/strings.xml index e306076eb5..3dfe87e9d2 100644 --- a/plugins/main/src/main/res/values-pl-rPL/strings.xml +++ b/plugins/main/src/main/res/values-pl-rPL/strings.xml @@ -308,12 +308,9 @@ Sterowanie z zegarka Ustawiaj wartości docelowe i wprowadzaj leczenie z zegarka. Obliczenia uwzględnione w wynikach kreatora: - Ustawienia wyświetlania Ustawienia ogólne Powiadom na SMB Pokaż SMB na zegarku jak bolus standardowy. - Pokaż prognozę poziomu na zegarku. - Prognozy Ustawienia niestandardowej tarczy Uprawnienia niestandardowej tarczy Upoważnij załadowaną niestandardową tarczę zegarka, aby mogła zmieniać i zablokować niektóre ustawienia wyświetlacza zegarka w celu dopasowania ich do tarczy diff --git a/plugins/main/src/main/res/values-pt-rBR/strings.xml b/plugins/main/src/main/res/values-pt-rBR/strings.xml index c543e5864d..b2871ff5ba 100644 --- a/plugins/main/src/main/res/values-pt-rBR/strings.xml +++ b/plugins/main/src/main/res/values-pt-rBR/strings.xml @@ -1,16 +1,18 @@ + Comunicador SMS + SMS Controle remotamente o AndroidAPS usando comandos SMS. do aplicativo Autenticador para: %1$s seguido por PIN PIN adicional obrigatório no fim do token Dígitos adicionais que devem ser memorizados e colados no final de cada Uma-Password-Única que seja gerada Configuração do Autenticador Código para verificar: - CÓDIGO + PIN + CÓDIGO OPT + PIN O código de verificação consiste em 6 dígitos exibidos pelo app Autenticador (conhecido como OTP) seguido por 3 ou mais dígitos do PIN obrigatório. - Repor Autenticadores - Repor Chave Autenticador + Redefinir Autenticadores + Redefinir chave do Autenticador Tem certeza de redefinir chave Authenticador? Ele tornará todos os Authenticators configurados atualmente como inválidos, e precisará de os configurar novamente. Nova Chave do Autenticador foi gerada! Por favor, use o QRCode atualizado para os autenticadores. Exportando senha OTP @@ -19,9 +21,13 @@ 1. Instalar Autenticador 2. Escaneie o QR Code para configurar os códigos OTP do AAPS 3. Teste Uma-Password-Única - Repor Autenticadores + Redefinir Autenticadores Instalar uma app Autenticador que suporte Tokens RFC 6238 TOTP em cada telefone seguidor. Populares aplicativos gratuitos são:\n • Authy\n • o Google Authenticator\n • LastPass Autenticador\n • FreeOTP Autenticador Ao redefinir o autenticador, você torna todos os autenticadores já provisionados inválidos. Você precisará configurá-los novamente! + OK + Tamanho inválido! + PIN incorreto + OTP incorreto Código errado. Comando cancelado. Excedido o tempo limite de espera ao aguardar o término da última comunicação com a bomba Números de telefone permitidos @@ -85,7 +91,7 @@ xDrip+ não está recebendo calibrações Corpo da mensagem inválido Enviar SMS se um evento de bomba inacessível for identificado - Reportar bomba inacessível + Relatar bomba inacessível Para mudar o modo do Loop para LGS (Suspensão de Baixa Glicemia), responda com o código %1$s Para mudar o modo do Loop para Loop Fechado, responda com o código %1$s Modo de loop atual: %1$s @@ -127,7 +133,7 @@ Defina um perfil que está disponível offline. adicionar novo à lista Deseja mudar de perfil e descartar as alterações feitas no perfil atual? - Guardar ou repor as alterações atuais primeiro + Salve ou redefina as alterações atuais primeiro Eliminar perfil atual? Unidades: Nome do perfil ausente @@ -303,12 +309,9 @@ Controles do Relógio Definir Alvo-Temp and inserir Tratamentos do relógio. Resultado cálculos incluídos no Assistente: - Mostrar Configurações Configurações gerais Notificar no SMB Mostrar SMB no relogio como bolus normal. - Mostrar a predições na face do relogio. - Previsão Configurações personalizadas de Watchface Autorização de Watchface Personalizada Autorizar watchface carregado e carregado para alterar e bloquear algumas configurações de relógio para o design do watchface @@ -320,6 +323,7 @@ Reenviar Todos os Dados Abrir Definições em Wear Lista de preferências bloqueadas pela Watchface + Lista de preferências solicitadas pela Watchface Lista de campos incluídos na Watchface Mostra uma notificação em curso com um breve resumo do que o seu loop está a fazer diff --git a/plugins/main/src/main/res/values-pt-rPT/strings.xml b/plugins/main/src/main/res/values-pt-rPT/strings.xml index 368da1218e..dcf7c28303 100644 --- a/plugins/main/src/main/res/values-pt-rPT/strings.xml +++ b/plugins/main/src/main/res/values-pt-rPT/strings.xml @@ -308,12 +308,9 @@ Controles do Relógio Definir Alvo-Temp and inserir Tratamentos do relógio. Resultado cálculos incluídos no Assistente: - Definições Ecrã Definições Gerais Notificar no SMB Mostrar SMB no relogio como bolus normal. - Mostrar previsões no mostrador. - Previsões Definições da watchface predefinida Autorização da watchface predefinida Autorizar watchface por definição para alterar e bloquear algumas configurações de exibição do relógio para se adequarem ao design do watchface diff --git a/plugins/main/src/main/res/values-ro-rRO/strings.xml b/plugins/main/src/main/res/values-ro-rRO/strings.xml index c7fb346d1b..e881e1ee66 100644 --- a/plugins/main/src/main/res/values-ro-rRO/strings.xml +++ b/plugins/main/src/main/res/values-ro-rRO/strings.xml @@ -264,12 +264,9 @@ Controlare din ceas Setare Ținte-Temporare și se introduc Tratamente din ceas. Calcule incluse în rezultatul asistentului: - Setări afișare Setări generale Notifică despre SMB Arată SMB pe ceas ca și un bolus standard. - Arată previziunile pe ceas. - Predicții Retrimite toate datele Deschide setările pe Wear diff --git a/plugins/main/src/main/res/values-ru-rRU/strings.xml b/plugins/main/src/main/res/values-ru-rRU/strings.xml index cf15bd4c4c..9347813a0d 100644 --- a/plugins/main/src/main/res/values-ru-rRU/strings.xml +++ b/plugins/main/src/main/res/values-ru-rRU/strings.xml @@ -24,6 +24,10 @@ Сбросить авторизацию На каждом отслеживающем телефоне установите приложение Authenticator, поддерживающее маркеры TOTP RFC 6238. Популярные бесплатные приложения: \n Authy\n Google Authenticator\n LastPass Authenticator\n FreeOTP Authenticator После сброса аутентификатора вы делаете все созданные идентификаторы недействительными. Вам нужно будет снова создать их! + OK + НЕВЕРНЫЙ РАЗМЕР! + НЕВЕРНЫЙ PIN-КОД + НЕВЕРНЫЙ РАЗОВЫЙ КОД Неверный код. Команда отменена. Время ожидания окончания предыдущего соединения с помпой истекло разрешенные телефонные номера @@ -239,6 +243,7 @@ Сокращенные наименования вкладок Показать поле примечаний в диалогах терапии Мастер болюса выполняет расчет, но подается только эта часть рекомендуемого инсулина. Полезно с алгоритмом SMB. + Подать полный болюс (100%), если гликемия старше Вкл помощник болюса Воспользуйтесь напоминанием, чтобы начать есть позже, вместо того, чтобы задействовать помощник болюса на высоких значениях ГК (\"пре-болюс\") Активировать суперболюс в помощнике болюса @@ -303,14 +308,22 @@ Контроль с часов Ставить временные цели и вводить терапию с часов. Расчеты включены в результат калькулятора: - Параметры экрана Общие настройки Сообщить о супер микро болюсе SMB Показывать супер микро болюс SMB на часах как стандартный болюс. - Показывать линию тренда на смарт-часах. - Прогнозирование + Настройка циферблатов + Авторизация пользовательских циферблатов + Авторизовать загруженные пользовательские циферблаты для изменения и блокировки некоторых параметров отображения часов в соответствии с дизайном часов + Пользовательский циферблат %1$s + Загрузить циферблат + Циферблат Infos + Экспортировать шаблон + Пользовательский шаблон циферблата экспортирован повторить отправку всех данных Открыть настройки на Wear + Список настроек, блокируемых циферблатом + Список настроек, требующихся для циферблата + Список полей, входящих в циферблат Показывает текущие уведомления и краткий обзор событий цикла старые данные diff --git a/plugins/main/src/main/res/values-sk-rSK/strings.xml b/plugins/main/src/main/res/values-sk-rSK/strings.xml index ed4a9f4fbe..3094af3305 100644 --- a/plugins/main/src/main/res/values-sk-rSK/strings.xml +++ b/plugins/main/src/main/res/values-sk-rSK/strings.xml @@ -309,12 +309,9 @@ Ovládanie z hodiniek Nastavovanie dočasných cieľov a vkladanie ošetrení hodinkami. Kalkulácia použitá vo výsledku wizardu: - Nastavenie zobrazenia Všeobecné nastavenia Oznámenie pri SMB Ukazovať SMB na hodinkách ako normálny bolus. - Zobrazovať predikcie na hodinkách. - Predikcia Nastavenie vlastného ciferníka Autorizácia vlastného ciferníka Autorizujte načítaný vlastný ciferník, aby se zmenili a uzamkli niektoré nastavenia hodiniek tak, aby vyhovovali designu ciferníka diff --git a/plugins/main/src/main/res/values-sv-rSE/strings.xml b/plugins/main/src/main/res/values-sv-rSE/strings.xml index 8bf7381617..6d03304326 100644 --- a/plugins/main/src/main/res/values-sv-rSE/strings.xml +++ b/plugins/main/src/main/res/values-sv-rSE/strings.xml @@ -309,12 +309,9 @@ Kontrollera från klockan Sätt temp målvärde och ange behandlingar från klockan. Kalkyler inkluderade i resultatet - Visningsinställningar Generella inställningar Skicka notis vid SMB Visa SMB på klockan som en standardbolus. - Visa BG-prognos på klockan. - BG-prognos Anpassade inställningar för urtavla Anpassad auktorisering för urtavla Auktorisera inlästa anpassade urtavlor för att ändra och låsa vissa visningsinställningar för att passa design av urtavlan diff --git a/plugins/main/src/main/res/values-tr-rTR/strings.xml b/plugins/main/src/main/res/values-tr-rTR/strings.xml index 0d2c58e28c..1a95f1180f 100644 --- a/plugins/main/src/main/res/values-tr-rTR/strings.xml +++ b/plugins/main/src/main/res/values-tr-rTR/strings.xml @@ -309,12 +309,9 @@ Saat tarafından kontrol Tedavileri ve Geçici hedefleri saat tarafından girin. Sihirbaz sonucuna dahil edilen hesaplamalar: - Görüntü Ayarları Genel Ayarlar SMB\'yi bildir Saatte SMB\'yi standart bir bolus gibi göster. - Saat arayüzü üzerindeki tahminleri göster. - Tahminler Özel Saat arayüzü Ayarları Özel Saat arayüzü Yetkilendirmesi Bazı saat ekranı ayarlarını saatarayüzü tasarımına uyacak şekilde değiştirmek ve kilitlemek için, yüklenen özel saat arayüzüne yetki verin diff --git a/plugins/main/src/main/res/values-zh-rCN/strings.xml b/plugins/main/src/main/res/values-zh-rCN/strings.xml index 24ff406fb8..7e0e457535 100644 --- a/plugins/main/src/main/res/values-zh-rCN/strings.xml +++ b/plugins/main/src/main/res/values-zh-rCN/strings.xml @@ -289,12 +289,9 @@ 从手表上控制 设置临时目标并从手表中进行治疗操作。 包含在向导中的计算结果: - 显示设置 常规设置 在 SMB 上通知 在手表上像显示常规大剂量一样显示SMB微型大剂量 - 在手表的表盘上显示预测 - 预测 重新发送所有数据 在手表上打开设置 diff --git a/plugins/sensitivity/src/main/res/values-pt-rBR/strings.xml b/plugins/sensitivity/src/main/res/values-pt-rBR/strings.xml index f38ecdfe18..4bf80e0e77 100644 --- a/plugins/sensitivity/src/main/res/values-pt-rBR/strings.xml +++ b/plugins/sensitivity/src/main/res/values-pt-rBR/strings.xml @@ -14,9 +14,9 @@ Intervalo para autosens [h] Quantidade de horas observadas para a deteção de sensibilidade (o tempo de absorção dos hidratos de carbono é excluído) Valor predefinido: 1.2\n Este é um multiplicador para autosens (e em breve autotune) que coloca um limite máximo de 20%% aos rácios superiores e inferiores de autosens, o que por sua vez calcula o quão alto autosens pode ajustar a basal, quão pode baixar o Factor de Sensibilidade (FSI) e baixar o valor alvo de glicose no sangue. - Valor padrão: 0.7\nO outro lado dos limites de segurança do autosens. Coloca um tecto no quão baixo autosens pode ajustar as basais, e quão alto pode ajustar os valores de ISF e valor alvo de glucose no sangue (BG). - Rácio máx. autosens - Rácio min. autosens + Valor padrão: 0,7\nO outro lado dos limites de segurança do Autosens, colocando um limite no quanto o Autosens pode ajustar os basais e no quanto pode ajustar os alvos FSI e alvos de Glicose. + Razão máx. autosens + Razão min. autosens Valor padrão: 3.0 para assitência avançada de refeições (AAR) ou 8.0 para super micro bolus (SMB). Esta é a configuração padrão para o calculo de quanto varia a cada 5 min a glicemia (BG) devido à absorção de carboidratos. O padrão é 3mg/dl/5min. Isso afeta a rapidez com que decaem os carboidratos ativos (CA) e quanta absorção de carboidrato será considerada no cálculo da previsão de glicemia futura, tornando possível notar que glicemia está baixando mais do que o esperado ou não subindo como esperado. Tempo máx. absorção refeição [h] Hora em que qualquer refeição é considerada absorvida. Restantes hidratos de carbono serão cortados. diff --git a/pump/combo/src/main/res/values-pt-rBR/strings.xml b/pump/combo/src/main/res/values-pt-rBR/strings.xml index d2517ebc70..17193f0b08 100644 --- a/pump/combo/src/main/res/values-pt-rBR/strings.xml +++ b/pump/combo/src/main/res/values-pt-rBR/strings.xml @@ -36,7 +36,7 @@ Configuração da bomba inválida, verifique a documentação e se o menu de informações rápidas está nomeado de QUICK INFO utilizando o programa de configuração 360. Lendo perfil basal O histórico da bomba foi alterado após o cálculo do bolo ter sido realizado. O bolus não foi aplicado. Por favor, verifique se bolus ainda é necessário. - O bolus foi aplicado, mas não foi possível adicionar ao histórico. Isto é possível se dois bolus do mesmo valor baixo foram aplicados nos últimos dois minutos. Por favor verifique o histórico da bomba e use o Careportal para adicionar os dados em falta caso necessário. Cuidado para não adicionar dados com o mesmo valor no mesmo minuto. + Bolus foi entregue com sucesso, mas a adição da entrada em Tratamento falhou. Isso pode acontecer se dois pequenos bolus do mesmo tamanho forem administrados nos últimos dois minutos. Verifique o histórico da bomba e as entradas de tratamento e use o Careportal para adicionar entradas ausentes. Certifique-se de não adicionar nenhuma entrada para o mesmo minuto e o mesmo valor. Rejeitando basal temporária porque o cálculo não considerou o histórico da bomba alterado recentemente Atualizando estado da bomba A taxa basal na bomba mudou e será atualizada em breve diff --git a/pump/combo/src/main/res/values-ro-rRO/strings.xml b/pump/combo/src/main/res/values-ro-rRO/strings.xml index 1efb6a0860..9d4c2d40c1 100644 --- a/pump/combo/src/main/res/values-ro-rRO/strings.xml +++ b/pump/combo/src/main/res/values-ro-rRO/strings.xml @@ -49,6 +49,11 @@ Total RBTuri Bolus oprit Se oprește bolusul + Număr erori comunicație + Arată număr erori comunicație + Arată numărul de erori în comunicarea cu Ruffy. Dacă numărul este mai mare de zero, asta indică în cele mai multe cazuri probleme de comunicare cu Ruffy (ar putea fi nevoie de restart). Niciodată + La eroare + Întotdeauna utilizare nesigură diff --git a/pump/danar/src/main/res/values-ro-rRO/strings.xml b/pump/danar/src/main/res/values-ro-rRO/strings.xml index 3ea04e700d..569cee5e11 100644 --- a/pump/danar/src/main/res/values-ro-rRO/strings.xml +++ b/pump/danar/src/main/res/values-ro-rRO/strings.xml @@ -1,2 +1,4 @@ - + + Acțiune nesuportată în pompă. Utilizați doar intrerfața AAPS! + diff --git a/pump/diaconn/src/main/res/values-ro-rRO/strings.xml b/pump/diaconn/src/main/res/values-ro-rRO/strings.xml index 5fae0b1468..e776af808d 100644 --- a/pump/diaconn/src/main/res/values-ro-rRO/strings.xml +++ b/pump/diaconn/src/main/res/values-ro-rRO/strings.xml @@ -152,4 +152,6 @@ Starea LGS este inactiv, comanda de inactivare este refuzată. Pornirea bazalei temporare este respinsă atunci când se execută bazala temporară Oprirea bazalei temporare este respinsă atunci când bazala temporară nu rulează + Trimite jurnalele pompei către Diaconn Cloud. + Sincronizare în Cloud Diaconn diff --git a/pump/eopatch/src/main/res/values-lt-rLT/strings.xml b/pump/eopatch/src/main/res/values-lt-rLT/strings.xml index a0453554af..760bb7f97d 100644 --- a/pump/eopatch/src/main/res/values-lt-rLT/strings.xml +++ b/pump/eopatch/src/main/res/values-lt-rLT/strings.xml @@ -27,21 +27,21 @@ 1 val 30 min 2 val \u0020 - Norėdami aktyvuoti naują rezervuarą, dabartinį turite baigti naudoti. Insulino tiekimas bus nutrauktas. - Rezervuaras baigtas naudoti. - Rezervuaras deaktyvuotas.\nBaikite naudoti rezervuarą.\nPašalinkite pompą nuo kūno. - Šiuo metu leidžiamas bolusas. Ar tikrai norite nutraukti insulino leidimą ir baigti naudoti rezervuarą? - Šiuo metu leidžiama laikina bazė. Ar tikrai norite nutraukti insulino leidimą ir baigti naudoti rezervuarą? - Šiuo metu leidžiamas bolusas ir veikia laikina bazė. Ar tikrai norite nutraukti insulino leidimą ir baigti naudoti rezervuarą? - Ar tikrai baigti naudoti rezervuarą? + Norėdami aktyvuoti naują rezervuarą, dabartinį turite išjungti. Insulino tiekimas bus nutrauktas. + Rezervuaras išjungtas. + Rezervuaras išjungtas.\nBaikite naudoti rezervuarą.\nPašalinkite pompą nuo kūno. + Šiuo metu leidžiamas bolusas. Ar tikrai norite nutraukti insulino leidimą ir išjungti rezervuarą? + Šiuo metu leidžiama laikina bazė. Ar tikrai norite nutraukti insulino leidimą ir išjungti rezervuarą? + Šiuo metu leidžiamas bolusas ir veikia laikina bazė. Ar tikrai norite nutraukti insulino leidimą ir išjungti rezervuarą? + Ar tikrai išjungti rezervuarą? Liko insulino Liko laiko Užbaigti - Baigti naudoti - Ryšio klaida baigiant naudoti rezervuarą - Įprastam deaktyvavimui spauskite \'Kartoti\'.\nVienpusiam deaktyvavimui spauskite \'Baigti naudoti\'. + Išjungti + Ryšio klaida išjungiant rezervuarą + Įprastam deaktyvavimui spauskite \'Kartoti\'.\nVienpusiam deaktyvavimui spauskite \'Išjungti\'. Įprastam deaktyvavimui spauskite \'Kartoti\'. - Vienpusiam deaktyvavimui spauskite \'Baigti naudoti\'. + Vienpusiam deaktyvavimui spauskite \'Išjungti\'. Rankiniu būdu išjungti rezervuaro aliarmus Vienpusiškai deaktyvavus, dėl ryšio klaidos rezervuaro aliarmo garsas gali nesustoti. Tokiu atveju Jūs galite jį visiškai nutildyti, pradurdami rankinio aliarmo atšaukimo prievadą, kaip nurodyta toliau: @@ -60,8 +60,8 @@ Pasiruoškite priklijuoti rezervuarą 3/6 Nuimkite pleistro apsaugą ir paspauskite \'Kitas\'. - [Caution1] Jei adata kyšo, spauskite \'Baigti naudoti\'. - [Caution2] Jei rezervuaras yra šlapias ar purvinas, arba pleistras susiraukšlėjęs, spauskite \'Baigti naudoti\'. + [Caution1] Jei adata kyšo, spauskite \'Išjungti\'. + [Caution2] Jei rezervuaras yra šlapias ar purvinas, arba pleistras susiraukšlėjęs, spauskite \'Išjungti\'. Rezervuaro prijungimas 4/6 Nuvalykite ir nudžiovinkite infuzijos vietą, tada priklijuokite rezervuarą prie odos. @@ -96,11 +96,11 @@ Sustabdžius dabartinis bolusas bus atšauktas. \n\nLiko insulino : %1$.2f v Sustabdžius dabartinė laikina bazė bus atšaukta. \n\nDydis : %1$s v/val\nLiko laiko : %2$s Insulino tiekimas bus sustabdytas. - Baigti naudoti/Keisti rezervuarą + Išjungti/Keisti rezervuarą Aktyvuoti rezervuarą - Baigti naudoti rezervuarą + Išjungti rezervuarą Atnaujinti - Baigti naudoti + Išjungti Ryšio patikrinimas Sustabdyti Sustabdyta @@ -113,11 +113,11 @@ Apdorojama Kartoti [Caution] Nenuimkite adatos dangtelio ir pleistro, kol nebus paprašyta. - Ar tikrai baigti naudoti rezervuarą? - Dėl nepatvirtintos boluso informacijos skaičiuotuvo negalima naudoti iki %s.\n\nAr tikrai norite baigti naudoti rezervuarą? + Ar tikrai išjungti rezervuarą? + Dėl nepatvirtintos boluso informacijos skaičiuotuvo negalima naudoti iki %s.\n\nAr tikrai norite išjungti rezervuarą? Adatos įvedimo klaida. Įsitikinkite, kad skylė, likusi pasukus svirtelę, yra tiesi ir spauskite \'Kartoti\'. - Norėdami deaktyvuoti rezervuarą spauskite \'Baigti naudoti\'. + Norėdami deaktyvuoti rezervuarą spauskite \'Išjungti\'. Bazės sustabdymo laikas Atnaujinti insulino tiekimą Pompos sustabdymo pabaiga.\nNorėdami atnaujinti insulino tiekimą, spauskite \'Patvirtinti\'.\n\n[Caution]\nInsulino tiekimas nebus atnaujintas, kol nepaspausite \'Patvirtinti\'.\nNepaspaudus \'Patvirtinti\', gali kilti hiperglikemija. diff --git a/pump/eopatch/src/main/res/values-ro-rRO/strings.xml b/pump/eopatch/src/main/res/values-ro-rRO/strings.xml index 2bc6062318..e474073435 100644 --- a/pump/eopatch/src/main/res/values-ro-rRO/strings.xml +++ b/pump/eopatch/src/main/res/values-ro-rRO/strings.xml @@ -1,5 +1,6 @@ + EOPatch2 Alerte Stare Rată bazală implicită diff --git a/pump/medtrum/src/main/res/values-bg-rBG/strings.xml b/pump/medtrum/src/main/res/values-bg-rBG/strings.xml index 7d12bc6b61..0fc18261f7 100644 --- a/pump/medtrum/src/main/res/values-bg-rBG/strings.xml +++ b/pump/medtrum/src/main/res/values-bg-rBG/strings.xml @@ -3,7 +3,6 @@ Medtrum MT - Интеграция за помпа Medtrum Nano Настройки за помпа Medtrum Грешка в помпа: %1$s !! Помпата е спряна diff --git a/pump/medtrum/src/main/res/values-cs-rCZ/strings.xml b/pump/medtrum/src/main/res/values-cs-rCZ/strings.xml index 1d386306d2..87a3910805 100644 --- a/pump/medtrum/src/main/res/values-cs-rCZ/strings.xml +++ b/pump/medtrum/src/main/res/values-cs-rCZ/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Integrace pumpy Medtrum Nano + Integrace pumpy pro Medtrum Nano a Medtrum 300U Nastavení pumpy Medtrum Chyba pumpy: %1$s!! Pumpa je pozastavena diff --git a/pump/medtrum/src/main/res/values-de-rDE/strings.xml b/pump/medtrum/src/main/res/values-de-rDE/strings.xml index ac4238e2e5..997e3b8ef9 100644 --- a/pump/medtrum/src/main/res/values-de-rDE/strings.xml +++ b/pump/medtrum/src/main/res/values-de-rDE/strings.xml @@ -3,7 +3,6 @@ Medtrum MT - Pumpenintegration für Medtrum Nano Medtrum Pumpeneinstellungen Pumpenfehler: %1$s!! Pumpe ist ausgesetzt diff --git a/pump/medtrum/src/main/res/values-es-rES/strings.xml b/pump/medtrum/src/main/res/values-es-rES/strings.xml index ef9134dbe6..b66f3ae3c4 100644 --- a/pump/medtrum/src/main/res/values-es-rES/strings.xml +++ b/pump/medtrum/src/main/res/values-es-rES/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Integración de bombas de insulina Medtrum Nano + Integración de bombas de insulina Medtrum Nano y Medtrum 300U Ajustes de la bomba Medtrum Error de bomba: %1$s !! Bomba suspendida diff --git a/pump/medtrum/src/main/res/values-fr-rFR/strings.xml b/pump/medtrum/src/main/res/values-fr-rFR/strings.xml index 02ed4893e5..b8685bbfcd 100644 --- a/pump/medtrum/src/main/res/values-fr-rFR/strings.xml +++ b/pump/medtrum/src/main/res/values-fr-rFR/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Intégration de pompe pour Medtrum Nano + Intégration des pompes Medtrum Nano et Medtrum 300U Paramètres de la pompe Medtrum Erreur pompe: %1$s!! La pompe est suspendue diff --git a/pump/medtrum/src/main/res/values-it-rIT/strings.xml b/pump/medtrum/src/main/res/values-it-rIT/strings.xml index be2266a908..594c3290fb 100644 --- a/pump/medtrum/src/main/res/values-it-rIT/strings.xml +++ b/pump/medtrum/src/main/res/values-it-rIT/strings.xml @@ -3,7 +3,6 @@ Medtrum MT - Integrazione del microinfusore Medtrum Nano Impostazioni micro Medtrum Errore micro: %1$s!! Il micro è sospeso diff --git a/pump/medtrum/src/main/res/values-iw-rIL/strings.xml b/pump/medtrum/src/main/res/values-iw-rIL/strings.xml index 4d4e49e9df..618b82acf9 100644 --- a/pump/medtrum/src/main/res/values-iw-rIL/strings.xml +++ b/pump/medtrum/src/main/res/values-iw-rIL/strings.xml @@ -1,6 +1,7 @@ + תמיכה במשאבת Medtrum Nano ו-Medtrum 300U בולוס פעיל diff --git a/pump/medtrum/src/main/res/values-ko-rKR/strings.xml b/pump/medtrum/src/main/res/values-ko-rKR/strings.xml index 36c8a820fe..7046fb4f4f 100644 --- a/pump/medtrum/src/main/res/values-ko-rKR/strings.xml +++ b/pump/medtrum/src/main/res/values-ko-rKR/strings.xml @@ -1,9 +1,118 @@ + Medtrum + MT + Medtrum 펌프 설정 + 펌프 오류: %1$s !! + 펌프 중지됨 + 시간 당 최대 인슐린을 초과하여 펌프가 중지됨 + 일일 최대 인슐린을 초과하여 펌프가 중지됨 + Patch가 활성화되지 않음 + 펌프에 사용자 설정 실패함! + 블루투스 상태 + 마지막 연결 + 활성 bolus + 펌프 상태 + 알람 활성화 + %.2f U + %.2f V + Basal 종류 + Basal 양 + %.2f U/h + 펌프 종류 + 펌웨어 버전 + Patch 번호 + Patch 만료 + 새로 고침 + 알람 재설정 + Patch 교체 + 사용자에 의해 요청됨 + 활성화 안 됨 + 없음 + 펌프 배터리 낮음 + 펌프 레저버 인슐린 적음 + 펌프 곧 만료됨 + 저혈당 중지 + 저혈당 중지 2 + 자동 중지됨 + 시간 당 최대치 중지됨 + 일일 최대치 중지됨 + 중지됨 + 일시 정지됨 + 주입 막힘 + 만료됨 + 인슐린 없음 + Patch 결함 + Patch 결함 2 + 베이스 결함 + 배터리 방전 + 보정 안됨 + 펌프 시간대 업데이트가 실패함, 메시지를 스누즈하고 수동으로 새로 고침하세요. + 재시도 + 다음 + 폐기 + Patch 활성화 + 연결과 채우기 + 프라임 + 프라이밍 + 프라이밍 완료 + Patch 부착 + 활성화 중... + 활성화 완료 + Patch 비활성화 + 비활성화 중... + Patch 비활성화됨 + 활성화 진행 중 + 예상치 못한 상태: %1$s + 프로파일이 선택되지 않았습니다. 프로파일을 선택하고 다시 시도하세요. + 펌프 베이스 시리얼: %1$X + 활성화된 patch가 없습니다. 활성화 과정을 시작하려면 다음을 누르세요. + 다음 단계까지 펌프 베이스를 patch에 연결하면 안됩니다! + 새로운 patch에 펌프 베이스를 연결한 뒤, 잔여 공기를 제거하고 인슐린을 채웁니다. 이후 다음을 누르세요. + 참고: 사용을 위해 최소 70 U이 필요합니다. + 아직 몸에 patch를 부착하지 마십시오. + 바늘 버튼을 반쯤 누르세요. 그리고나서 다음을 눌러 프라임을 시작하세요. + 프라이밍이 완료될 때까지 기다리십시오. + 프라임에 실패함, 재시도를 눌러 다시 시도하세요. + 계속하려면 다음을 누르세요. + 활성화를 시작하려면 다음을 누르세요. + 안전 잠금 장치를 제거하세요. 몸에 펌프를 부착하세요. 바늘 버튼을 누르세요. + 펌프를 활성화하고 초기 basal 양을 설정함. 기다리세요. + 활성화에 실패함, 재시도를 눌러 다시 시도하세요. + 새 patch가 활성화됨. %.2f U남아있음. + 메인 화면으로 돌아가려면 OK를 누르세요. + 현재 patch를 비활성화하는 것이 맞습니까? + 활성화를 취소하는 것이 맞습니까? + 확실합니까? 이 작업은 되돌릴 수 없습니다!! + 비활성화하기 위해 다음을 누르거나 메인 화면으로 돌아가기 위해 취소를 누르세요. + Patch 비활성화 중. 기다리세요. + 비활성화 실패함, patch를 삭제하려면 폐기를 누르세요. + 바늘을 뒤로 당기기. 몸에서 patch를 제거하세요. + 펌프 베이스를 제거하고 사용한 patch를 적절하게 폐기하세요. + 메인 화면으로 돌아가려면 OK를 누르세요. 새로운 patch의 활성화를 시작하려면 다음을 누르세요. + 이런! 문제 발생, 활성화가 이미 진행 중인 것으로 보입니다. + 활성화를 재시작하려면 다음을 누르거나, 활성화 상태를 재설정하려면 폐기를 누르세요. + 펌프에서 활성화 상태를 읽어오는 중이므로 기다려주세요. + 시리얼 넘버 + 펌프 베이스의 시리얼 넘버를 입력하세요. + 유효하지 않은 시리얼 넘버! + 펌프가 테스트되지 않음: %1$d! 지원을 위해 discord 또는 github으로 연락하세요. + 알람 설정 + 선호하는 펌프 알람 설정을 선택하세요. + Patch 만료 + 활성화되면, patch는 3일 후에 만료되며, 이후 8시간의 유예 기간이 적용됩니다. + 시간당 최대 인슐린 + 시간당 허용되는 인슐린 최대 unit을 정합니다. 이를 초과하면, 펌프는 중지됩니다. + 일일 최대 인슐린 + 하루에 허용되는 인슐린 최대 unit을 정합니다. 이를 초과하면, 펌프는 중지됩니다. + 펌프 상태 가져오기 + Bolus 상태 가져오기 + 임시 basal 상태 가져오기 + 사용자 옵션 설정 diff --git a/pump/medtrum/src/main/res/values-lt-rLT/strings.xml b/pump/medtrum/src/main/res/values-lt-rLT/strings.xml index 1bf4d9f3d7..98952d7733 100644 --- a/pump/medtrum/src/main/res/values-lt-rLT/strings.xml +++ b/pump/medtrum/src/main/res/values-lt-rLT/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Medtrum Nano integracija + Medtrum Nano ir Medtrum 300U integracija Medtrum pompos nustatymai Pompos klaida: %1$s !! Pompa sustabdyta @@ -24,7 +24,7 @@ %.2f v/val. Pompos tipas FW versija - Rezerv. nr. + Rezervuaro nr. Rezerv. gal. baigsis Atnaujinti Atstatyti aliarmus @@ -35,7 +35,7 @@ Nėra Senka pompos baterija Senka rezervuaras - Pompa baigia darbą + Rezervuaras netrukus išsijungs Sustabdyta dėl hipo Sustabdyta dėl hipo 2 Autom. sustabdyta @@ -44,9 +44,9 @@ Sustabdyta Pristabdyta Užsikimšimas - Baigėsi gal. laikas + Išsijungė Rezervuaras tuščias - Rezerv. klaida + Rezervuaro klaida Rezerv. klaida 2 Pagrindo klaida Tuščia baterija @@ -55,8 +55,8 @@ Kartoti Kitas - Baigti naudoti - Aktyvuoti rezervuarą + Išjungti + Įjungti rezervuarą Prijungti ir užpildyti Pildyti Pildoma @@ -64,10 +64,10 @@ Prijungti rezervuarą Aktyvuojama... Aktyvuota - Deaktyvuoti rezervuarą - Deaktyvuojama... - Deaktyvuota - Aktyvuojama + Išjungti rezervuarą + Išjungiama... + Išjungta + Įjungiama Netikėta būsena: %1$s Nepasirinktas profilis. Pasirinkite profilį ir bandykite dar kartą. Pompos pagrindo SN: %1$X @@ -75,8 +75,8 @@ Neprijunkite pagrindo prie rezervuaro iki kito žingsnio! Prijunkite pompos pagrindą prie naujo rezervuaro, pašalinkite orą ir užpildykite insulinu, tada spauskite Kitas. Svarbu: būtina užpildyti bent 70 v. - Kol kas neprijunkite pompos prie kūno. - Pusiau spustelėkite adatos mygtuką. Spauskite Kitas pildymui pradėti. + Kol kas neklijuokite pompos prie kūno. + Spustelėkite adatos mygtuką. Spauskite Kitas pildymui pradėti. Palaukite, kol baigsis pildymas. Pildymas nepavyko, spauskite Kartoti. Norėdami tęsti, spauskite Kitas. @@ -84,18 +84,18 @@ Pašalinkite apsaugą. Priklijuokite pompą prie kūno. Paspauskite adatos mygtuką. Palaukite, kol bus aktyvuota pompa ir nustatyta pradinė bazė. Aktyvavimas nepavyko, spauskite Kartoti. - Naujas rezervuaras aktyvus. Yra %.2f v insulino. + Naujas rezervuaras įjungtas. Yra %.2f v insulino. Norėdanu grįžti į pradžios ekraną, spauskite OK. - Ar tikrai norite deaktyvuoti rezervuarą? - Ar tikrai norite nutraukti aktyvavimą? + Ar tikrai norite išjungti rezervuarą? + Ar tikrai norite nutraukti įjungimą? Ar tikrai norite tęsti? Veiksmo nebus galima atšaukti! - Jei norite deaktyvuoti, spauskite Kitas, jei norite grįžti į pradžios ekaraną, spauskite Atšaukti. - Deaktyvuojama. Palaukite. - Deaktyvuoti nepavyko, spauskite Baigti naudoti. + Jei norite išjungti, spauskite Kitas, jei norite grįžti į pradžios ekaraną, spauskite Atšaukti. + Išjungiama. Palaukite. + Išjungti nepavyko, spauskite Išjungti. Ištraukite adatą. Nuimkite pompą nuo kūno. Nuimkite pompos pagrindą ir tinkamai pašalinkite naudotą rezervuarą. - Norėdami grįžti į pradžios ekraną, spauskite OK. Norėdami aktyvuoti naują rezervuarą, spauskite Kitas. - Ups! Panašu, kad aktyvavimo procesas jau vyksta. + Norėdami grįžti į pradžios ekraną, spauskite OK. Norėdami įjungti naują rezervuarą, spauskite Kitas. + Ups! Panašu, kad įjungimo procesas jau vyksta. Norėdami atnaujinti aktyvavimą, spauskite Kitas, norėdami atšaukti, spauskite Baigti naudoti. Palaukite, nuskaitomas pompos aktyvavimo statusas. @@ -105,8 +105,8 @@ Pompa netestuota: %1$d! Susisiekite su mumis Discord arba Github kanalais Aliarmų nustatymai Pasirinkite pompos aliarmų nustatymus - Rezervuaro galiojimo pabaiga - Įgalinus rezervuaras baigs galioti po 3 parų ir 8 val. + Rezervuaras išsijungs + Įgalinus, rezervuaras išsijungs po 3 parų ir 8 val. Valandos insulino limitas Nustatykite maksimalų insulino kiekį valandai. Jį viršijus pompa bus sustabdyta. Paros insulino limitas diff --git a/pump/medtrum/src/main/res/values-nl-rNL/strings.xml b/pump/medtrum/src/main/res/values-nl-rNL/strings.xml index cfda17eed6..fa7e028eaf 100644 --- a/pump/medtrum/src/main/res/values-nl-rNL/strings.xml +++ b/pump/medtrum/src/main/res/values-nl-rNL/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Pomp integratie voor Medtrum Nano + Pomp integratie voor Medtrum Nano en Medtrum 300U Medtrum pomp instellingen Pomp fout: %1$s!! Pomp is onderbroken diff --git a/pump/medtrum/src/main/res/values-no-rNO/strings.xml b/pump/medtrum/src/main/res/values-no-rNO/strings.xml index 9bbc851cf0..12cf4bd90e 100644 --- a/pump/medtrum/src/main/res/values-no-rNO/strings.xml +++ b/pump/medtrum/src/main/res/values-no-rNO/strings.xml @@ -3,7 +3,6 @@ Medtrum MT - Pumpeintegrasjon for Medtrum Nano Medtrum pumpeinnstillinger Pumpefeil: %1$s!! Pumpen er pauset diff --git a/pump/medtrum/src/main/res/values-pl-rPL/strings.xml b/pump/medtrum/src/main/res/values-pl-rPL/strings.xml index 6a952d13ea..6f07d4ac51 100644 --- a/pump/medtrum/src/main/res/values-pl-rPL/strings.xml +++ b/pump/medtrum/src/main/res/values-pl-rPL/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Integracja z pompą Medtrum Nano + Integracja z pompami Medtrum Nano i Medtrum 300U Ustawienia pompy Medtrum Błąd pompy: %1$s!! Pompa jest wstrzymana diff --git a/pump/medtrum/src/main/res/values-pt-rBR/strings.xml b/pump/medtrum/src/main/res/values-pt-rBR/strings.xml index 573d62ba47..96e009ec22 100644 --- a/pump/medtrum/src/main/res/values-pt-rBR/strings.xml +++ b/pump/medtrum/src/main/res/values-pt-rBR/strings.xml @@ -3,7 +3,6 @@ Medtrum MT - Integração com a bomba para Medtrum Nano Configurações da Bomba Medtrum Erro da Bomba: %1$s !! Bomba suspensa diff --git a/pump/medtrum/src/main/res/values-pt-rPT/strings.xml b/pump/medtrum/src/main/res/values-pt-rPT/strings.xml index b47973319b..0ccd994a3a 100644 --- a/pump/medtrum/src/main/res/values-pt-rPT/strings.xml +++ b/pump/medtrum/src/main/res/values-pt-rPT/strings.xml @@ -1,6 +1,7 @@ + Integração com a bomba Medtrum Nano e Medtrum 300U Bólus ativo diff --git a/pump/medtrum/src/main/res/values-sk-rSK/strings.xml b/pump/medtrum/src/main/res/values-sk-rSK/strings.xml index b2539f9ed9..53c6a82b5d 100644 --- a/pump/medtrum/src/main/res/values-sk-rSK/strings.xml +++ b/pump/medtrum/src/main/res/values-sk-rSK/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Integrácia pumpy Medtrum Nano + Integrácia pumpy Medtrum Nano a Medtrum 300U Nastavenie pumpy Medtrum Chyba pumpy: %1$s!! Pumpa je pozastavená diff --git a/pump/medtrum/src/main/res/values-sv-rSE/strings.xml b/pump/medtrum/src/main/res/values-sv-rSE/strings.xml index 3c4218974d..b15bcb2527 100644 --- a/pump/medtrum/src/main/res/values-sv-rSE/strings.xml +++ b/pump/medtrum/src/main/res/values-sv-rSE/strings.xml @@ -3,7 +3,6 @@ Medtrum MT - Pumpintegration för Medtrum Nano Inställningar för Medtrum-pump Pumpfel: %1$s !! Pumpen är pausad diff --git a/pump/medtrum/src/main/res/values-tr-rTR/strings.xml b/pump/medtrum/src/main/res/values-tr-rTR/strings.xml index dfccf59592..a572d5c0c4 100644 --- a/pump/medtrum/src/main/res/values-tr-rTR/strings.xml +++ b/pump/medtrum/src/main/res/values-tr-rTR/strings.xml @@ -3,7 +3,7 @@ Medtrum MT - Medtrum Nano için pompa entegrasyonu + Medtrum Nano ve Medtrum 300U için pompa entegrasyonu Medtrum pompa ayarları Pompa hatası: %1$s !! Pompa durduruldu diff --git a/pump/omnipod-common/src/main/res/values-el-rGR/strings.xml b/pump/omnipod-common/src/main/res/values-el-rGR/strings.xml index 0082230e2c..838e457321 100644 --- a/pump/omnipod-common/src/main/res/values-el-rGR/strings.xml +++ b/pump/omnipod-common/src/main/res/values-el-rGR/strings.xml @@ -2,14 +2,64 @@ + Διαχείριση Pod Ενέργειες + Εργαλεία + Ενεργοποίηση Pod + Απενεργοποίηση Pod + Απόρριψη Pod + Αν απορρίψετε το Pod, δεν θα μπορείτε πλέον να επικοινωνείτε μαζί του. Θα πρέπει να το κάνετε αυτό μόνο όταν αποτυγχάνει συνεχώς η επικοινωνία με το Pod. Αν μπορείτε ακόμα να επικοινωνήσετε με το Pod, παρακαλούμε χρησιμοποιήστε την επιλογή Απενεργοποίηση Pod.\n\nΑν επιθυμείτε να προχωρήσετε, βεβαιωθείτε ότι αφαιρέσατε το Pod από το σώμα σας! + Δοκιμαστικός ήχος + Αναπαραγωγή Δοκιμαστικού ήχου… + Ιστορικό Pod + Δεν υπάρχει ενεργό Pod + Αποτυχία ρύθμισης βασικού προφίλ. + Η Δόση Bolus δεν πέτυχε. + Απέτυχε ο ορισμός του βασικού προφίλ: Λήφθηκε ένα κενό προφίλ. Βεβαιωθείτε ότι ενεργοποιήσατε το βασικό προφίλ σας. + Δεν υπάρχει ενεργό βασικό προφίλ. Βεβαιωθείτε ότι έχετε ενεργοποιήσει το βασικό σας προφίλ. + Μη υποστηριζόμενη εντολή: %1$s + Απέτυχε η ανανέωση της κατάστασης + Απέτυχε η ανανέωση κατάστασης κατά την εκκίνηση + Απέτυχε η σίγαση ειδοποιήσεων + Απέτυχε η αναστολή εγχυσης + Απέτυχε ο ορισμός ώρας + Απέτυχε η συνέχιση έγχυσης + Αποτυχία αρχικοποίησης του Pod + Αποτυχία εισαγωγής καθετήρα + Υπέρβαση του χρόνου ενεργοποίησης του Pod. Αυτό το Pod δεν μπορεί πλέον να ενεργοποιηθεί. + Αποτυχία επαλήθευσης προόδου ενεργοποίησης. Παρακαλώ προσπαθήστε ξανά. + Αναστολή Pod + Αποτυχία αναπαραγωγής δοκιμαστικού μπιπ + Η ώρα στο Pod δεν είναι συγχρονισμένη. Παρακαλούμε ενημερώστε την ώρα στην καρτέλα Omnipod. + Παρουσιάστηκε μη αναμενόμενο σφάλμα. Παρακαλούμε να το αναφέρετε! (%1$s: %2$s). Επιβεβαίωση + Η ώρα ή/και η ζώνη ώρας άλλαξαν στο Pod. + Οι ρυθμίσεις ειδοποιήσεων έχουν ενημερωθεί στο Pod. + Η ώρα στο Pod έχει ενημερωθεί. + Όλη η χορήγηση ινσουλίνης έχει ανασταλεί. + Οι ενεργές ειδοποιήσεις έχουν μπει σε σίγαση. + Η χορήγηση ινσουλίνης συνεχίζεται. + Ρύθμιση ώρας Αναστολή + Συνέχιση Έγχυσης + Διαχείριση Pod + Σίγαση Ειδοποιήσεων + Κατάσταση Pod + Σύνολο Χορηγήσεων %1$.2f U + Μοναδικό ID + Αριθμός Παρτίδας + Αριθμός Ακολουθίας + Το Pod Λήγει + Τελευταία Σύνδεση + Τελευταίο Bolus + Προσωρινός Βασικός Ρυθμός + Βάση Βασικού Ρυθμού Αμπούλα + Ειδοποιήσεις Ενεργού Pod Σφάλματα Ακύρωση @@ -21,12 +71,42 @@ Άλλο Ειδοποιήσεις + Ρύθμιση σε εξέλιξη (αναμονή για ενεργοποίηση Pod) + Ρύθμιση σε εξέλιξη (αναμονή εισαγωγής καθετήρα) Εκτελείτε + Σε αναστολή + Σφάλμα Pod + Υπέρβαση χρόνου ενεργοποίησης + Ανενεργό + Σφάλμα Pod: %1$03d %2$s + Απενεργοποίηση Pod + Απόρριψη Pod Όρισε bolus Ακύρωση του Bolus Βάλτε Προσωρινό Ρυθμό + Ακύρωση Προσωρινού Βασικού (εσωτερικά από τον οδηγό) + Ακύρωση Προσωρινού Βασικού + Ορισμός Χρονοδιαγράμματος Βασικού + Λήψη Κατάστασης Pod + Λήψη Πληροφοριών Pod + Ορισμός Ώρας + Ρύθμιση Ειδοποιήσεων + Σίγαση Ειδοποιήσεων + Αναστολή Έγχυσης + Συνέχιση Έγχυσης + Άγνωστη Καταχώρηση + Αρχικοποίηση Pod + Εισαγωγή Καθετήρα + Ανάγνωση Αρχείου Καταγραφής Pulse + Ορίστε ψεύτικο προσωρινό βασικό επειδή το Pod είναι σε αναστολή + Ακύρωση ψεύτικου προσωρινού βασικού που δημιουργήθηκε επειδή το Pod ήταν σε αναστολή + Διαίρεση προσωρινού βασικού λόγω αβέβαιης αποτυχίας στην ακύρωση + Ρύθμιση Ήχων + Αναπαραγωγή Δοκιμαστικού Ήχου + Υπενθύμιση ολοκλήρωσης εγκατάστασης + Το Pod θα λήξει σύντομα Ναι diff --git a/pump/omnipod-common/src/main/res/values-es-rES/strings.xml b/pump/omnipod-common/src/main/res/values-es-rES/strings.xml index 38879209a2..06aa635503 100644 --- a/pump/omnipod-common/src/main/res/values-es-rES/strings.xml +++ b/pump/omnipod-common/src/main/res/values-es-rES/strings.xml @@ -104,6 +104,11 @@ Mostrar el botón Suspender Entrega en la pestaña Omnipod Detección de zona horaria activada Recordatorio de expiración activado + Cuando está activado, el POD emite un pitido cuando se alcanza el tiempo especificado + Recordatorio horas antes de la expiración (72 horas) + Alerta de expiración activada + Cuando está activado, el POD emite un pitido cuando se alcanza el tiempo especificado y 1 hora antes de apagarse + Alerta horas antes del apagado (80 horas) Alerta de reservorio bajo habilitada Número de unidades Silenciar automáticamente las alertas de POD diff --git a/pump/omnipod-common/src/main/res/values-fr-rFR/strings.xml b/pump/omnipod-common/src/main/res/values-fr-rFR/strings.xml index a1d05af4b7..5582068512 100644 --- a/pump/omnipod-common/src/main/res/values-fr-rFR/strings.xml +++ b/pump/omnipod-common/src/main/res/values-fr-rFR/strings.xml @@ -104,6 +104,11 @@ Montrer le bouton \"Suspendre\" dans l\'onglet Omnipod Changement d\'heure ou fuseau horaire Activé Rappel d\'expiration activé + Lorsque cette option est activée, le pod sonnera quand le temps spécifié est atteint + Rappel nombre d\'heures avant l\'expiration (72 heures) + Alerte d\'expiration activée + Lorsque cette option est activée, le pod sonnera lorsque le temps spécifié est atteint et 1 heure avant l\'arrêt définitif + Alerte nombre d\'heures avant l\'arrêt (80 heures) Alerte Réservoir bas activée Nombre d\'unités Rendre automatiquement silencieuses les alertes Pod diff --git a/pump/omnipod-common/src/main/res/values-iw-rIL/strings.xml b/pump/omnipod-common/src/main/res/values-iw-rIL/strings.xml index 251eb86a96..18b986ed5e 100644 --- a/pump/omnipod-common/src/main/res/values-iw-rIL/strings.xml +++ b/pump/omnipod-common/src/main/res/values-iw-rIL/strings.xml @@ -104,6 +104,9 @@ הצג לחצן \"השהיית מתן אינסולין\" בלשונית אומניפוד זיהוי אזור זמן ושעון קיץ מופעל תזכורת לתפוגה מופעלת + תזכורת שעות לפני תפוגת תוקף (72 שעות) + תזכורת לתפוגה מופעלת + הזהר שעות לפני כיבוי הפוד (80 שעות) התראת מכל נמוך מופעלת מספר יחידות השתק התראות פוד אוטומטית diff --git a/pump/omnipod-common/src/main/res/values-lt-rLT/strings.xml b/pump/omnipod-common/src/main/res/values-lt-rLT/strings.xml index ad2bfd3144..f70721fedf 100644 --- a/pump/omnipod-common/src/main/res/values-lt-rLT/strings.xml +++ b/pump/omnipod-common/src/main/res/values-lt-rLT/strings.xml @@ -7,8 +7,8 @@ Įrankiai Aktyvuoti Pod Deaktyvuoti Pod - Baigti naudoti Pod - Jei baigsite naudoti Pod, ryšio su juo nebebus galima atkurti. Darykite tai tik tada, kai nebepavyksta užmegzti ryšio. Jei ryšys visgi yra, naudokite Deaktyvuoti Pod funkciją. \n\nJei norite tęsti, pašalinkite Pod nuo savo kūno! + Išjungti Pod + Jei išjungsite Pod, ryšio su juo nebebus galima atkurti. Darykite tai tik tada, kai nebepavyksta užmegzti ryšio. Jei ryšys visgi yra, naudokite Deaktyvuoti Pod funkciją. \n\nJei norite tęsti, pašalinkite Pod nuo savo kūno! Paleisti bandomąjį signalą Bandomasis signalas paleistas… Pod istorija @@ -72,7 +72,7 @@ Kitas Kartoti Deaktyvuoti Pod - Baigti naudoti Pod + Išjungti Pod Jūs dar nebaigėte visų veiksmų. Ar tikrai norite išeiti? Išeiti @@ -92,10 +92,10 @@ Pod deaktyvuojamas.\n\nKai veiksmas bus sėkmingai baigtas, spauskite Kitas. Pod deaktyvuotas Pod deaktyvuotas.\n\nNuimkite Pod nuo kūno ir jį išmeskite. - Pod baigtas naudoti + Pod išjungtas Pod statusas atmestas. Insulino tiekimas nesustabdytas, nes Pod nebuvo teisingai deaktyvuotas. \n\nPašalinkite Pod nuo savo kūno ir jį utilizuokite. - Jei baigsite naudoti Pod, ryšio su juo nebebus galima užmegzti. Darykite tai tik tada, kai užmegzti ryšio nebepavyksta. Ar esate tikri, kad norite baigti naudoti Pod? - Baigti naudoti Pod + Jei išjungsite Pod, ryšio su juo nebebus galima užmegzti. Darykite tai tik tada, kai užmegzti ryšio nebepavyksta. Ar esate tikri, kad norite baigti naudoti Pod? + Išjungti Pod Boluso signalai įjungti Bazės signalai įjungti @@ -131,7 +131,7 @@ Pod klaida: %1$03d %2$s Išjungti Pod - Baigti naudoti Pod + Išjungti Pod Nustatyti bolusą Atšaukti bolusą Nustatyti laikiną bazę diff --git a/pump/omnipod-common/src/main/res/values-nl-rNL/strings.xml b/pump/omnipod-common/src/main/res/values-nl-rNL/strings.xml index c75d70bec3..8502534c17 100644 --- a/pump/omnipod-common/src/main/res/values-nl-rNL/strings.xml +++ b/pump/omnipod-common/src/main/res/values-nl-rNL/strings.xml @@ -104,6 +104,11 @@ Knop voor het onderbreken van insuline toediening weergeven op het Omnipod-tabblad Zomertijd-/tijdzonedetectie ingeschakeld Herinnering vervaldatum ingeschakeld + Wanneer ingeschakeld zal de pod piepen wanneer de opgegeven tijd is bereikt + Herinnering uren voor vervaldatum (72 uur) + Alert vervaldatum ingeschakeld + Wanneer ingeschakeld zal de pod piepen als de opgegeven tijd is bereikt en 1 uur voor uitschakelen + Waarschuwing op uren voor uitschakelen (80 uur) Pieptonen voor \"Reservoir bijna leeg\" ingeschakeld Aantal eenheden Podwaarschuwingen automatisch bevestigen diff --git a/pump/omnipod-common/src/main/res/values-ru-rRU/strings.xml b/pump/omnipod-common/src/main/res/values-ru-rRU/strings.xml index b3a6b95b3b..efa7578782 100644 --- a/pump/omnipod-common/src/main/res/values-ru-rRU/strings.xml +++ b/pump/omnipod-common/src/main/res/values-ru-rRU/strings.xml @@ -104,6 +104,11 @@ Показывать кнопку Приостановить подачу на вкладке Omnipod Включено обнаружение часового пояса Включено напоминание об истечении срока действия + После активации POD издаст звуковой сигнал в определенное время + Напомнить за… часов до окончания срока работы (72 часа) + Включено напоминание об истечении срока работы + После активации POD издаст звуковой сигнал в определенное время и за час до отключения + Оповещение за... часов до выключения (80 часов) Предупреждение о низком уровне в резервуаре включено К-во единиц Автоматически заглушать прочитанные оповещения diff --git a/pump/omnipod-dash/src/main/res/values-el-rGR/strings.xml b/pump/omnipod-dash/src/main/res/values-el-rGR/strings.xml index 7d0dbe22ce..98872f2226 100644 --- a/pump/omnipod-dash/src/main/res/values-el-rGR/strings.xml +++ b/pump/omnipod-dash/src/main/res/values-el-rGR/strings.xml @@ -10,4 +10,8 @@ %1$.2f U + Η ρύθμιση του βασικού προφίλ μπορεί να έχει αποτύχει. Η χορήγηση μπορεί να έχει ανασταλεί! Παρακαλώ ανανεώστε την κατάσταση του Pod χειροκίνητα από την καρτέλα Omnipod και συνεχίστε την χορήγηση αν χρειαστεί. + Αβέβαιη κατάσταση παράδοσης Bolus. Ανανεώστε την κατάσταση του pod για να επιβεβαιώσετε ή αρνηθείτε. + Η κατάσταση του Προσωρινού Ρυθμού δεν είναι όπως αναμενόταν! Αν ο Προσωρινός Ρυθμός εκτελούνταν προηγουμένως, πλέον έχει ακυρωθεί. Παρακαλώ ελέγξτε το ιστορικό χορήγησης ινσουλίνης και του pod + Έλεγχος κατάστασης χορήγησης diff --git a/pump/omnipod-dash/src/main/res/values-ro-rRO/strings.xml b/pump/omnipod-dash/src/main/res/values-ro-rRO/strings.xml index 3b167ac99d..6d29779df8 100644 --- a/pump/omnipod-dash/src/main/res/values-ro-rRO/strings.xml +++ b/pump/omnipod-dash/src/main/res/values-ro-rRO/strings.xml @@ -38,4 +38,15 @@ Nu a rămas suficientă insulină în rezervor Comandă neconfirmată Solicitat de utilizator + Setare profil OK + Suspendarea livrării nu se poate confirma! Verificați manual statusul podului din tab-ul Omnipod și reîncercați livrarea dacă este necesar. + Administrarea insulinei este suspendată + Fusul orar al pod-ului este diferit de fusul orar de pe telefon. Rata bazală este incorectă. Comutați profilul pentru a remedia + Setarea profilului bazalei a eșuat. Livrare suspendată + Setarea profilului bazal s-ar putea să fi eșuat. Livrarea ar putea fi suspendată! Vă rugăm să reîmprospătați manual starea Pod-ului din secțiunea Omnipod și să continuați livrarea dacă este necesar. + Starea livrării bolusului este incertă. Reîncarcă starea pod-ului pentru a confirma sau a refuza. + Verificare stare livrare + Setarea bazalei temporare s-ar putea sa fi eșuat. Dacă o bazală temporară era activă anterior, a fost anulată. Reîmprospătați manual starea Pod-ului din secțiunea Omnipod. + Comanda resumeDelivery neconfirmată. Vă rugăm să reîmprospătați starea pod + Anularea bazalei temporare a eșuat. Dacă o bazală temporară era activă anterior, este posibil să fie de asemenea anulată. Reîmprospătați manual starea Pod-ului din secțiunea Omnipod. diff --git a/pump/pump-common/src/main/res/values-ro-rRO/strings.xml b/pump/pump-common/src/main/res/values-ro-rRO/strings.xml index ddd3e52d73..8c81220c84 100644 --- a/pump/pump-common/src/main/res/values-ro-rRO/strings.xml +++ b/pump/pump-common/src/main/res/values-ro-rRO/strings.xml @@ -5,9 +5,14 @@ Operațiunea nu este ÎNCĂ suportată de către pompă. OK Număr serial pompă + %1$.2f U din %2$.2f U livrate Neiniţializat + Pornit + Criptare comunicație + Ocupat Suspendat + Executare comandă Bazale Configurații @@ -19,8 +24,20 @@ Amorsare Alarme Glicemie + Bază Altul + Toate evenimentele + Evenimente (fără Status) + Astăzi + Ultima Oră + Ultimele 3 ore + Ultimele 6 ore + Ultimele 12 ore + Ultimele 2 zile + Ultimele 4 zile + Săptămâna trecută + Ultima lună Scanare Stop @@ -33,9 +50,15 @@ Bluetooth dezactivat Nu există un adaptor Bluetooth + Pompa configurată nu a fost găsită Pompă indisponibilă + Nu s-a reușit conectarea la dispozitivul BLE + Criptare eșuată + A fost găsită o pompă neîmperecheată Setările de profil/șablon bazale nu sunt activate în pompă. Vă rugăm să le activați din pompă. + Profilul bazal setat în pompă este incorect (trebuie să fie %s). + Tip incorect de RBT setat în pompă (trebuie să fie %s). Bolus maxim setat incorect în pompă (trebuie să fie %1$.2f). Bazala maximă setată incorect în pompă (trebuie să fie %1$.2f). @@ -50,4 +73,9 @@ %1$d ore %1$d ore + + %1$d ore în urmă + %1$d ore în urmă + %1$d ore în urmă + diff --git a/ui/src/main/res/values-el-rGR/strings.xml b/ui/src/main/res/values-el-rGR/strings.xml index cd046147fe..3e282b91d5 100644 --- a/ui/src/main/res/values-el-rGR/strings.xml +++ b/ui/src/main/res/values-el-rGR/strings.xml @@ -54,6 +54,7 @@ 2ώρες Αποτέλεσμα: %1$s %2$s Που υπολείπεται%1$d + τρέχουσα γλυκόζη αίματος Ώρα γεύματος Υπολογ diff --git a/ui/src/main/res/values-ro-rRO/strings.xml b/ui/src/main/res/values-ro-rRO/strings.xml index d2af65c39d..6f34d4a5bf 100644 --- a/ui/src/main/res/values-ro-rRO/strings.xml +++ b/ui/src/main/res/values-ro-rRO/strings.xml @@ -103,4 +103,7 @@ STOP APĂSAT + Calculul procentajului + Implicit pentru aplicație + mâner de glisare și plasare diff --git a/wear/src/main/res/values-cs-rCZ/strings.xml b/wear/src/main/res/values-cs-rCZ/strings.xml index ef9a6e7e33..2fd291f06d 100644 --- a/wear/src/main/res/values-cs-rCZ/strings.xml +++ b/wear/src/main/res/values-cs-rCZ/strings.xml @@ -24,6 +24,11 @@ Vibrovat při bolusu Jednotky pro akce U + Displej + Graf + Rozhraní + Ostatní + Komplikace Zobrazit datum Zobrazit IOB Zobrazit detailní IOB @@ -41,6 +46,7 @@ Zobrazit aktualizováno před Tmavý Zvýraznit bazály + Zobrazit predikce Odpovídající oddělovač Časové okno grafu 1 hodina diff --git a/wear/src/main/res/values-el-rGR/strings.xml b/wear/src/main/res/values-el-rGR/strings.xml index 5d1988c394..e65d2b1468 100644 --- a/wear/src/main/res/values-el-rGR/strings.xml +++ b/wear/src/main/res/values-el-rGR/strings.xml @@ -3,31 +3,89 @@ AAPS AAPS AAPS + AAPS(μεγάλο) + AAPS(μεγαλο_γράφημα) + AAPS(χωρίς_γράφημα) + AAPS(Κυκλικό) + AAPS(v2) + AAPS(Πιλοτήριο) + AAPS(Steampunk) + AAPS(ψηφιακό) + AAPS(προσαρμοσμένα_χαρακτηριστικά) + AAPS( Ενέργειες) + AAPS(προσωρινός_στόχος) + AAPS(Quick Wizard) + Δεν υπάρχουν δεδομένα! + Παλιά δεδομένα! + Από %1$s + Συγχρονισμός με AAPS! + Δεν ελήφθησαν δεδομένα από τις %1$s! Ελέγξτε αν το AAPS στο τηλέφωνο στέλνει δεδομένα στο ρολόι + Τα δεδομένα AAPS είναι %1$s παλιά! Ελέγξτε τον αισθητήρα, το xDrip +, το NS, το AAPS ή άλλα! + Δόνηση στην Δόση Bolus + Μονάδες για Ενέργειες + U + Εμφάνιση ημερομηνίας + Εμφάνιση IOB + Εμφάνιση λεπτομερούς IOB + Εμφάνιση COB + Εμφάνιση Delta + Εμφάνιση λεπτομερούς Delta + Εμφάνιση AvgDelta + Εμφάνιση ποσοστού μπαταρίας Τηλεφώνου + Εμφάνιση Μπαταρίας + Εμφάνιση Βασικού Ρυθμού + Εμφάνιση Κατάστασης Βρόχου + Εμφάνιση γλυκόζης αίματος + Εμφάνιση BGI + Εμφάνιση Βέλους Κατεύθυνσης + Εμφάνιση Πριν + Σκούρο + Επισήμανση Βασικών + Εμφάνιση προβλέψεων + Ταίριασμα διαχωριστικού + Χρόνος Διαγράμματος 1 ώρα 2 ώρες 3 ώρες 4 ώρες 5 ώρες + Σχεδιασμός Εισαγωγής + Προεπιλογή Χαμηλή Υψηλό Αυτόματο + Μεγάλοι Αριθμοί + Εφέ Κίνησης + Μεμονωμένος Στόχος Έκδοση: + Προσωρινός Στόχος Υπολογιστής Υπολογ Θεραπεία + Αντιμετώπιση-Θεραπεία Bolus Υδατάνθρακες eCarbs Ρυθμίσεις Κατάσταση + Επανασυγχρονισμός Πλήρωση/Γέμισμα + Καμία + Προεπιλογή + Μενού + XL Διάρκεια + Ζητήθηκε Προσωρινός Στόχος + Ζητήθηκε Θεραπεία + Αιτούνται Υδατάνθρακες + Ζητήθηκε Αλλαγή Προφίλ Στόχος Χαμηλό Υψηλό Υδατάνθρακες eCarbs Ποσοστό + Έναρξη [min] Διάρκεια [h] Ινσουλίνη αλλαγή ώρας diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index 52fe48fc52..b97d390a17 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -24,6 +24,11 @@ Vibrar en bolos Unidades para Acciones U + Pantalla + Gráfico + Interfaz + Otros + Complicaciones Mostrar fecha Mostrar Insulina activa (IOB) Mostrar IOB detallada @@ -41,6 +46,7 @@ Mostrar histórico Tema oscuro Resaltar las basales + Mostrar predicciones Divisor de coincidencia Gráfico por franja de tiempo 1 hora diff --git a/wear/src/main/res/values-fr-rFR/strings.xml b/wear/src/main/res/values-fr-rFR/strings.xml index 562ff431ef..080c8e4d1f 100644 --- a/wear/src/main/res/values-fr-rFR/strings.xml +++ b/wear/src/main/res/values-fr-rFR/strings.xml @@ -24,6 +24,11 @@ Vibrer sur Bolus Unités pour les Actions U + Affichage + Graphique + Interface + Autres + Complication Afficher Date Afficher IA Afficher IA détaillée @@ -41,6 +46,7 @@ Afficher Min Passées Sombre Surbrillance Basale + Afficher prévisions Séparateur Invisible Echelle Graphique 1 heure diff --git a/wear/src/main/res/values-iw-rIL/strings.xml b/wear/src/main/res/values-iw-rIL/strings.xml index 8a19ff3598..bc4359285f 100644 --- a/wear/src/main/res/values-iw-rIL/strings.xml +++ b/wear/src/main/res/values-iw-rIL/strings.xml @@ -22,6 +22,11 @@ נתוני AAPS מלפני %1$s! בדקו את החיישן, הגדרות xDrip, NS, AAPS או אחר! רטט במתן בולוס יחידות עבור פעולות + תצוגה + גרף + ממשק + אחרים + סיבוכים הצג תאריך הצג אינסולין IOB הצג COB @@ -36,6 +41,7 @@ הצג עבר כהה הדגש בזאלים + הצג תחזיות מחיצות מותאמות מסגרת זמן התרשים שעה diff --git a/wear/src/main/res/values-ko-rKR/strings.xml b/wear/src/main/res/values-ko-rKR/strings.xml index cb0c67e531..e0268f71a5 100644 --- a/wear/src/main/res/values-ko-rKR/strings.xml +++ b/wear/src/main/res/values-ko-rKR/strings.xml @@ -7,9 +7,14 @@ AAPS(큰차트) AAPS(차트없음) AAPS(원형) + AAPS(v2) AAPS(조종석) AAPS(스팀펑크) AAPS(디지털방식) + AAPS(Custom) + AAPS(Actions) + AAPS(Temp Target) + AAPS(Quick Wizard) 데이터없음! 오래된 데이터! %1$s 이후 @@ -18,16 +23,20 @@ AAPS 데이터가 %1$s 오래되었습니다! 센서, xDrip+, NS, AAPS 설정 또는 기타사항을 확인하세요! Bolus 주입시 진동 단위 + U 날짜 표시 IOB 표시 + IOB 자세히 표시하기 COB 표시 증분 표시 + Delta 자세히 표시하기 평균증분 표시 폰배터리 표시 종합 배터리 표시 Basal 값 표시 Loog 상태 표시 혈당 표시 + BGI 표시하기 화살표 표시 \'분전\' 표시 어두움 @@ -53,8 +62,10 @@ 원형 이력 연한 원형 이력 애니메이션 + 메뉴의 계산기 메뉴에서 교체 단일 목표 + 계산기의 퍼센트 컴플리케이션 탭 동작 컴플리케이션에서 유니코드 사용 버전: @@ -64,8 +75,10 @@ 계산기 Calc 관리 + 처치 Bolus 탄수화물 + eCarbs 설정 상태 재동기화 @@ -73,11 +86,21 @@ 없음 기본 메뉴 + XL 기간 + 임시 목표 요청됨 + Quick Wizard 요청됨 + 처치 요청됨 + Bolus 요청됨 + 계산기 요청됨 + 채우기 요청됨 + 탄수화물 요청됨 + 프로파일 변경 요청됨 목표: 저혈당 고혈당 탄수화물 + eCarbs 퍼센트 시작 [min] 기간 [h] @@ -121,8 +144,11 @@ 흰색 검정 다양한 색상 + UI 단순화 + 시간과 BG만 보여주기 시간마다 진동 몇 번째 주인지 표시 + 초 표시하기 사용자 형식: 형식 없음 단순한 형태 @@ -136,10 +162,44 @@ Bolus 진행과 취소 Bolus 주입과 취소 시 진동 적게 함 꺼짐 + 충전 중 + Always On 모드 + Always On과 충전 중 + 식사 저혈당 활동 수동 취소 없음 + 가능한 환경설정 없음 + Wear 조작 불가능함 + 사용할 수 있는 데이터 없음 + 증가 + 감소 + H + L + 평균 --U + --g + -.--U/h + U: --% + S: -- + -- 분전 + --- mg/dl + Loop 상태 없음 + 000g + 00,0 + 0,00U + AAPS Snooze 경고 + AAPS에 snooze 보내기 + h + w + d + h + %1$s:%2$s + %1$s:%2$s:%3$s + old + !old! + !err! + 심박수 diff --git a/wear/src/main/res/values-lt-rLT/strings.xml b/wear/src/main/res/values-lt-rLT/strings.xml index 1701c952ad..54727ea9ae 100644 --- a/wear/src/main/res/values-lt-rLT/strings.xml +++ b/wear/src/main/res/values-lt-rLT/strings.xml @@ -24,6 +24,11 @@ Vibruoti, kai leidžiamas bolusas Veiksmų vienetai v + Ekranas + Grafikas + Sąsaja + Kiti + Ekrano elementas Rodyti datą Rodyti AIO Rodyti detalų AIO @@ -41,6 +46,7 @@ Laikas nuo pask. vertės Tamsus Paryškinti valandines bazes + Rodyti prognozes Vienodos spalvos skirtukas Diagramos laikotarpis 1 val. diff --git a/wear/src/main/res/values-nl-rNL/strings.xml b/wear/src/main/res/values-nl-rNL/strings.xml index 5b2baef589..7a87ccc1f8 100644 --- a/wear/src/main/res/values-nl-rNL/strings.xml +++ b/wear/src/main/res/values-nl-rNL/strings.xml @@ -24,6 +24,11 @@ Trillen bij bolus Eenheden voor acties E + Scherm + Grafiek + Interface + Overige + Complicatie Toon datum Toon IOB Toon gedetailleerde IOB @@ -41,6 +46,7 @@ Toon tijd geleden Donker Markeer basaalstanden + Voorspellingen tonen Bijpassende verdeler Tijdsschaal grafiek 1 uur diff --git a/wear/src/main/res/values-no-rNO/strings.xml b/wear/src/main/res/values-no-rNO/strings.xml index 1360190146..4680f70739 100644 --- a/wear/src/main/res/values-no-rNO/strings.xml +++ b/wear/src/main/res/values-no-rNO/strings.xml @@ -24,6 +24,11 @@ Vibrer ved bolus Enheter for handlinger E + Skjerm + Graf + Grensesnitt + Annet + Urskive Vis dato Vis IOB Vis detaljert IOB @@ -41,6 +46,7 @@ Vis siden Mørkt Marker basaler + Vis prognoser Matchende avdeler Tidsspenn for diagram 1 time diff --git a/wear/src/main/res/values-pl-rPL/strings.xml b/wear/src/main/res/values-pl-rPL/strings.xml index 0109dc36c9..e4382dd45c 100644 --- a/wear/src/main/res/values-pl-rPL/strings.xml +++ b/wear/src/main/res/values-pl-rPL/strings.xml @@ -24,6 +24,11 @@ Wibruj przy Bolusie Jednostki dla akcji U + Wyświetlanie + Wykres + Interfejs + Inne + Komplikacje Pokaż Datę Pokaż IOB Pokaż szczegółowe IOB @@ -41,6 +46,7 @@ Pokaż aktualność Tryb ciemny Podświetl Bazę + Pokazuj predykcje Separator pod kolor Ramy czasowe wykresu 1 godzina diff --git a/wear/src/main/res/values-pt-rPT/strings.xml b/wear/src/main/res/values-pt-rPT/strings.xml index c874ad0cd6..469c1dc139 100644 --- a/wear/src/main/res/values-pt-rPT/strings.xml +++ b/wear/src/main/res/values-pt-rPT/strings.xml @@ -24,6 +24,11 @@ Vibrar no Bólus Unidades para Acções U + Ecrã + Gráfico + Interface + Outros + Complicação Mostrar Data Mostrar IA Mostrar IA detalhada diff --git a/wear/src/main/res/values-ro-rRO/strings.xml b/wear/src/main/res/values-ro-rRO/strings.xml index 7494b1ca6c..96d2051776 100644 --- a/wear/src/main/res/values-ro-rRO/strings.xml +++ b/wear/src/main/res/values-ro-rRO/strings.xml @@ -7,6 +7,7 @@ AAPS(GraficMare) AAPS(FărăGrafic) AAPS(Cerc) + AAPS(v2) AAPS(Panou) AAPS (Steampunk) AAPS (DigitalStyle) @@ -59,6 +60,7 @@ Calculator în meniu Amorsare în meniu Țintă unică + Calculator Procentaj Acţiuni pentru complicaţii Unicode în complicații Versiune: @@ -68,6 +70,7 @@ Calculator Calc Tratament + Tratare Bolus Carbohidrați eCarbs @@ -78,11 +81,16 @@ Nimic Implicit Meniu + XL Durată + Țintă temporară solicitată + Asistent rapid solicitat Tratament solicitat Bolus solicitat Calcul solicitat Completare solicitată + Carbohidrați solicitați + Schimbare profil solicitată Țintă Scăzut Mare @@ -151,6 +159,7 @@ În timpul încărcării Modul mereu activ Mereu activ şi încărcare + Mănânc Hipo Exercițiu fizic Manual @@ -159,5 +168,29 @@ Nici o configurație disponibilă Comenzi Wear dezactivate Nu există date disponibile + creștere + scădere + H + L + med. --U + --g + -.--U/o + U: --% + S: -- + -- Min în urmă + --- mg/dl + Fără stare buclă + 000g + 00,0 + 0,00U + Amânare alertă AAPS + Se transmite amânarea alertei către AAPS + o + săpt + z + h + vechi + !vechi! + !eroare! diff --git a/wear/src/main/res/values-ru-rRU/strings.xml b/wear/src/main/res/values-ru-rRU/strings.xml index 9414b826d7..f27ada1b69 100644 --- a/wear/src/main/res/values-ru-rRU/strings.xml +++ b/wear/src/main/res/values-ru-rRU/strings.xml @@ -11,6 +11,7 @@ AAPS (кабина пилота) AAPS (Стимпанк) AAPS (ЦифровойСтиль) + AAPS (настраиваемый) AAPS (Действия) AAPS(ВремЦель) AAPS(Мастер) @@ -36,6 +37,7 @@ Показывать ретро события Тёмная Выделить базалы + Показывать прогноз Соответствующий делитель Временной диапазон графика 1 час @@ -143,6 +145,7 @@ Показывать только время и ГК Почасовая вибрация Показывать номер недели + Показывать секунды Ваш стиль: без стиля минималистский @@ -190,6 +193,8 @@ н д ч + %1$s%2$s + %1$s%2$s%3$s старые !старое! !ошибка! diff --git a/wear/src/main/res/values-sk-rSK/strings.xml b/wear/src/main/res/values-sk-rSK/strings.xml index 568113e127..d4bfc99adb 100644 --- a/wear/src/main/res/values-sk-rSK/strings.xml +++ b/wear/src/main/res/values-sk-rSK/strings.xml @@ -41,6 +41,7 @@ Zobraziť aktualizované pred Tmavý Zvýrazniť bazály + Zobraziť predikcie Zodpovedajúci oddeľovač Časové okno grafu 1 hodina diff --git a/wear/src/main/res/values-tr-rTR/strings.xml b/wear/src/main/res/values-tr-rTR/strings.xml index 5c68d705fe..261d6d2985 100644 --- a/wear/src/main/res/values-tr-rTR/strings.xml +++ b/wear/src/main/res/values-tr-rTR/strings.xml @@ -24,6 +24,11 @@ Bolus\'ta Titreşim Eylemler için Birimler Ü + Ekran + Grafik + Arayüz + Diğer + Komplikasyon Tarihi Göster IOB\'yi göster Ayrıntılı AİNS göster @@ -41,6 +46,7 @@ Önce Göster Koyu Bazalları Vurgula + Tahminleri göster Eşleşen bölücü Grafik Zaman Çerçevesi 1 saat