From 42c2d89f987c8819c369940fad89d15568ade9db Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 6 Feb 2020 21:24:19 +0100 Subject: [PATCH 001/100] ask for overlay permission on android 10 only --- .../androidaps/utils/AndroidPermission.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java index d884552ac4..41e26e8e3b 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java @@ -133,20 +133,20 @@ public class AndroidPermission { } public static synchronized void notifyForSystemWindowPermissions(Activity activity) { - if (!Settings.canDrawOverlays(activity)) { - NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_SYSTEM_WINDOW, MainApp.gs(R.string.needsystemwindowpermission), Notification.URGENT); - notification.action(R.string.request, () -> { - // Check if Android Q or higher - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { - // Show alert dialog to the user saying a separate permission is needed - // Launch the settings activity if the user prefers - Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, - Uri.parse("package:" + activity.getPackageName())); - activity.startActivity(intent); - } - }); - RxBus.INSTANCE.send(new EventNewNotification(notification)); - } else - RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_SYSTEM_WINDOW)); + // Check if Android Q or higher + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { + if (!Settings.canDrawOverlays(activity)) { + NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_SYSTEM_WINDOW, MainApp.gs(R.string.needsystemwindowpermission), Notification.URGENT); + notification.action(R.string.request, () -> { + // Show alert dialog to the user saying a separate permission is needed + // Launch the settings activity if the user prefers + Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, + Uri.parse("package:" + activity.getPackageName())); + activity.startActivity(intent); + }); + RxBus.INSTANCE.send(new EventNewNotification(notification)); + } else + RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_SYSTEM_WINDOW)); + } } } From 9098eb2da0661a6dc3e01341aa47884b208b9356 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 9 Feb 2020 13:04:49 +0100 Subject: [PATCH 002/100] save Careportal events directly to DB --- .../plugins/pump/insight/LocalInsightPlugin.java | 12 ++++++++++++ .../pump/medtronic/data/MedtronicHistoryData.java | 6 ++++++ .../plugins/source/SourceDexcomPlugin.kt | 15 +++++++++++++++ .../plugins/source/SourceEversensePlugin.java | 7 +++++++ 4 files changed, 40 insertions(+) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 5104e70fe8..afca125092 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -1524,6 +1524,12 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", CareportalEvent.NOTE); data.put("notes", note); + CareportalEvent careportalEvent = new CareportalEvent(); + careportalEvent.date = date; + careportalEvent.source = Source.USER; + careportalEvent.eventType = CareportalEvent.NOTE; + careportalEvent.json = data.toString(); + MainApp.getDbHelper().createOrUpdate(careportalEvent); NSUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { log.error("Unhandled exception", e); @@ -1552,6 +1558,12 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", event); + CareportalEvent careportalEvent = new CareportalEvent(); + careportalEvent.date = date; + careportalEvent.source = Source.USER; + careportalEvent.eventType = event; + careportalEvent.json = data.toString(); + MainApp.getDbHelper().createOrUpdate(careportalEvent); NSUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { log.error("Unhandled exception", e); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index 11d1bad3d9..39c44167a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java @@ -528,6 +528,12 @@ public class MedtronicHistoryData { if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", event); + CareportalEvent careportalEvent = new CareportalEvent(); + careportalEvent.date = date; + careportalEvent.source = Source.USER; + careportalEvent.eventType = event; + careportalEvent.json = data.toString(); + MainApp.getDbHelper().createOrUpdate(careportalEvent); NSUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { LOG.error("Unhandled exception", e); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt index 633f16cf10..bf5661ad00 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt @@ -9,6 +9,8 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.RequestDexcomPermissionActivity import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.db.CareportalEvent +import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.dialogs.CareDialog import info.nightscout.androidaps.interfaces.BgSourceInterface import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription @@ -96,6 +98,13 @@ object SourceDexcomPlugin : PluginBase(PluginDescription() jsonObject.put("glucoseType", "Finger") jsonObject.put("glucose", meter.getInt("meterValue")) jsonObject.put("units", Constants.MGDL) + + val careportalEvent = CareportalEvent() + careportalEvent.date = timestamp + careportalEvent.source = Source.USER + careportalEvent.eventType = CareportalEvent.BGCHECK + careportalEvent.json = jsonObject.toString() + MainApp.getDbHelper().createOrUpdate(careportalEvent) NSUpload.uploadCareportalEntryToNS(jsonObject) } } @@ -110,6 +119,12 @@ object SourceDexcomPlugin : PluginBase(PluginDescription() jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType") jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime)) jsonObject.put("eventType", CareportalEvent.SENSORCHANGE) + val careportalEvent = CareportalEvent() + careportalEvent.date = sensorInsertionTime + careportalEvent.source = Source.USER + careportalEvent.eventType = CareportalEvent.SENSORCHANGE + careportalEvent.json = jsonObject.toString() + MainApp.getDbHelper().createOrUpdate(careportalEvent) NSUpload.uploadCareportalEntryToNS(jsonObject) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceEversensePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceEversensePlugin.java index 6f39e3d762..6d0067414a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceEversensePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceEversensePlugin.java @@ -15,6 +15,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -143,6 +144,12 @@ public class SourceEversensePlugin extends PluginBase implements BgSourceInterfa data.put("glucoseType", "Finger"); data.put("glucose", calibrationGlucoseLevels[i]); data.put("units", Constants.MGDL); + CareportalEvent careportalEvent = new CareportalEvent(); + careportalEvent.date = calibrationTimestamps[i]; + careportalEvent.source = Source.USER; + careportalEvent.eventType = CareportalEvent.BGCHECK; + careportalEvent.json = data.toString(); + MainApp.getDbHelper().createOrUpdate(careportalEvent); NSUpload.uploadCareportalEntryToNS(data); } } catch (JSONException e) { From f111b731e75a86edafd2ddb8424a01b718691ab8 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 9 Feb 2020 22:16:48 +0100 Subject: [PATCH 003/100] Improve SetupWizardTest to be runnable on real device --- app/build.gradle | 1 + .../nightscout/androidaps/EspressoHelper.kt | 8 +++ .../androidaps/SetupWizardActivityTest.kt | 61 +++++++++++-------- 3 files changed, 44 insertions(+), 26 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 53b0398a43..69ae9369cb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -315,6 +315,7 @@ dependencies { androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test:rules:1.3.0-alpha03' androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.2' + androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' } diff --git a/app/src/androidTest/java/info/nightscout/androidaps/EspressoHelper.kt b/app/src/androidTest/java/info/nightscout/androidaps/EspressoHelper.kt index b50bb746fb..cf7118ebd2 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/EspressoHelper.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/EspressoHelper.kt @@ -4,6 +4,9 @@ import androidx.test.espresso.ViewAction import androidx.test.espresso.ViewInteraction import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.uiautomator.UiDevice +import androidx.test.uiautomator.UiSelector fun ViewInteraction.isDisplayed(): Boolean { try { @@ -25,3 +28,8 @@ fun ViewInteraction.waitAndPerform(viewActions: ViewAction): ViewInteraction? { return perform(viewActions) } +fun clickOkInDialog() { + val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) + val button = uiDevice.findObject(UiSelector().clickable(true).checkable(false).index(1)) + if (button.exists() && button.isEnabled) button.click() +} diff --git a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt index dd1c0b12bc..a2742c2a34 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps - import android.os.SystemClock import android.view.View import android.view.ViewGroup @@ -9,12 +8,15 @@ import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.scrollTo -import androidx.test.espresso.matcher.ViewMatchers.* +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import androidx.test.espresso.matcher.ViewMatchers.withClassName +import androidx.test.espresso.matcher.ViewMatchers.withId +import androidx.test.espresso.matcher.ViewMatchers.withTagValue +import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.rule.ActivityTestRule import androidx.test.rule.GrantPermissionRule -import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin @@ -39,7 +41,6 @@ import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith - @LargeTest @RunWith(AndroidJUnit4::class) class SetupWizardActivityTest { @@ -50,12 +51,12 @@ class SetupWizardActivityTest { @Rule @JvmField - var mGrantPermissionRule = - GrantPermissionRule.grant( - android.Manifest.permission.ACCESS_FINE_LOCATION, - android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, - android.Manifest.permission.WRITE_EXTERNAL_STORAGE - ) + var mGrantPermissionRule: GrantPermissionRule = + GrantPermissionRule.grant( + android.Manifest.permission.ACCESS_FINE_LOCATION, + android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, + android.Manifest.permission.WRITE_EXTERNAL_STORAGE + ) @Before fun clear() { @@ -74,9 +75,9 @@ adb shell settings put global transition_animation_scale 0 & adb shell settings put global animator_duration_scale 0 & */ - @Test fun setupWizardActivityTest() { + SP.clear() Assert.assertTrue(isRunningTest()) // Welcome page onView(withId(R.id.next_button)).perform(click()) @@ -86,7 +87,7 @@ adb shell settings put global animator_duration_scale 0 & // Agreement page onView(withText("I UNDERSTAND AND AGREE")).perform(scrollTo(), click()) onView(withId(R.id.next_button)).waitAndPerform(click()) - // Loction permission + // Location permission var askButton = onView(withText("Ask for permission")) if (askButton.isDisplayed()) { askButton.perform(scrollTo(), click()) @@ -99,6 +100,11 @@ adb shell settings put global animator_duration_scale 0 & onView(withText("OK")).perform(click()) onView(withId(R.id.next_button)).waitAndPerform(click()) } + // Import settings : skip of found + askButton = onView(withText("IMPORT SETTINGS")) + if (askButton.isDisplayed()) { + onView(withId(R.id.next_button)).waitAndPerform(click()) + } // Units selection onView(withText("mmol/L")).perform(scrollTo(), click()) onView(withId(R.id.next_button)).perform(click()) @@ -125,41 +131,44 @@ adb shell settings put global animator_duration_scale 0 & // Local profile - IC onView(withId(R.id.ic_tab)).perform(scrollTo(), click()) onView(Matchers.allOf(withTagValue(Matchers.`is`("IC-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("2"), ViewActions.closeSoftKeyboard()) + .perform(ViewActions.replaceText("2"), ViewActions.closeSoftKeyboard()) // Local profile - ISF onView(withId(R.id.isf_tab)).perform(scrollTo(), click()) onView(Matchers.allOf(withTagValue(Matchers.`is`("ISF-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("3"), ViewActions.closeSoftKeyboard()) + .perform(ViewActions.replaceText("3"), ViewActions.closeSoftKeyboard()) // Local profile - BAS onView(withId(R.id.basal_tab)).perform(scrollTo(), click()) onView(childAtPosition(Matchers.allOf(withId(R.id.localprofile_basal), childAtPosition(withClassName(Matchers.`is`("android.widget.LinearLayout")), 6)), 2)) - .perform(scrollTo(), click()) + .perform(scrollTo(), click()) onView(Matchers.allOf(withTagValue(Matchers.`is`("BASAL-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("1.1"), ViewActions.closeSoftKeyboard()) + .perform(ViewActions.replaceText("1.1"), ViewActions.closeSoftKeyboard()) onView(Matchers.allOf(withTagValue(Matchers.`is`("BASAL-1-1")), isDisplayed())) - .perform(ViewActions.replaceText("1.2"), ViewActions.closeSoftKeyboard()) + .perform(ViewActions.replaceText("1.2"), ViewActions.closeSoftKeyboard()) onView(Matchers.allOf(withId(R.id.timelistedit_time), childAtPosition(childAtPosition(withId(R.id.localprofile_basal), 2), 0))) - .perform(scrollTo(), click()) + .perform(scrollTo(), click()) onData(Matchers.anything()).inAdapterView(childAtPosition(withClassName(Matchers.`is`("android.widget.PopupWindow\$PopupBackgroundView")), 0)).atPosition(13) - .perform(click()) + .perform(click()) // Local profile - TARGET onView(withId(R.id.target_tab)).perform(scrollTo(), click()) onView(Matchers.allOf(withTagValue(Matchers.`is`("TARGET-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("6"), ViewActions.closeSoftKeyboard()) + .perform(ViewActions.replaceText("6"), ViewActions.closeSoftKeyboard()) onView(Matchers.allOf(withTagValue(Matchers.`is`("TARGET-2-0")), isDisplayed())) - .perform(ViewActions.replaceText("6.5"), ViewActions.closeSoftKeyboard()) + .perform(ViewActions.replaceText("6.5"), ViewActions.closeSoftKeyboard()) onView(withText("Save")).perform(scrollTo(), click()) onView(Matchers.allOf(withId(R.id.localprofile_profileswitch), isDisplayed())) - .perform(scrollTo(), click()) + .perform(scrollTo(), click()) onView(allOf(withId(R.id.ok), isDisplayed())).perform(click()) - onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) + // confirm dialog + //onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) not working on real phone + clickOkInDialog() onView(withId(R.id.next_button)).waitAndPerform(click()) // Profile switch askButton = onView(withText("Do Profile Switch")) if (askButton.isDisplayed()) { askButton.perform(scrollTo(), click()) onView(allOf(withId(R.id.ok), isDisplayed())).perform(click()) - onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) + // onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) not working on real phone + clickOkInDialog() while (ProfileFunctions.getInstance().profile == null) SystemClock.sleep(100) onView(withId(R.id.next_button)).waitAndPerform(click()) } @@ -204,7 +213,7 @@ adb shell settings put global animator_duration_scale 0 & } private fun childAtPosition( - parentMatcher: Matcher, position: Int): Matcher { + parentMatcher: Matcher, position: Int): Matcher { return object : TypeSafeMatcher() { override fun describeTo(description: Description) { @@ -215,7 +224,7 @@ adb shell settings put global animator_duration_scale 0 & public override fun matchesSafely(view: View): Boolean { val parent = view.parent return parent is ViewGroup && parentMatcher.matches(parent) - && view == parent.getChildAt(position) + && view == parent.getChildAt(position) } } } From 0ff7702b1a29fa6016e3b3e9011094fc17e9b396 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 11 Feb 2020 17:06:30 +0100 Subject: [PATCH 004/100] RealPumpTest| --- app/build.gradle | 30 +++++ .../nightscout/androidaps/RealPumpTest.kt | 116 ++++++++++++++++++ .../nightscout/androidaps/MainActivity.java | 4 +- .../androidaps/interfaces/PluginBase.java | 2 +- .../plugins/source/RandomBgPlugin.kt | 6 +- .../androidaps/utils/EspressoTestHelper.kt | 10 ++ 6 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt diff --git a/app/build.gradle b/app/build.gradle index 69ae9369cb..7d622ed56f 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -343,6 +343,36 @@ task full_clean(type: Delete) { delete file("src/main/jniLibs") } +// Run 'adb' shell command to clear application data of main app for 'debug' variant +task clearMainAppData(type: Exec) { + // we have to iterate to find the 'debug' variant to obtain a variant reference + android.applicationVariants.all { variant -> + if (variant.name == "fullDebug") { + def applicationId = [variant.mergedFlavor.applicationId, variant.buildType.applicationIdSuffix].findAll().join() + def clearDataCommand = ['adb', 'shell', 'pm', 'clear', applicationId] + println "Clearing application data of ${variant.name} variant: [${clearDataCommand}]" + def stdout = new ByteArrayOutputStream() + exec { + commandLine clearDataCommand + standardOutput = stdout + } + String result = stdout.toString().trim() + if (!result.startsWith("Success")) { + println result + throw new GradleException(clearDataCommand.join(" ")) + } + } + } +} +// Clear Application Data (once) before running instrumentation test +tasks.whenTaskAdded { task -> + // Both of these targets are equivalent today, although in future connectedCheck + // will also include connectedUiAutomatorTest (not implemented yet) + if(task.name == "connectedAndroidTest" || task.name == "connectedCheck"){ + task.dependsOn(clearMainAppData) + } +} + clean.dependsOn full_clean preBuild.dependsOn copyLibs diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt new file mode 100644 index 0000000000..5463fbcd26 --- /dev/null +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -0,0 +1,116 @@ +package info.nightscout.androidaps + +import android.os.SystemClock +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.LargeTest +import androidx.test.rule.ActivityTestRule +import androidx.test.rule.GrantPermissionRule +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.PumpInterface +import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin +import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin +import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin +import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin +import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin +import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin +import info.nightscout.androidaps.plugins.source.RandomBgPlugin +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.SP +import info.nightscout.androidaps.utils.isRunningTest +import org.json.JSONObject +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.slf4j.LoggerFactory + +@LargeTest +@RunWith(AndroidJUnit4::class) +class RealPumpTest { + + private val log = LoggerFactory.getLogger(L.CORE) + + companion object { + val pump: PumpInterface = DanaRv2Plugin.getPlugin() + const val R_PASSWORD = 1234 + const val R_SERIAL = "PBB00013LR_P" + } + + private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + + @Rule + @JvmField + var mActivityTestRule = ActivityTestRule(MainActivity::class.java) + + @Rule + @JvmField + var mGrantPermissionRule: GrantPermissionRule = + GrantPermissionRule.grant( + android.Manifest.permission.ACCESS_FINE_LOCATION, + android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, + android.Manifest.permission.WRITE_EXTERNAL_STORAGE + ) + + @Before + fun clear() { + SP.clear() + SP.putBoolean(R.string.key_setupwizard_processed, true) + SP.putString(R.string.key_aps_mode, "closed") + MainApp.getDbHelper().resetDatabases() + MainApp.devBranch = false + } + + private fun preparePlugins() { + // Source + RandomBgPlugin.performPluginSwitch(true, PluginType.BGSOURCE) + // Profile + LocalProfilePlugin.performPluginSwitch(true, PluginType.PROFILE) + val profile = Profile(JSONObject(validProfile), Constants.MGDL) + Assert.assertTrue(profile.isValid("Test")) + LocalProfilePlugin.profiles.clear() + LocalProfilePlugin.numOfProfiles = 0 + val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(profile, "TestProfile") + LocalProfilePlugin.addProfile(singleProfile) + ProfileFunctions.doProfileSwitch(LocalProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, DateUtil.now()) + // Insulin + InsulinOrefUltraRapidActingPlugin.getPlugin().performPluginSwitch(true, PluginType.INSULIN) + // Pump + SP.putInt(R.string.key_danar_password, R_PASSWORD) + SP.putString(R.string.key_danar_bt_name, R_SERIAL) + (pump as PluginBase).performPluginSwitch(true, PluginType.PUMP) + // Sensitivity + SensitivityOref1Plugin.getPlugin().performPluginSwitch(true, PluginType.SENSITIVITY) + // APS + OpenAPSSMBPlugin.getPlugin().performPluginSwitch(true, PluginType.APS) + LoopPlugin.getPlugin().performPluginSwitch(true, PluginType.LOOP) + + // Enable common + ActionsPlugin.performPluginSwitch(true, PluginType.GENERAL) + + // Disable unneeded + MainApp.getPluginsList().remove(ObjectivesPlugin) + } + + @Test + fun doTest() { + Assert.assertTrue(isRunningTest()) + preparePlugins() + + while (!pump.isInitialized) { + log.debug("Waiting for initialization") + SystemClock.sleep(1000) + } + + while (true) { + log.debug("Tick") + SystemClock.sleep(1000) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index f74a58856f..c152c415cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -63,6 +63,8 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; +import static info.nightscout.androidaps.utils.EspressoTestHelperKt.isRunningRealPumpTest; + public class MainActivity extends NoSplashAppCompatActivity { private static Logger log = LoggerFactory.getLogger(L.CORE); private CompositeDisposable disposable = new CompositeDisposable(); @@ -137,7 +139,7 @@ public class MainActivity extends NoSplashAppCompatActivity { .subscribe(this::processPreferenceChange, FabricPrivacy::logException) ); - if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) { + if (!SP.getBoolean(R.string.key_setupwizard_processed, false) && !isRunningRealPumpTest()) { Intent intent = new Intent(this, SetupWizardActivity.class); startActivity(intent); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java index e236125255..5d4ec01fd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java @@ -74,7 +74,7 @@ public abstract class PluginBase { } } - private void performPluginSwitch(boolean enabled, PluginType type) { + public void performPluginSwitch(boolean enabled, PluginType type) { setPluginEnabled(type, enabled); setFragmentVisible(type, enabled); ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, getType()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index ea6731ca60..1f79b82bc6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -31,7 +31,7 @@ object RandomBgPlugin : PluginBase(PluginDescription() private val loopHandler = Handler() private lateinit var refreshLoop: Runnable - const val interval = 5L // minutes + const val interval = 1L // minutes init { refreshLoop = Runnable { @@ -55,7 +55,7 @@ object RandomBgPlugin : PluginBase(PluginDescription() } override fun specialEnableCondition(): Boolean { - return VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP) && (MainApp.engineeringMode || isRunningTest()) + return isRunningTest() || VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP) && MainApp.engineeringMode } override fun handleNewData(intent: Intent) { @@ -65,7 +65,7 @@ object RandomBgPlugin : PluginBase(PluginDescription() val cal = GregorianCalendar() val currentMinute = cal.get(Calendar.MINUTE) + (cal.get(Calendar.HOUR_OF_DAY) % 2) * 60 - val bgMgdl = min + (max - min) * sin(currentMinute / 120.0 * 2 * PI) + val bgMgdl = min + (max - min) + (max - min) * sin(currentMinute / 120.0 * 2 * PI) val bgReading = BgReading() bgReading.value = bgMgdl diff --git a/app/src/main/java/info/nightscout/androidaps/utils/EspressoTestHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/EspressoTestHelper.kt index 7288e6679f..0cddcc0792 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/EspressoTestHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/EspressoTestHelper.kt @@ -9,3 +9,13 @@ fun isRunningTest(): Boolean { false } } + +@Synchronized +fun isRunningRealPumpTest(): Boolean { + return try { + Class.forName("info.nightscout.androidaps.RealPumpTest") + true + } catch (e: ClassNotFoundException) { + false + } +} From b11707b5d44c12756138e73f43a5130fb5b4d3e4 Mon Sep 17 00:00:00 2001 From: sabsoubi Date: Fri, 21 Feb 2020 11:04:59 +0100 Subject: [PATCH 005/100] Fixed Bug that doesn't show COB if BGI disabled. --- .../general/xdripStatusline/StatuslinePlugin.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index da61b83b98..bd5b7e4eab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -202,13 +202,13 @@ public class StatuslinePlugin extends PluginBase { + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")"; } - if (!mPrefs.getBoolean("xdripstatus_showbgi", false)) { - return status; + // BGI + if (mPrefs.getBoolean("xdripstatus_showbgi", true)) { + double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(); + status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi); } - double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(); - - status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi); + /* COB */ status += " " + IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "StatuslinePlugin").generateCOBString(); return status; From 3b9ea53cc4f0f65eec3c698afe3e8a3e6f075432 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 25 Feb 2020 20:46:04 +0100 Subject: [PATCH 006/100] Fix TempTarget confirm dialog --- .../nightscout/androidaps/dialogs/TempTargetDialog.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index 77cb0b6823..5b1dd48692 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -114,11 +114,11 @@ class TempTargetDialog : DialogFragmentWithDate() { val reason = overview_temptarget_reason.selectedItem.toString() val unitResId = if (ProfileFunctions.getSystemUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol val target = overview_temptarget_temptarget.value - val duration = overview_temptarget_duration.value - if (target != 0.0 && duration != 0.0) { + val duration = overview_temptarget_duration.value.toInt() + if (target != 0.0 && duration != 0) { actions.add(MainApp.gs(R.string.reason) + ": " + reason) actions.add(MainApp.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + MainApp.gs(unitResId)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_hours, duration)) + actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, duration)) } else { actions.add(MainApp.gs(R.string.stoptemptarget)) } @@ -128,7 +128,7 @@ class TempTargetDialog : DialogFragmentWithDate() { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { log.debug("USER ENTRY: TEMP TARGET $target duration: $duration") - if (target == 0.0 || duration == 0.0) { + if (target == 0.0 || duration == 0) { val tempTarget = TempTarget() .date(eventTime) .duration(0) @@ -145,7 +145,7 @@ class TempTargetDialog : DialogFragmentWithDate() { .high(Profile.toMgdl(target, ProfileFunctions.getSystemUnits())) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) } - if (duration == 10.0) SP.putBoolean(R.string.key_objectiveusetemptarget, true) + if (duration == 10) SP.putBoolean(R.string.key_objectiveusetemptarget, true) }) } return true From 832663081101188d20c3380cc8818d5f6fc7ec35 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 25 Feb 2020 21:30:44 +0100 Subject: [PATCH 007/100] Revert gradle changes for UI tests --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 7d622ed56f..0dd80641bf 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -342,7 +342,7 @@ task copyLibs(dependsOn: downloadAndUnzipFile, type: Copy) { task full_clean(type: Delete) { delete file("src/main/jniLibs") } - +/* // Run 'adb' shell command to clear application data of main app for 'debug' variant task clearMainAppData(type: Exec) { // we have to iterate to find the 'debug' variant to obtain a variant reference @@ -372,7 +372,7 @@ tasks.whenTaskAdded { task -> task.dependsOn(clearMainAppData) } } - +*/ clean.dependsOn full_clean preBuild.dependsOn copyLibs From 26170ddea55401a2a15c60140365d40551b61b51 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 25 Feb 2020 21:54:14 +0100 Subject: [PATCH 008/100] New Crowdin translations (#2429) * New translations strings.xml (Swedish) * New translations strings.xml (Italian) * New translations strings.xml (Korean) * New translations strings.xml (German) * New translations strings.xml (Slovak) * New translations strings.xml (Korean) * New translations strings.xml (Korean) * New translations strings.xml (Portuguese) * New translations strings.xml (Korean) * New translations strings.xml (Korean) * New translations strings.xml (German) * New translations strings.xml (French) * New translations exam.xml (Dutch) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (Bulgarian) * New translations strings.xml (Korean) * New translations strings.xml (French) * New translations strings.xml (Spanish) * New translations strings.xml (Spanish) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) * New translations strings.xml (French) --- app/src/main/res/values-bg-rBG/strings.xml | 6 ++- app/src/main/res/values-de-rDE/strings.xml | 4 +- app/src/main/res/values-es-rES/strings.xml | 5 ++- app/src/main/res/values-fr-rFR/strings.xml | 42 ++++++++++++--------- app/src/main/res/values-it-rIT/strings.xml | 1 + app/src/main/res/values-ko-rKR/strings.xml | 37 +++++++++--------- app/src/main/res/values-nl-rNL/exam.xml | 4 +- app/src/main/res/values-pt-rPT/strings.xml | 5 +++ app/src/main/res/values-sk-rSK/strings.xml | 5 +++ app/src/main/res/values-sv-rSE/strings.xml | 7 ++++ wear/src/main/res/values-es-rES/strings.xml | 2 +- 11 files changed, 74 insertions(+), 44 deletions(-) diff --git a/app/src/main/res/values-bg-rBG/strings.xml b/app/src/main/res/values-bg-rBG/strings.xml index d3a01e2d86..78b71447fb 100644 --- a/app/src/main/res/values-bg-rBG/strings.xml +++ b/app/src/main/res/values-bg-rBG/strings.xml @@ -1,5 +1,4 @@ - @@ -946,6 +945,7 @@ Започнете първа цел Разрешение Питане за разрешение + ААПС изисква разрешение за да може да Ви уведомява Приложението се нуждае от достъп до вашето местоположение за да активира BT сканиране Приложението се нуждае от разрешение да съхранява данни за да може съхранява лог файлове Искане @@ -1449,4 +1449,8 @@ \"PhoneChecker\" Меню на графиката АS + Диапазон между изпълнение на SMB + Макс. време за изпълнение за SMB + Диапазон между временни базали + Продължителност на временни базали diff --git a/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/values-de-rDE/strings.xml index 8673afb35a..3ccf637260 100644 --- a/app/src/main/res/values-de-rDE/strings.xml +++ b/app/src/main/res/values-de-rDE/strings.xml @@ -846,7 +846,7 @@ Das Einlesen der geänderten Basalrate in der Pumpe schlug fehl Änderungen der Historie werden gesucht Der Import mehrerer Boli der gleichen Menge, abgegeben in der gleichen Minute, ist gescheitert: Nur ein Datensatz konnte den Behandlungen hinzugefügt werden. Bitte überprüfe die Pumpe und verwende das Careportal, um fehlende Einträge hinzuzufügen. Stelle sicher, dass keine Einträge für genau dieselbe Minute mit derselben Menge hinzugefügt werden. - \n\nhttp://www.androidaps.org\nhttp://www.androidaps.de (de)\n\nSupport:\nhttps://de.loopercommunity.org/ (de)\nhttp://facebook.androidaps.org + \n\nhttp://www.androidaps.org\nhttp://www.androidaps.de (de)\n\nSupport:\nhttps://de.loopercommunity.org/\nhttp://facebook.androidaps.org Der letzte Bolus liegt mehr als 24 Stunden zurück oder liegt in der Zukunft. Prüfe bitte das Datum auf der Pumpe. Zeit/Datum des abgegebenen Boluses auf der Pumpe erscheint falsch, IOB ist wahrscheinlich nicht korrekt. Bitte prüfe Zeit/Datum der Pumpe. Profil-Wechsel fehlt, bitte nimm einen Profil-Wechsel vor oder drücke \"AKTIVIERE PROFIL\" im lokalen Profil. @@ -1447,7 +1447,7 @@ Unerwartetes Verhalten. Warteschlange löschen? Alle Daten in der Warteschlange gehen verloren! Die Verwendung eines Verzögerungsbolus unterbricht dem Closed Loop Modus für die Dauer des Verzögerungsbolus. Willst Du das wirklich? Closed Loop wegen Verzögerungsbolus unterbrochen - VB + VerzB \"PhoneChecker\" Diagrammmenü AS diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 48e69e0564..9c4bd4d36a 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1,5 +1,4 @@ - @@ -1446,4 +1445,8 @@ El uso de la función de bolo extendido detendrá el modo de bucle cerrado durante el tiempo de ejecución del bolo extendido. ¿Realmente quieres esto? Bucle cerrado inhabilitado debido a la ejecución del bolo extendido EB + Menú gráfico + AS + Tiempo requerido de SMB + Tiempo de ejecución de SMB diff --git a/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml index 2437913625..c398fc1990 100644 --- a/app/src/main/res/values-fr-rFR/strings.xml +++ b/app/src/main/res/values-fr-rFR/strings.xml @@ -1,5 +1,4 @@ - @@ -157,7 +156,7 @@ Changez vos entrées ! Source des glycémies Quelle source de données doit être utilisée par AndroidAPS ? - xDrip + xDrip+ Mode APS Boucle Fermée Boucle Ouverte @@ -196,7 +195,7 @@ Capteur Glucides Insuline - Heure glucides + Décalage horaire Diviser Durée Pourcentage @@ -220,7 +219,7 @@ Importer les paramètres Max. U/hr pour le débit temp Basal Cette valeur est appelée Basal Maximum dans le contexte OpenAPS - Le Basal IA maximum que l\'OpenAPS pourra délivrer [U] + IA basale max que OpenAPS pourra délivrer [U] Cette valeur est appelée Max IA (Insuline Active) dans le contexte OpenAPS\nC\'estlle maximum d\'insuline en [U] que APS peut délivrer en une seule fois. FERMER DanaR @@ -385,7 +384,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Renvoyer toutes les données Afficher les Paramètres sur la Montre Erreur Pompe - Niveau Batterie Bas + Piles Faibles Arrêt de la Pompe Batterie Pompe Déchargée DanaR Coréenne @@ -644,7 +643,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Temps du Pic [min] Profil d\'insuline ajustable Oref Insuline à Action Rapide Oref - Insuline à Action Ultra Rapide Oref + Insuline Ultra Rapide Oref Durée d’Action pour %1$f trop courte - utiliser %2$f à la place ! Activer le profil Date @@ -701,7 +700,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Pilote pompe corrigé Pompe hors de portée Valeurs de glycémie manquantes - Utiliser le système des notifications + Utiliser les notifications système pour les alertes et notifications Alertes locales Alerte pas nouvelle donnée glycémique Alerte si la pompe est hors de portée @@ -766,7 +765,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Historique pompe Définir le profil basal Niveau réservoir pompe bas - Niveau batterie pompe bas + Pile pompe faible La pompe affiche l’erreur E%1$d: %2$s Bas Vide @@ -885,7 +884,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S réinitialiser En attente de synchronisation de l\'heure (%1$d sec) Déconnecté (%1$d m) - Maximum Insuline Active IA pour OpenAPS [U] + IA totale maximale pour OpenAPS [U] Cette valeur est appelée Max IA (Insuline Active) dans le contaxte OpenAPS\nOpenAPS n’ajoutera pas plus d’insuline si l\'IA (Insuline Active) actuelle est supérieure à cette valeur Pompe arrêtée Pompe démarrée @@ -909,15 +908,15 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S MGC Utilisez uniquement connexion Wi-fi Wi-fi SSID - Wi-fi uniquement pendant la charge + Uniquement si en charge Paramètres de connexion SSIDs autorisés (séparés par point-virgule) Autoriser connexion données itinérance Maximum Ratio Autosens Minimum Ratio Autosens - Diviseur de Bolus snooze DIA - Maximum multiplicateur quotidien de sécurité - Multiplicateur actuel de sécurité du Basal + Snooze bolus Diviseur de DAI + Multiplicateur max quotidien de sécurité + Multiplicateur de sécurité basale courante ND Type de pompe virtuelle Définition de pompe @@ -947,6 +946,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Démarrez votre premier objectif Autorisation Demande d\'autorisation + L\'application a besoin de l\'autorisation d\'accès à la fenêtre système pour les notifications L\'application requiert l\'autorisation de localisation pour le balayage Bluetooth L\'application requiert une autorisation de stockage de données afin de pouvoir sauvegarder les fichiers journaux Demande @@ -1015,7 +1015,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Erreur de commande Erreur de vitesse Violation d\'une limite d\'insuline - Changement minimum possible [%] + Changement minimum [%] Le fonctionnement de la Boucle demandera une confirmation uniquement si le changement est supérieur à cette valeur en %. Par défaut, la valeur est 20% Appairez SVP votre pompe avec votre téléphone ! Recherche d\'appareils en cours… @@ -1244,7 +1244,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Mondial (868 Mhz) Encodage logiciel 4b6b Encodage matériel 4b6b - Réveil et mise au point + Réveil et Réglage Effacer le bloc Bolus Réinitialiser la config. RileyLink Type de batterie (vue d\'alimentation) @@ -1270,8 +1270,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Paramètres Historique - Statut du RileyLink - Statut de la pompe + État du RileyLink + État de la pompe Paramètres RileyLink RileyLink Adresse configurée @@ -1300,7 +1300,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Bluetooth est désactivé Aucun adaptateur Bluetooth Échec du réglage - Pompe inaccessible + Pompe hors de portée Pod inaccessible Non configuré @@ -1448,4 +1448,10 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Boucle fermée désactivée à cause du bolus étendu EB \"Vérif. du téléphone\" + Menu Graph + AS + Heure de demande SMB + Heure d\'exécution SMB + Heure de demande basal temp + Heure d\'exécution basal temp diff --git a/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/values-it-rIT/strings.xml index cbf0f50945..952633064b 100644 --- a/app/src/main/res/values-it-rIT/strings.xml +++ b/app/src/main/res/values-it-rIT/strings.xml @@ -946,6 +946,7 @@ Avvia il tuo primo obiettivo Permesso Chiedi il permesso + L\'applicazione richiede il permesso finestra di sistema per le notifiche L\'applicazione richiede l\'accesso alla posizione per eseguire lo scan bluetooth L\'applicazione richiede l\'accesso alla memoria per salvare i file di log Richiesta diff --git a/app/src/main/res/values-ko-rKR/strings.xml b/app/src/main/res/values-ko-rKR/strings.xml index 066b4aee6b..66e4215fe6 100644 --- a/app/src/main/res/values-ko-rKR/strings.xml +++ b/app/src/main/res/values-ko-rKR/strings.xml @@ -1,5 +1,4 @@ - @@ -105,7 +104,7 @@ 근거 혈당 증분 - 증분: + Delta: 구성 관리자 목표 OpenAPS MA @@ -155,7 +154,7 @@ Basal: 탄수화물 입력값을 변경하세요! - 혈당 소스 + 혈당 출처 AndroidAPS가 어디에서 데이터를 가져옵니까? xDrip APS 모드 @@ -183,7 +182,7 @@ 인슐린 카트리지 교체 프로파일 변경 간식Bolus - 식사Bolus + Meal Bolus 교정Bolus 콤보Bolus 임시Basal 시작 @@ -254,7 +253,7 @@ 허가된 전화번호 +XXXXXXXXXX;+YYYYYYYYYY Bolus %1$.2fU 을 주입하려면 %2$s 를 입력하고 답장하세요 - 식사Bolus %1$.2f을 주입하려면 %2$s를 입력하고 답장하세요 + MEAL Bolus %1$.2f을 주입하려면 %2$s를 입력하고 답장하세요 임시목표 %1$s를 설정하려면 %2$s를 입력하고 답장하세요 임시목표를 취소하려면 %1$s를 입력하고 답장하세요 SMS 원격 기능을 비활성화려면 %1$s를 입력하고 답장하세요.\n\nAAPS 마스터폰을 통해서만 다시 활성화할 수 있습니다. @@ -267,7 +266,7 @@ Bolus %1$.2fU이 주입 완료되었습니다. %1$.2fU을 주입합니다 Bolus %1$.2fU이 주입 완료되었습니다 - 식사Bolus %1$.2f이 주입 완료되었습니다 + Meal Bolus %1$.2f이 주입 완료되었습니다 %2$d 분 동안 목표 %1$s %2$d 분 동안 목표 %1$s 설정이 완료되었습니다 임시 목표 취소가 완료되었습니다 @@ -328,24 +327,24 @@ 원격 명령이 허가되지 않았습니다 원격 주입이 불가능합니다. 나중에 다시 시도해주세요. %2$d분 동안 Basal %1$.2fU/h 주입하려면 %3$s 를 입력하고 답장하세요 - 프로파일을 %1$s %2$d%%로 변경하려면 %3$s 를 입력하고 답장하세요 + 프로파일 %1$s %2$d%%로 변경하려면 %3$s 를 입력하고 답장하세요 %2$d분 동안 확장 Bolus %1$.2fU 주입하려면 %3$s 를 입력하고 답장하세요 %2$s에 %1$dg을 입력하려면 %3$s를 입력하고 답장하세요 %2$d 분 동안 Basal %1$d%% 주입하려면 %3$s을 입력하고 답장하세요 %1$d분동안 Loop 일시중지하려면 %2$s 를 입력하고 답장하세요 Temp Basal %1$.2fU/h for %2$d min started successfully - %2$d분 동안 확장Bolus %1$.2fU주입이 성공적으로 시작되었습니다 + Extended bolus %1$.2fU for %2$d min started successfully 탄수화물 %1$dg 입력이 완료되었습니다 탄수화물 %1$dg 입력이 실패하였습니다 - %2$d분 동안 임시Basal %1$d%%주입이 성공적으로 시작되었습니다 + Temp basal %1$d%% for %2$d min started successfully Temp Basal start failed - 확장 Bolus 실행 실패 + Extended bolus start failed 임시Basal을 중지하려면 %1$s 를 입력하고 답장하세요 확장 Bolus를 중지하려면 %1$s 를 입력하고 답장하세요 Temp Basal canceled - 확장 Bolus 취소 + Extended bolus canceled Canceling Temp Basal failed - 확장 Bolus 취소가 실패하였습니다. + Canceling extended bolus failed 알려지지 않은 명령이거나 잘못된 답장입니다 빠른마법사 빠른마법사 설정 @@ -355,12 +354,12 @@ 추가 수정 삭제 - 식사 + Meal 교정주입 실행 AndroidAPS 시작 NS에 업로드만 하기(동기화 안됨) - NS에 업로드만 하기. 로컬소스(xDrip)가 선택되지 않으면 SGV에는 효력이 없습니다. NS프로파일이 사용중이라면 프로파일에는 효력이 없습니다. + NS에 업로드만 하기. xDrip같은 로컬 혈당 출처가 선택되지 않다면 SGV에는 효력이 없습니다. NS프로파일이 사용중이라면 프로파일에는 효력이 없습니다. 펌프가 초기화 되지 않았습니다! 펌프가 초기화와 프로파일 설정이 되지 않았습니다! 교체/채움 @@ -668,7 +667,7 @@ 임시목표 기본값 식사직전 기간 식사직전 목표 - activity 기간 + 활동 기간 활동 목표 저혈당 기간 저혈당 목표 @@ -784,9 +783,9 @@ %1$.2f 시간 %1$d 분 항상 SMB 사용하기 - Bolus와 독립적으로 항상 SMB를 사용합니다. G5처럼 잘 필터된 혈당소스와만 사용이 가능합니다. + Bolus와 독립적으로 항상 SMB를 사용합니다. G5처럼 잘 필터된 혈당출처와만 사용이 가능합니다. 탄수화물 이후 SMB를 사용합니다. - 탄수화물 이후 6시간동안 SMB를 사용합니다, 0 COB이라도 적용됩니다. G5처럼 잘 필터된 혈당소스와만 사용이 가능합니다. + 탄수화물 이후 6시간동안 SMB를 사용합니다, 0 COB이라도 적용됩니다. G5처럼 잘 필터된 혈당출처와만 사용이 가능합니다. COB와 SMB를 사용합니다. 활성화된 COB가 있으면 SMB를 사용합니다. 임시 목표에서 SMB 사용하기 @@ -878,7 +877,7 @@ 상태를 읽지 못했습니다. 펌프 위치 변경 기록 인슐린 카트리지 변경 기록 - 선택한 BG 소스가 고급 필터링을 지원하지 않기 때문에 SMB가 항상 비활성화됩니다. + 선택한 혈당 출처가 고급 필터링을 지원하지 않기 때문에 SMB가 항상 비활성화됩니다. Open Loop모드에선 SMB가 허용되지 않습니다. Food 재설정 @@ -940,7 +939,7 @@ https://github.com/MilosKozak/AndroidAPS/wiki/Sensitivity-detection-and-COB NSClient는 Nightscout와의 연결을 처리합니다. 이 부분을 건너뛸 수 있지만 설정하기 전엔 목적을 수행할 수 없습니다. 새로운 인슐린 프로파일은 최소 5시간의 DIA가 요구됩니다. 새로운 프로파일의 DIA 5-6시간은 구식 인슐린 프로파일의 DIA 3시간과 동일합니다. - 혈당소스 설정하기 + 혈당 출처 설정하기 프로파일 소스를 선택해주세요. 당뇨인이 어린이라면 NS 프로파일을 선택하여야 합니다. Nightscout으로 관리해줄 사람이 없다면 당신은 로컬 프로파일을 선호할 수도 있습니다. 여기선 프로파일의 소스를 선택할 뿐이라는 것을 명심하세요. 그 프로파일을 실제 사용하려면 \"프로파일 변경\"을 실행하여 프로파일을 활성화 시켜야합니다. 사용 가능한 알고리즘 중 하나를 선택하세요. 과거부터 최신의 순으로 정렬이 되어 있습니다. 일반적으로 새로운 알고리즘은 보다 강력하고 공격적입니다. 따라서 당신이 신규 사용자라면 최신의 알고리즘보단 AMA로 시작하는것이 나을 수 있습니다. 사용 전에 OpenAPS 문서를 읽어보고 설정하는 것을 잊지마세요. 첫번째 목표를 시작하세요. diff --git a/app/src/main/res/values-nl-rNL/exam.xml b/app/src/main/res/values-nl-rNL/exam.xml index 9768183305..eefa78bba3 100644 --- a/app/src/main/res/values-nl-rNL/exam.xml +++ b/app/src/main/res/values-nl-rNL/exam.xml @@ -122,7 +122,7 @@ xDrip app in volg-modus. Loop app op de iPhone. Spike app op de iPhone. - https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Children/kinderen.html + https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Children/Children.html Onderwerp: Insulinegevoeligheidsfactor Hogere ISF-waarden leiden tot minder insulineafgifte wanneer AAPS voor hoge BG corrigeert. Lagere ISF-waarden leiden tot minder insulineafgifte wanneer AAPS voor hoge BG corrigeert. @@ -130,7 +130,7 @@ U moet ISF invoeren in Instellingen. Het wijzigen van de ISF-waarde in uw profiel is voldoende om de wijziging toe te passen. https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#insuline-gevoeligheids-factor-insulin-sensitivity-factor-ISF-mmol-l-E-of-mg-dl-E - https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Profielen.html + https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Profiles.html Onderwerp: De KH ratio Hogere KH ratios leiden tot minder insuline afgifte voor een bepaalde hoeveelheid koolhydraten. Lagere KH ratios leiden tot minder insuline afgifte voor een bepaalde hoeveelheid koolhydraten. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index d2c3a9d519..313f6c6658 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -946,6 +946,7 @@ Iniciar primeiro objectivo Permissão Pedir permissão + Aplicação precisa de permissão de janela do sistema para notificações Aplicação requer permissão de localização para pesquisa BT Aplicação necessita da permissão de armazenamento para ser capaz de armazenar ficheiros de registo Pedido @@ -1449,4 +1450,8 @@ \"VerificadorTelefone\" Menu do Gráfico AS + Hora de solicitação SMB + Hora de execução do SMB + Hora de solicitação Basal Temp + Hora de execução Basal Temp diff --git a/app/src/main/res/values-sk-rSK/strings.xml b/app/src/main/res/values-sk-rSK/strings.xml index 38500ca8a2..0b8fdca2e3 100644 --- a/app/src/main/res/values-sk-rSK/strings.xml +++ b/app/src/main/res/values-sk-rSK/strings.xml @@ -946,6 +946,7 @@ Spusťte prvý cieľ Povolenie Vyžiadať si povolenie + Aplikácia vyžaduje pre oznámenia systémové oprávnenie Aplikácia vyžaduje povolenie \"polohy\", aby mohla vyhľadávať BT zariadenia Aplikácia vyžaduje prístup k úložisku, aby mohla ukladať logy Požiadavka @@ -1449,4 +1450,8 @@ PhoneChecker Grafové menu AS + Čas požiadavky SMB + Čas aplikácie SMB + Čas požiadavky dočasného bazálu + Čas spustenia dočasného bazálu diff --git a/app/src/main/res/values-sv-rSE/strings.xml b/app/src/main/res/values-sv-rSE/strings.xml index ec0e76b738..96b45303a9 100644 --- a/app/src/main/res/values-sv-rSE/strings.xml +++ b/app/src/main/res/values-sv-rSE/strings.xml @@ -947,6 +947,7 @@ Eversense-appen. Påbörja ditt första mål Behörighet Be om behörighet + Applikationen behöver förhöjd behörighet för aviseringar Appen behöver behörighet att använda Platsinfo för att kunna söka efter Bluetooth-enheter Appen behöver behörighet att använda Lagring för att kunna spara loggfiler Begäran @@ -1448,4 +1449,10 @@ Eversense-appen. Closed Loop-läget inaktiverat pga att en förlängd bolus är aktiv FB Telefonkontroll + Diagrammeny + AS + SMB begärd + SMB utförd + Basalförändring begärd + Basalförändring utförd diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index af200da3fb..6e65157335 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -1,5 +1,4 @@ - AAPS AAPS @@ -51,6 +50,7 @@ Bajo Medio Alto + Auto Números grandes Historial de Ring Historial de Ring Light From 1db651055b46f88ae924525f40f3546b3150a68e Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 28 Feb 2020 22:51:12 +0100 Subject: [PATCH 009/100] RS tests --- .../DanaRS_Packet_Notify_Delivery_Complete.kt | 2 +- app/src/test/java/info/TestBase.kt | 24 +++++++++ .../comm/DanaRSMessageHashTableTest.java | 36 ------------- .../danaRS/comm/DanaRSMessageHashTableTest.kt | 50 +++++++++++++++++++ ...Packet_Bolus_Set_Step_Bolus_StartTest.java | 46 ----------------- ...RS_Packet_Bolus_Set_Step_Bolus_StopTest.kt | 29 ++++++----- ...aRS_Packet_Notify_Delivery_CompleteTest.kt | 30 ++++++----- 7 files changed, 108 insertions(+), 109 deletions(-) create mode 100644 app/src/test/java/info/TestBase.kt delete mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.java create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.kt delete mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.java diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.kt index a0419deaaa..246f2c7fe5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.kt @@ -27,7 +27,7 @@ class DanaRS_Packet_Notify_Delivery_Complete( val deliveredInsulin = byteArrayToInt(getBytes(data, DATA_START, 2)) / 100.0 danaRSPlugin.bolusingTreatment.insulin = deliveredInsulin val bolusingEvent = EventOverviewBolusProgress - bolusingEvent.status = String.format(resourceHelper.gs(R.string.bolusdelivering), deliveredInsulin) + bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, deliveredInsulin) bolusingEvent.t = danaRSPlugin.bolusingTreatment bolusingEvent.percent = min((deliveredInsulin / danaRSPlugin.bolusAmountToBeDelivered * 100).toInt(), 100) danaRSPlugin.bolusDone = true diff --git a/app/src/test/java/info/TestBase.kt b/app/src/test/java/info/TestBase.kt new file mode 100644 index 0000000000..235e470e65 --- /dev/null +++ b/app/src/test/java/info/TestBase.kt @@ -0,0 +1,24 @@ +package info + +import org.junit.Rule +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnit +import org.mockito.junit.MockitoRule + +open class TestBase { + // Add a JUnit rule that will setup the @Mock annotated vars and log. + // Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method. + @get:Rule + val mockitoRule: MockitoRule = MockitoJUnit.rule() + + // Workaround for Kotlin nullability. + // https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791 + // https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin + fun anyObject(): T { + Mockito.any() + return uninitialized() + } + + @Suppress("Unchecked_Cast") + fun uninitialized(): T = null as T +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.java deleted file mode 100644 index b498fb8bbc..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm; - - -import com.cozmo.danar.util.BleCommandUtil; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; - -/** - * Created by Rumen Georgiev on 8/9/2018. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, SP.class, L.class, DanaRSMessageHashTable.class}) -public class DanaRSMessageHashTableTest { - @Test - public void runTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); -// HashMap messages = new DanaRSMessageHashTable().messages; - DanaRS_Packet forTesting = new DanaRS_Packet_APS_Set_Event_History(); - DanaRS_Packet testPacket = DanaRSMessageHashTable.findMessage(forTesting.getCommand()); - assertEquals(BleCommandUtil.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY, testPacket.getOpCode()); - } - -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.kt new file mode 100644 index 0000000000..55a3539d8b --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTableTest.kt @@ -0,0 +1,50 @@ +package info.nightscout.androidaps.plugins.pump.danaRS.comm + +import com.cozmo.danar.util.BleCommandUtil +import info.TestBase +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump +import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.Mockito.`when` +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner + +@RunWith(PowerMockRunner::class) +@PrepareForTest(ConstraintChecker::class) +class DanaRSMessageHashTableTest : TestBase() { + + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var rxBus: RxBusWrapper + @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var danaRSPlugin: DanaRSPlugin + @Mock lateinit var activePlugin: ActivePluginProvider + @Mock lateinit var constraintChecker: ConstraintChecker + @Mock lateinit var sp: SP + lateinit var danaRPump: DanaRPump + + @Test + fun runTest() { + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + + val danaRSMessageHashTable = DanaRSMessageHashTable(aapsLogger, rxBus, resourceHelper, danaRPump, danaRSPlugin, activePlugin, constraintChecker) + val forTesting: DanaRS_Packet = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, 0, 0, 0) + val testPacket: DanaRS_Packet = danaRSMessageHashTable.findMessage(forTesting.command) + Assert.assertEquals(BleCommandUtil.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY.toLong(), testPacket.getOpCode().toLong()) + } + + @Before + fun setup() { + danaRPump = DanaRPump(aapsLogger, sp) + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.java deleted file mode 100644 index 1889ff9611..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; - -/** - * Created by Rumen on 31.07.2018. - */ - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, SP.class, L.class}) -public class DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest { - - @Test - public void runTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); - - DanaRS_Packet_Bolus_Set_Step_Bolus_Start packet = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(); - - // test params - byte[] testparams = packet.getRequestParams(); - assertEquals(0, testparams[0]); - assertEquals(0, testparams[2]); - - // test message decoding - packet.handleMessage(new byte[]{(byte) 0, (byte) 0, (byte) 0}); - assertEquals(false, packet.failed); - packet.handleMessage(new byte[]{(byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1, (byte) 1}); - assertEquals(true, packet.failed); - - assertEquals("BOLUS__SET_STEP_BOLUS_START", packet.getFriendlyName()); - } - -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt index 4ecf11ef16..ae68b1c123 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt @@ -2,30 +2,35 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.AAPSMocker -import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.logging.L +import info.TestBase +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.utils.DefaultValueHelper -import info.nightscout.androidaps.utils.SP import info.nightscout.androidaps.utils.resources.ResourceHelper import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(MainApp::class, SP::class, L::class) -class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest : DanaRS_Packet_Bolus_Set_Step_Bolus_Stop() { +@PrepareForTest(RxBusWrapper::class) +class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest : TestBase() { @Mock lateinit var defaultValueHelper: DefaultValueHelper + @Mock lateinit var rxBus: RxBusWrapper + @Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Mock lateinit var danaRSPlugin: DanaRSPlugin private var treatmentInjector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { @@ -39,17 +44,15 @@ class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest : DanaRS_Packet_Bolus_Set_Step } @Test fun runTest() { - AAPSMocker.mockMainApp() - AAPSMocker.mockApplicationContext() - AAPSMocker.mockStrings() - AAPSMocker.mockSP() - AAPSMocker.mockL() - val testPacket = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(1.0, Treatment(treatmentInjector)) + `when`(resourceHelper.gs(Mockito.anyInt())).thenReturn("SomeString") + + danaRSPlugin.bolusingTreatment = Treatment(treatmentInjector) + val testPacket = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin) // test message decoding testPacket.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, testPacket.failed) testPacket.handleMessage(byteArrayOf(1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte())) Assert.assertEquals(true, testPacket.failed) - Assert.assertEquals("BOLUS__SET_STEP_BOLUS_STOP", friendlyName) + Assert.assertEquals("BOLUS__SET_STEP_BOLUS_STOP", testPacket.friendlyName) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.kt index 77863a83d8..501b8472c8 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.kt @@ -2,28 +2,34 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.AAPSMocker -import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.logging.L +import info.TestBase +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.utils.DefaultValueHelper -import info.nightscout.androidaps.utils.SP import info.nightscout.androidaps.utils.resources.ResourceHelper import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock +import org.mockito.Mockito.`when` +import org.mockito.Mockito.anyDouble +import org.mockito.Mockito.anyInt import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(MainApp::class, SP::class, L::class) -class DanaRS_Packet_Notify_Delivery_CompleteTest { +@PrepareForTest(RxBusWrapper::class) +class DanaRS_Packet_Notify_Delivery_CompleteTest : TestBase() { @Mock lateinit var defaultValueHelper: DefaultValueHelper + @Mock lateinit var rxBus: RxBusWrapper + @Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var danaRSPlugin: DanaRSPlugin @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin @@ -39,17 +45,15 @@ class DanaRS_Packet_Notify_Delivery_CompleteTest { } @Test fun runTest() { - AAPSMocker.mockMainApp() - AAPSMocker.mockApplicationContext() - AAPSMocker.mockSP() - AAPSMocker.mockL() - AAPSMocker.mockStrings() - val packet = DanaRS_Packet_Notify_Delivery_Complete(0.5, Treatment(treatmentInjector)) + `when`(resourceHelper.gs(anyInt(), anyDouble())).thenReturn("SomeString") + + danaRSPlugin.bolusingTreatment = Treatment(treatmentInjector) + val packet = DanaRS_Packet_Notify_Delivery_Complete(aapsLogger, rxBus, resourceHelper, danaRSPlugin) // test params Assert.assertEquals(null, packet.requestParams) // test message decoding packet.handleMessage(createArray(17, 0.toByte())) - Assert.assertEquals(true, DanaRS_Packet_Notify_Delivery_Complete.done) + Assert.assertEquals(true, danaRSPlugin.bolusDone) Assert.assertEquals("NOTIFY__DELIVERY_COMPLETE", packet.friendlyName) } From a694edd1708ab25391e30c43ad0b4f041c86dac5 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 29 Feb 2020 00:12:13 +0100 Subject: [PATCH 010/100] RS tests --- ...ket_APS_Basal_Set_Temporary_BasalTest.java | 93 --------------- ...acket_APS_Basal_Set_Temporary_BasalTest.kt | 54 +++++++++ .../DanaRS_Packet_APS_History_EventsTest.java | 106 ------------------ .../DanaRS_Packet_APS_History_EventsTest.kt | 73 ++++++++++++ ...naRS_Packet_APS_Set_Event_HistoryTest.java | 72 ------------ ...DanaRS_Packet_APS_Set_Event_HistoryTest.kt | 56 +++++++++ 6 files changed, 183 insertions(+), 271 deletions(-) delete mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.java create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.kt delete mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.kt delete mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.java create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.java deleted file mode 100644 index c249f9c618..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm; - - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; - -/** - * Created by mike on 20.11.2017. - */ - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, SP.class, L.class}) -public class DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest { - - @Test - public void runTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); - - // under 100% should last 30 min - DanaRS_Packet_APS_Basal_Set_Temporary_Basal packet = new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(); - packet.setParams(0); - assertEquals(0, packet.temporaryBasalRatio); - assertEquals(packet.PARAM30MIN, packet.temporaryBasalDuration); - //constructor with param - packet = new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(10); - assertEquals(10, packet.temporaryBasalRatio); - assertEquals(packet.PARAM30MIN, packet.temporaryBasalDuration); - packet = new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(20, true, false); - assertEquals(20, packet.temporaryBasalRatio); - assertEquals(packet.PARAM15MIN, packet.temporaryBasalDuration); - // over 100% should last 15 min - packet.setParams(150); - assertEquals(150, packet.temporaryBasalRatio); - assertEquals(packet.PARAM15MIN, packet.temporaryBasalDuration); - // test low hard limit - packet.setParams(-1); - assertEquals(0, packet.temporaryBasalRatio); - assertEquals(packet.PARAM30MIN, packet.temporaryBasalDuration); - // test high hard limit - packet.setParams(550); - assertEquals(500, packet.temporaryBasalRatio); - assertEquals(packet.PARAM15MIN, packet.temporaryBasalDuration); - // test setting 15 min - packet.setParams(50, true, false); - assertEquals(50, packet.temporaryBasalRatio); - assertEquals(packet.PARAM15MIN, packet.temporaryBasalDuration); - // test setting 30 min - packet.setParams(50, false, true); - assertEquals(50, packet.temporaryBasalRatio); - assertEquals(packet.PARAM30MIN, packet.temporaryBasalDuration); - // over 200% set always 15 min - packet.setParams(250, false, true); - assertEquals(250, packet.temporaryBasalRatio); - assertEquals(packet.PARAM15MIN, packet.temporaryBasalDuration); - // test low hard limit - packet.setParams(-1, false, true); - assertEquals(0, packet.temporaryBasalRatio); - assertEquals(packet.PARAM30MIN, packet.temporaryBasalDuration); - // test high hard limit - packet.setParams(550, false, true); - assertEquals(500, packet.temporaryBasalRatio); - assertEquals(packet.PARAM15MIN, packet.temporaryBasalDuration); - - // test message generation - packet.setParams(260, true, false); - byte[] generatedCode = packet.getRequestParams(); - assertEquals(3, generatedCode.length); - assertEquals((byte) 4, generatedCode[0]); - assertEquals((byte) 1, generatedCode[1]); - assertEquals((byte) packet.PARAM15MIN, generatedCode[2]); - - // test message decoding - packet.handleMessage(new byte[]{(byte) 0, (byte) 0, (byte) 0}); - assertEquals(false, packet.failed); - packet.handleMessage(new byte[]{(byte) 0, (byte) 0, (byte) 1}); - assertEquals(true, packet.failed); - - assertEquals("BASAL__APS_SET_TEMPORARY_BASAL", packet.getFriendlyName()); - } - -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.kt new file mode 100644 index 0000000000..7196e4ba87 --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest.kt @@ -0,0 +1,54 @@ +package info.nightscout.androidaps.plugins.pump.danaRS.comm + +import info.TestBase +import info.nightscout.androidaps.logging.AAPSLogger +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner + +@RunWith(PowerMockRunner::class) +@PrepareForTest() +class DanaRS_Packet_APS_Basal_Set_Temporary_BasalTest : TestBase() { + + @Mock lateinit var aapsLogger: AAPSLogger + + @Test fun runTest() { + + // under 100% should last 30 min + var packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 0) + Assert.assertEquals(0, packet.temporaryBasalRatio) + Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM30MIN, packet.temporaryBasalDuration) + //constructor with param + packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 10) + Assert.assertEquals(10, packet.temporaryBasalRatio) + Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM30MIN, packet.temporaryBasalDuration) + // over 100% should last 15 min + packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 150) + Assert.assertEquals(150, packet.temporaryBasalRatio) + Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM15MIN, packet.temporaryBasalDuration) + // test low hard limit + packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, -1) + Assert.assertEquals(0, packet.temporaryBasalRatio) + Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM30MIN, packet.temporaryBasalDuration) + // test high hard limit + packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 550) + Assert.assertEquals(500, packet.temporaryBasalRatio) + Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM15MIN, packet.temporaryBasalDuration) + // test message generation + packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 260) + val generatedCode = packet.requestParams + Assert.assertEquals(3, generatedCode.size.toLong()) + Assert.assertEquals(4.toByte(), generatedCode[0]) + Assert.assertEquals(1.toByte(), generatedCode[1]) + Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM15MIN.toUByte(), generatedCode[2].toUByte()) + // test message decoding + packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) + Assert.assertEquals(false, packet.failed) + packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 1.toByte())) + Assert.assertEquals(true, packet.failed) + Assert.assertEquals("BASAL__APS_SET_TEMPORARY_BASAL", packet.friendlyName) + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java deleted file mode 100644 index a866ce73a7..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm; - - -import android.content.Context; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Calendar; -import java.util.GregorianCalendar; - -import info.AAPSMocker; -import info.SPMocker; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.db.DatabaseHelper; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.treatments.TreatmentService; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Created by Rumen on 31.07.2018. - */ - -@RunWith(PowerMockRunner.class) -@PrepareForTest({SP.class, MainApp.class, ConfigBuilderPlugin.class, Context.class, NSUpload.class, TreatmentsPlugin.class, TreatmentService.class, DatabaseHelper.class, DateUtil.class}) -public class DanaRS_Packet_APS_History_EventsTest extends DanaRS_Packet_APS_History_Events { - - @Test - public void runTest() { - DanaRS_Packet_APS_History_Events testPacket = new DanaRS_Packet_APS_History_Events(DateUtil.now()); - // test getRequestedParams - byte[] returnedValues = testPacket.getRequestParams(); - byte[] expectedValues = getCalender(DateUtil.now()); - //year - assertEquals(expectedValues[0], returnedValues[0]); - //month - assertEquals(expectedValues[1], returnedValues[1]); - //day of month - assertEquals(expectedValues[2], returnedValues[2]); - // hour - assertEquals(expectedValues[3], returnedValues[3]); - // minute - assertEquals(expectedValues[4], returnedValues[4]); - // second - assertEquals(expectedValues[5], returnedValues[5]); - - // test message decoding - testPacket.handleMessage(createArray(50, (byte) 0)); - assertEquals(false, failed); -// testPacket.handleMessage(createArray(50, (byte) 1)); -// assertEquals(true, done); - - assertEquals("APS_HISTORY_EVENTS", getFriendlyName()); - } - - byte[] createArray(int length, byte fillWith) { - byte[] ret = new byte[length]; - for (int i = 0; i < length; i++) { - ret[i] = fillWith; - } - return ret; - } - - public byte[] getCalender(long from) { - GregorianCalendar cal = new GregorianCalendar(); - if (from != 0) - cal.setTimeInMillis(from); - else - cal.set(2000, 0, 1, 0, 0, 0); - byte[] ret = new byte[6]; - ret[0] = (byte) ((cal.get(Calendar.YEAR) - 1900 - 100) & 0xff); - ret[1] = (byte) ((cal.get(Calendar.MONTH) + 1) & 0xff); - ret[2] = (byte) ((cal.get(Calendar.DAY_OF_MONTH)) & 0xff); - ret[3] = (byte) ((cal.get(Calendar.HOUR_OF_DAY)) & 0xff); - ret[4] = (byte) ((cal.get(Calendar.MINUTE)) & 0xff); - ret[5] = (byte) ((cal.get(Calendar.SECOND)) & 0xff); - - return ret; - } - - @Before - public void prepareTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - SPMocker.prepareMock(); - SP.putString("profile", AAPSMocker.getValidProfileStore().getData().toString()); - AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockStrings(); - PowerMockito.mockStatic(NSUpload.class); - AAPSMocker.mockDatabaseHelper(); - - PowerMockito.mockStatic(DateUtil.class); - when(DateUtil.now()).thenReturn(5456465445L); - } -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.kt new file mode 100644 index 0000000000..42cf5bf7eb --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.kt @@ -0,0 +1,73 @@ +package info.nightscout.androidaps.plugins.pump.danaRS.comm + +import info.TestBase +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner +import java.util.* + +@RunWith(PowerMockRunner::class) +@PrepareForTest(RxBusWrapper::class) +class DanaRS_Packet_APS_History_EventsTest : TestBase() { + + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var rxBus: RxBusWrapper + @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var activePlugin: ActivePluginProvider + @Mock lateinit var danaRSPlugin: DanaRSPlugin + + @Test fun runTest() { + val now = DateUtil.now() + + val testPacket = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, now) + // test getRequestedParams + val returnedValues = testPacket.requestParams + val expectedValues = getCalender(now) + //year + Assert.assertEquals(expectedValues[0], returnedValues[0]) + //month + Assert.assertEquals(expectedValues[1], returnedValues[1]) + //day of month + Assert.assertEquals(expectedValues[2], returnedValues[2]) + // hour + Assert.assertEquals(expectedValues[3], returnedValues[3]) + // minute + Assert.assertEquals(expectedValues[4], returnedValues[4]) + // second + Assert.assertEquals(expectedValues[5], returnedValues[5]) + // test message decoding + testPacket.handleMessage(createArray(50, 0.toByte())) + Assert.assertEquals(false, testPacket.failed) + Assert.assertEquals("APS_HISTORY_EVENTS", testPacket.friendlyName) + } + + fun createArray(length: Int, fillWith: Byte): ByteArray { + val ret = ByteArray(length) + for (i in 0 until length) { + ret[i] = fillWith + } + return ret + } + + fun getCalender(from: Long): ByteArray { + val cal = GregorianCalendar() + if (from != 0L) cal.timeInMillis = from else cal[2000, 0, 1, 0, 0] = 0 + val ret = ByteArray(6) + ret[0] = (cal[Calendar.YEAR] - 1900 - 100 and 0xff).toByte() + ret[1] = (cal[Calendar.MONTH] + 1 and 0xff).toByte() + ret[2] = (cal[Calendar.DAY_OF_MONTH] and 0xff).toByte() + ret[3] = (cal[Calendar.HOUR_OF_DAY] and 0xff).toByte() + ret[4] = (cal[Calendar.MINUTE] and 0xff).toByte() + ret[5] = (cal[Calendar.SECOND] and 0xff).toByte() + return ret + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.java deleted file mode 100644 index 49820441be..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm; - - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; -import static org.powermock.api.mockito.PowerMockito.when; - -/** - * Created by Rumen on 31.07.2018. - */ - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, SP.class, L.class, DateUtil.class}) -public class DanaRS_Packet_APS_Set_Event_HistoryTest { - - @Test - public void runTest() { - // test for negative carbs - DanaRS_Packet_APS_Set_Event_History historyTest = new DanaRS_Packet_APS_Set_Event_History(DanaRPump.CARBS, DateUtil.now(), -1, 0); - byte[] testparams = historyTest.getRequestParams(); - assertEquals((byte) 0, testparams[8]); - // 5g carbs - historyTest = new DanaRS_Packet_APS_Set_Event_History(DanaRPump.CARBS, DateUtil.now(), 5, 0); - testparams = historyTest.getRequestParams(); - assertEquals((byte) 5, testparams[8]); - // 150g carbs - historyTest = new DanaRS_Packet_APS_Set_Event_History(DanaRPump.CARBS, DateUtil.now(), 150, 0); - testparams = historyTest.getRequestParams(); - assertEquals((byte) 150, testparams[8]); - // test low hard limit - // test high hard limit - - // test message generation - historyTest = new DanaRS_Packet_APS_Set_Event_History(DanaRPump.CARBS, DateUtil.now(), 5, 0); - testparams = historyTest.getRequestParams(); - assertEquals((byte) 5, testparams[8]); - assertEquals(11, testparams.length); - assertEquals((byte) DanaRPump.CARBS, testparams[0]); - - // test message decoding - historyTest.handleMessage(new byte[]{(byte) 0, (byte) 0, (byte) 0}); - assertEquals(false, historyTest.failed); - historyTest.handleMessage(new byte[]{(byte) 0, (byte) 0, (byte) 1}); - assertEquals(true, historyTest.failed); - - assertEquals("APS_SET_EVENT_HISTORY", historyTest.getFriendlyName()); - } - - @Before - public void prepareTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); - - PowerMockito.mockStatic(DateUtil.class); - when(DateUtil.now()).thenReturn(5456465445L); - } -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt new file mode 100644 index 0000000000..e20b2e7f83 --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_HistoryTest.kt @@ -0,0 +1,56 @@ +package info.nightscout.androidaps.plugins.pump.danaRS.comm + +import info.AAPSMocker +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump +import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.powermock.api.mockito.PowerMockito +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner + +@RunWith(PowerMockRunner::class) +@PrepareForTest() +class DanaRS_Packet_APS_Set_Event_HistoryTest { + + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var rxBus: RxBusWrapper + @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var activePlugin: ActivePluginProvider + @Mock lateinit var danaRSPlugin: DanaRSPlugin + + @Test fun runTest() { // test for negative carbs + val now = DateUtil.now() + var historyTest = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, now, -1, 0) + var testparams = historyTest.requestParams + Assert.assertEquals(0.toByte(), testparams[8]) + // 5g carbs + historyTest = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, now, 5, 0) + testparams = historyTest.requestParams + Assert.assertEquals(5.toByte(), testparams[8]) + // 150g carbs + historyTest = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, now, 150, 0) + testparams = historyTest.requestParams + Assert.assertEquals(150.toByte(), testparams[8]) + // test message generation + historyTest = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, now, 5, 0) + testparams = historyTest.requestParams + Assert.assertEquals(5.toByte(), testparams[8]) + Assert.assertEquals(11, testparams.size) + Assert.assertEquals(DanaRPump.CARBS.toByte(), testparams[0]) + // test message decoding + historyTest.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) + Assert.assertEquals(false, historyTest.failed) + historyTest.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 1.toByte())) + Assert.assertEquals(true, historyTest.failed) + Assert.assertEquals("APS_SET_EVENT_HISTORY", historyTest.friendlyName) + } +} \ No newline at end of file From dfd3115b590262a6183bd0ec92c1c8ffd426ac5e Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 29 Feb 2020 21:32:06 +0100 Subject: [PATCH 011/100] gradle update --- .idea/codeStyles/Project.xml | 3 --- build.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 ++-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 48bbf82e58..d1c3d63de5 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -1,9 +1,6 @@ diff --git a/wear/src/main/res/values-it-rIT/strings.xml b/wear/src/main/res/values-it-rIT/strings.xml index 5247ee0674..0f7282e210 100644 --- a/wear/src/main/res/values-it-rIT/strings.xml +++ b/wear/src/main/res/values-it-rIT/strings.xml @@ -1,5 +1,4 @@ - AAPS AAPS @@ -98,7 +97,7 @@ TDD CHO IOB - no stato + no status mg/dl mmol/l g diff --git a/wear/src/main/res/values-nl-rNL/strings.xml b/wear/src/main/res/values-nl-rNL/strings.xml index e1e7c4c3d6..784fdb2f19 100644 --- a/wear/src/main/res/values-nl-rNL/strings.xml +++ b/wear/src/main/res/values-nl-rNL/strings.xml @@ -1,18 +1,109 @@ - + AAPS + AAPS + AAPS + AAPS(Groot) + AAPS(GroteGrafiek) + AAPS(GeenGrafiek) + AAPS(Cirkel) + AAPSv2 + AAPS(Cockpit) + AAPS(Steampunk) + Geen gegevens! + Oude gegevens! + Sinds %1$s + Synchroniseer met AAPS! + Geen gegevens ontvangen sinds %1$s! Controleer of AAPS op de telefoon gegevens verstuurt naar horloge AAPS gegevens zijn %1$s oud! Controleer je sensor, xDrip+, NS, AAPS instellingen of andere! Aan Uit Trillen bij bolus Eenheden voor acties Toon datum + Toon IOB + Toon COB Toon Delta Toon gemiddelde delta + Toon telefoonbatterij + Toon rig batterij + Toon basaal + Toon loop status + Toon BG + Toon richtingspijl + Toon tijd geleden + Donker + Markeer basaalstanden + Bijpassende verdeler + Tijdsschaal grafiek 1 uur 2 uren 3 uren 4 uren 5 uren + Invoer ontwerp Standaard + Snel rechts + Snel links + Modern spaarzaam + Delta schaalverdeling (Steampunk) + Laag + Middel + Hoog + Automatisch + Grote nummers + Ring geschiedenis + Lichte ring geschiedenis + Animaties + Wizard in menu + Ontlucht/vul in menu + Enkel streefdoel + Wizardpercentage + Complicatie tik voor actie + Unicode in complicaties + Versie: + TijdStreefd + Wizard + Bolus + eCarb + Instellingen + Status + Ontlucht/vul + Geen + Standaard + Menu + tijdsduur + doel + laag + hoog + khd + percentage + start [min] + duur [h] + insuline + Voorinstelling 1 + Voorinstelling 2 + Voorinstelling 3 + Vrije hoeveelheid + BEVESTIGEN + STATUS POMP + STATUS LOOP + tijdsverschuiving + Gewogen TDD + bolus + Pomp + Loop + CPP + TDD + Khd + IOB + geen status + mg/dl + mmol/l + g + E + E/u + u + d + w From 6fa05f11c92a3965e0a7d901220163afd4986089 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 6 Mar 2020 19:02:34 +0100 Subject: [PATCH 030/100] LocalInsightPlugin crash fix --- .../androidaps/plugins/pump/insight/LocalInsightPlugin.java | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 8dd425b12c..2197b48577 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -937,6 +937,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); + if (connectionService == null) return null; if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) { return null; } From ac70c89eee3f5f18100abb5ca227b4ac12680d09 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 6 Mar 2020 19:13:33 +0100 Subject: [PATCH 031/100] Unregister shared preferences properly --- .../androidaps/activities/MyPreferenceFragment.kt | 7 +++++++ 1 file changed, 7 insertions(+) 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 70d8520182..5ef5d8f6a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -112,6 +112,13 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang outState.putInt("id", pluginId) } + override fun onDestroy() { + super.onDestroy() + PreferenceManager + .getDefaultSharedPreferences(context) + .unregisterOnSharedPreferenceChangeListener(this) + } + private fun addPreferencesFromResourceIfEnabled(p: PluginBase?, rootKey: String?, enabled: Boolean) { if (enabled) addPreferencesFromResourceIfEnabled(p, rootKey) } From 95394d6cb370fb8f92f81af00b8183e4f269c9c8 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 6 Mar 2020 19:13:56 +0100 Subject: [PATCH 032/100] Unregister shared preferences properly --- .../androidaps/activities/PreferencesActivity.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java index 328f143836..96a2b23b06 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -68,6 +68,12 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); } + @Override + protected void onDestroy() { + super.onDestroy(); + PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); + } + @Override public void attachBaseContext(Context newBase) { super.attachBaseContext(LocaleHelper.INSTANCE.wrap(newBase)); From 4cca305e1bb9d7cba6f4672ca6e1756e8db5e1ac Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 6 Mar 2020 19:40:29 +0100 Subject: [PATCH 033/100] fix ProfileSwitch confirm dialog --- .../nightscout/androidaps/dialogs/ProfileSwitchDialog.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index f594564a78..a258cbec8a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -78,9 +78,9 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { ?: return false val actions: LinkedList = LinkedList() - val duration = overview_profileswitch_duration.value + val duration = overview_profileswitch_duration.value.toInt() if (duration > 0) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_hours, duration)) + actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, duration)) val profile = overview_profileswitch_profile.selectedItem.toString() actions.add(MainApp.gs(R.string.profile) + ": " + profile) val percent = overview_profileswitch_percentage.value.toInt() @@ -98,7 +98,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { log.debug("USER ENTRY: PROFILE SWITCH $profile percent: $percent timeshift: $timeShift duration: $duration") - ProfileFunctions.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) + ProfileFunctions.doProfileSwitch(profileStore, profile, duration, percent, timeShift, eventTime) }) } return true From 70053ea61cca3faa2c585b064a8deb477fa469b7 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Fri, 6 Mar 2020 12:33:20 +0100 Subject: [PATCH 034/100] Combo: create separate bolus/carb records at driver level. --- .../plugins/pump/combo/ComboPlugin.java | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 32a17f8a89..e71a86d91f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -654,16 +654,29 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint * Creates a treatment record based on the request in DetailBolusInfo and the delivered bolus. */ private boolean addBolusToTreatments(DetailedBolusInfo detailedBolusInfo, Bolus lastPumpBolus) { - DetailedBolusInfo dbi = detailedBolusInfo.copy(); - dbi.date = calculateFakeBolusDate(lastPumpBolus); - dbi.pumpId = dbi.date; - dbi.source = Source.PUMP; - dbi.insulin = lastPumpBolus.amount; + DetailedBolusInfo bolusInfo = detailedBolusInfo.copy(); + bolusInfo.date = calculateFakeBolusDate(lastPumpBolus); + bolusInfo.pumpId = bolusInfo.date; + bolusInfo.source = Source.PUMP; + bolusInfo.insulin = lastPumpBolus.amount; try { - TreatmentsPlugin.getPlugin().addToHistoryTreatment(dbi, true); + if (bolusInfo.carbs > 0 && bolusInfo.carbTime != 0) { + // split out a separate carbs record without a pumpId + DetailedBolusInfo carbInfo = new DetailedBolusInfo(); + carbInfo.date = bolusInfo.date + bolusInfo.carbTime * 60L * 1000L; + carbInfo.carbs = bolusInfo.carbs; + carbInfo.source = Source.USER; + TreatmentsPlugin.getPlugin().addToHistoryTreatment(carbInfo, true); + + // remove carbs from bolusInfo to not trigger any unwanted code paths in + // TreatmentsPlugin.addToHistoryTreatment() method + bolusInfo.carbTime = 0; + bolusInfo.carbs = 0; + } + TreatmentsPlugin.getPlugin().addToHistoryTreatment(bolusInfo, true); } catch (Exception e) { log.error("Adding treatment record failed", e); - if (dbi.isSMB) { + if (bolusInfo.isSMB) { Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); RxBus.INSTANCE.send(new EventNewNotification(notification)); } From 1e02773b71d0180bf30b6185c40b718ea268200f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 6 Mar 2020 20:27:39 +0100 Subject: [PATCH 035/100] fire immediatelly TreatmentChange if not from NS --- .../plugins/treatments/TreatmentService.java | 66 ++++++++++++------- 1 file changed, 41 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 1331c8eedf..1b118da1d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -160,7 +160,7 @@ public class TreatmentService extends OrmLiteBaseService { } catch (SQLException e) { log.error("Unhandled exception", e); } - scheduleTreatmentChange(null); + scheduleTreatmentChange(null, true); } @@ -208,18 +208,30 @@ public class TreatmentService extends OrmLiteBaseService { /** * Schedule a foodChange Event. */ - public void scheduleTreatmentChange(@Nullable final Treatment treatment) { - this.scheduleEvent(new EventReloadTreatmentData(new EventTreatmentChange(treatment)), treatmentEventWorker, new ICallback() { - @Override - public void setPost(ScheduledFuture post) { - scheduledTreatmentEventPost = post; + public void scheduleTreatmentChange(@Nullable final Treatment treatment, boolean runImmediately) { + if (runImmediately) { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Firing EventReloadTreatmentData"); + RxBus.INSTANCE.send(new EventReloadTreatmentData(new EventTreatmentChange(treatment))); + if (DatabaseHelper.earliestDataChange != null) { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Firing EventNewHistoryData"); + RxBus.INSTANCE.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); } + DatabaseHelper.earliestDataChange = null; + } else { + this.scheduleEvent(new EventReloadTreatmentData(new EventTreatmentChange(treatment)), treatmentEventWorker, new ICallback() { + @Override + public void setPost(ScheduledFuture post) { + scheduledTreatmentEventPost = post; + } - @Override - public ScheduledFuture getPost() { - return scheduledTreatmentEventPost; - } - }); + @Override + public ScheduledFuture getPost() { + return scheduledTreatmentEventPost; + } + }); + } } public List getTreatmentData() { @@ -294,7 +306,7 @@ public class TreatmentService extends OrmLiteBaseService { getDao().create(existingTreatment); DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(sameSource, false); //updating a pump treatment with another one from the pump is not counted as clash } return new UpdateReturn(equalRePumpHistory, false); @@ -318,14 +330,14 @@ public class TreatmentService extends OrmLiteBaseService { getDao().create(existingTreatment); DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(equalRePumpHistory || sameSource, false); } getDao().create(treatment); if (L.isEnabled(L.DATATREATMENTS)) log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, true); } if (treatment.source == Source.NIGHTSCOUT) { @@ -343,7 +355,7 @@ public class TreatmentService extends OrmLiteBaseService { DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(old.date); } - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, false); return new UpdateReturn(true, true); } if (L.isEnabled(L.DATATREATMENTS)) @@ -366,7 +378,7 @@ public class TreatmentService extends OrmLiteBaseService { DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(old.date); } - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, false); return new UpdateReturn(true, true); } if (L.isEnabled(L.DATATREATMENTS)) @@ -378,7 +390,7 @@ public class TreatmentService extends OrmLiteBaseService { if (L.isEnabled(L.DATATREATMENTS)) log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, false); return new UpdateReturn(true, true); } if (treatment.source == Source.USER) { @@ -386,7 +398,7 @@ public class TreatmentService extends OrmLiteBaseService { if (L.isEnabled(L.DATATREATMENTS)) log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, true); } } catch (SQLException e) { @@ -414,7 +426,7 @@ public class TreatmentService extends OrmLiteBaseService { if (L.isEnabled(L.DATATREATMENTS)) log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, true); } else { @@ -428,7 +440,7 @@ public class TreatmentService extends OrmLiteBaseService { } getDao().update(existingTreatment); DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, false); } else { if (MedtronicHistoryData.doubleBolusDebug) @@ -439,7 +451,7 @@ public class TreatmentService extends OrmLiteBaseService { optionalTreatmentCopy(existingTreatment, treatment, fromNightScout); getDao().create(existingTreatment); DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, false); //updating a pump treatment with another one from the pump is not counted as clash } } @@ -626,9 +638,13 @@ public class TreatmentService extends OrmLiteBaseService { if (stored != null) { if (L.isEnabled(L.DATATREATMENTS)) log.debug("Removing Treatment record from database: " + stored.toString()); - delete(stored); + try { + getDao().delete(stored); + } catch (SQLException e) { + log.error("Unhandled exception", e); + } DatabaseHelper.updateEarliestDataChange(stored.date); - scheduleTreatmentChange(null); + this.scheduleTreatmentChange(stored, false); } } @@ -643,7 +659,7 @@ public class TreatmentService extends OrmLiteBaseService { try { getDao().delete(treatment); DatabaseHelper.updateEarliestDataChange(treatment.date); - this.scheduleTreatmentChange(treatment); + this.scheduleTreatmentChange(treatment, true); } catch (SQLException e) { log.error("Unhandled exception", e); } @@ -656,7 +672,7 @@ public class TreatmentService extends OrmLiteBaseService { } catch (SQLException e) { log.error("Unhandled exception", e); } - scheduleTreatmentChange(treatment); + scheduleTreatmentChange(treatment, true); } /** From 8799c30b8e83379f23e922366bb1e305fa3372a1 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 6 Mar 2020 23:43:29 +0100 Subject: [PATCH 036/100] ActionLoopDisableTest --- .../androidaps/data/PumpEnactResult.java | 84 +++++++++---------- .../dependencyInjection/AppComponent.kt | 2 + .../dependencyInjection/AppModule.kt | 3 + .../actions/ActionLoopDisableTest.kt | 27 +++--- 4 files changed, 63 insertions(+), 53 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index 8563bfbe17..edfe7cfc35 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -2,18 +2,18 @@ package info.nightscout.androidaps.data; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; +import javax.inject.Inject; + import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.Round; +import info.nightscout.androidaps.utils.resources.ResourceHelper; public class PumpEnactResult { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.APS); + @Inject AAPSLogger aapsLogger; + @Inject ResourceHelper resourceHelper; public boolean success = false; // request was processed successfully (but possible no change was needed) public boolean enacted = false; // request was processed successfully and change has been made @@ -47,7 +47,7 @@ public class PumpEnactResult { } public PumpEnactResult comment(int comment) { - this.comment = MainApp.gs(comment); + this.comment = resourceHelper.gs(comment); return this; } @@ -106,66 +106,66 @@ public class PumpEnactResult { } public String toString() { - String ret = MainApp.gs(R.string.success) + ": " + success; + String ret = resourceHelper.gs(R.string.success) + ": " + success; if (enacted) { if (bolusDelivered > 0) { - ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted; - ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "\n" + MainApp.gs(R.string.configbuilder_insulin) - + ": " + bolusDelivered + " " + MainApp.gs(R.string.insulin_unit_shortname); + ret += "\n" + resourceHelper.gs(R.string.enacted) + ": " + enacted; + ret += "\n" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "\n" + resourceHelper.gs(R.string.configbuilder_insulin) + + ": " + bolusDelivered + " " + resourceHelper.gs(R.string.insulin_unit_shortname); } else if (isTempCancel) { - ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted; + ret += "\n" + resourceHelper.gs(R.string.enacted) + ": " + enacted; if (!comment.isEmpty()) - ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "\n" + MainApp.gs(R.string.canceltemp); + ret += "\n" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "\n" + resourceHelper.gs(R.string.canceltemp); } else if (isPercent) { - ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted; + ret += "\n" + resourceHelper.gs(R.string.enacted) + ": " + enacted; if (!comment.isEmpty()) - ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "\n" + MainApp.gs(R.string.duration) + ": " + duration + " min"; - ret += "\n" + MainApp.gs(R.string.percent) + ": " + percent + "%"; + ret += "\n" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "\n" + resourceHelper.gs(R.string.duration) + ": " + duration + " min"; + ret += "\n" + resourceHelper.gs(R.string.percent) + ": " + percent + "%"; } else { - ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted; + ret += "\n" + resourceHelper.gs(R.string.enacted) + ": " + enacted; if (!comment.isEmpty()) - ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "\n" + MainApp.gs(R.string.duration) + ": " + duration + " min"; - ret += "\n" + MainApp.gs(R.string.absolute) + ": " + absolute + " U/h"; + ret += "\n" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "\n" + resourceHelper.gs(R.string.duration) + ": " + duration + " min"; + ret += "\n" + resourceHelper.gs(R.string.absolute) + ": " + absolute + " U/h"; } } else { - ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment; + ret += "\n" + resourceHelper.gs(R.string.comment) + ": " + comment; } return ret; } public String toHtml() { - String ret = "" + MainApp.gs(R.string.success) + ": " + success; + String ret = "" + resourceHelper.gs(R.string.success) + ": " + success; if (queued) { - ret = MainApp.gs(R.string.waitingforpumpresult); + ret = resourceHelper.gs(R.string.waitingforpumpresult); } else if (enacted) { if (bolusDelivered > 0) { - ret += "
" + MainApp.gs(R.string.enacted) + ": " + enacted; + ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted; if (!comment.isEmpty()) - ret += "
" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "
" + MainApp.gs(R.string.smb_shortname) + ": " + bolusDelivered + " " + MainApp.gs(R.string.insulin_unit_shortname); + ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "
" + resourceHelper.gs(R.string.smb_shortname) + ": " + bolusDelivered + " " + resourceHelper.gs(R.string.insulin_unit_shortname); } else if (isTempCancel) { - ret += "
" + MainApp.gs(R.string.enacted) + ": " + enacted; - ret += "
" + MainApp.gs(R.string.comment) + ": " + comment + - "
" + MainApp.gs(R.string.canceltemp); + ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted; + ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment + + "
" + resourceHelper.gs(R.string.canceltemp); } else if (isPercent && percent != -1) { - ret += "
" + MainApp.gs(R.string.enacted) + ": " + enacted; + ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted; if (!comment.isEmpty()) - ret += "
" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "
" + MainApp.gs(R.string.duration) + ": " + duration + " min"; - ret += "
" + MainApp.gs(R.string.percent) + ": " + percent + "%"; + ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "
" + resourceHelper.gs(R.string.duration) + ": " + duration + " min"; + ret += "
" + resourceHelper.gs(R.string.percent) + ": " + percent + "%"; } else if (absolute != -1) { - ret += "
" + MainApp.gs(R.string.enacted) + ": " + enacted; + ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted; if (!comment.isEmpty()) - ret += "
" + MainApp.gs(R.string.comment) + ": " + comment; - ret += "
" + MainApp.gs(R.string.duration) + ": " + duration + " min"; - ret += "
" + MainApp.gs(R.string.absolute) + ": " + DecimalFormatter.to2Decimal(absolute) + " U/h"; + ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment; + ret += "
" + resourceHelper.gs(R.string.duration) + ": " + duration + " min"; + ret += "
" + resourceHelper.gs(R.string.absolute) + ": " + DecimalFormatter.to2Decimal(absolute) + " U/h"; } } else { - ret += "
" + MainApp.gs(R.string.comment) + ": " + comment; + ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment; } return ret; } @@ -188,7 +188,7 @@ public class PumpEnactResult { result.put("duration", duration); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return result; } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index e9a8590cfe..1bf03a66e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -6,6 +6,7 @@ import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* @@ -38,6 +39,7 @@ import javax.inject.Singleton interface AppComponent : AndroidInjector { fun injectProfileStore(profileStore: ProfileStore) + fun injectPumpEnactResult(pumpEnactResult: PumpEnactResult) fun injectCommandQueue(commandQueue: CommandQueue) fun injectCommandBolus(commandBolus: CommandBolus) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 047123fe5f..fdcf2ad72b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -10,6 +10,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider @@ -78,6 +79,8 @@ open class AppModule { @ContributesAndroidInjector fun profileStoreInjector(): ProfileStore + @ContributesAndroidInjector fun pumpEnactResultInjector(): PumpEnactResult + @ContributesAndroidInjector fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt index 5860823475..a96800345b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt @@ -25,24 +25,23 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner +@RunWith(PowerMockRunner::class) +@PrepareForTest(VirtualPumpPlugin::class, RxBusWrapper::class) class ActionLoopDisableTest : TestBase() { @Mock lateinit var rxBus: RxBusWrapper @Mock lateinit var sp: SP - @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var resourceHelper: ResourceHelper - @Mock lateinit var profileFunction: ProfileFunction - @Mock lateinit var context: Context @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin - @Mock lateinit var lazyActionStringHandler: Lazy - @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Mock lateinit var loopPlugin: LoopPlugin lateinit var sut: ActionLoopDisable @@ -54,6 +53,8 @@ class ActionLoopDisableTest : TestBase() { val pumpDescription = PumpDescription().apply { isTempBasalCapable = true } `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) `when`(configBuilderPlugin.activePump).thenReturn(virtualPumpPlugin) + `when`(resourceHelper.gs(R.string.disableloop)).thenReturn("Disable loop") + `when`(resourceHelper.gs(R.string.alreadydisabled)).thenReturn("Disable loop") sut = ActionLoopDisable(HasAndroidInjector { AndroidInjector { Unit } }) // do nothing injector .also { // inject the mocks @@ -65,19 +66,23 @@ class ActionLoopDisableTest : TestBase() { } } - @Test fun friendlyNameTest() { + @Test + fun friendlyNameTest() { Assert.assertEquals(R.string.disableloop.toLong(), sut.friendlyName().toLong()) } - @Test fun shortDescriptionTest() { + @Test + fun shortDescriptionTest() { Assert.assertEquals("Disable loop", sut.shortDescription()) } - @Test fun iconTest() { - Assert.assertEquals(Optional.of(R.drawable.ic_stop_24dp), sut.icon()) + @Test + fun iconTest() { + Assert.assertEquals(R.drawable.ic_stop_24dp, sut.icon()) } - @Test fun doActionTest() { + @Test + fun doActionTest() { sut.doAction(object : Callback() { override fun run() {} }) From 93820634b58cc4d55aa2f4c590c409d7b7281163 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 7 Mar 2020 00:43:28 +0100 Subject: [PATCH 037/100] AbstractSensitivityPluginTest --- .../AbstractSensitivityPlugin.java | 73 ------------------- .../sensitivity/AbstractSensitivityPlugin.kt | 58 +++++++++++++++ .../sensitivity/SensitivityAAPSPlugin.java | 47 +++++------- .../sensitivity/SensitivityOref0Plugin.java | 53 +++++++------- .../sensitivity/SensitivityOref1Plugin.java | 41 ++++------- .../SensitivityWeightedAveragePlugin.java | 65 ++++++++--------- .../AbstractSensitivityPluginTest.java | 63 ---------------- .../AbstractSensitivityPluginTest.kt | 47 ++++++++++++ 8 files changed, 197 insertions(+), 250 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt delete mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.java create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java deleted file mode 100644 index 6c8f061417..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.java +++ /dev/null @@ -1,73 +0,0 @@ -package info.nightscout.androidaps.plugins.sensitivity; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.SensitivityInterface; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.utils.Round; -import info.nightscout.androidaps.utils.SP; -import info.nightscout.androidaps.utils.SafeParse; -import info.nightscout.androidaps.utils.resources.ResourceHelper; - -public abstract class AbstractSensitivityPlugin extends PluginBase implements SensitivityInterface { - - private static final Logger log = StacktraceLoggerWrapper.getLogger(L.AUTOSENS); - - public AbstractSensitivityPlugin(PluginDescription pluginDescription, AAPSLogger aapsLogger, ResourceHelper resourceHelper) { - super(pluginDescription, aapsLogger, resourceHelper); - } - - @Override - public abstract AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime); - - AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, - String ratioLimit, String sensResult, int deviationsArraySize) { - return this.fillResult(ratio, carbsAbsorbed, pastSensitivity, ratioLimit, sensResult, - deviationsArraySize, - SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_min, "0.7")), - SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_max, "1.2"))); - } - - public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, - String ratioLimit, String sensResult, int deviationsArraySize, - double ratioMin, double ratioMax) { - double rawRatio = ratio; - ratio = Math.max(ratio, ratioMin); - ratio = Math.min(ratio, ratioMax); - - //If not-excluded data <= MIN_HOURS -> don't do Autosens - //If not-excluded data >= MIN_HOURS_FULL_AUTOSENS -> full Autosens - //Between MIN_HOURS and MIN_HOURS_FULL_AUTOSENS: gradually increase autosens - double autosensContrib = (Math.min(Math.max(MIN_HOURS, deviationsArraySize / 12d), - MIN_HOURS_FULL_AUTOSENS) - MIN_HOURS) / (MIN_HOURS_FULL_AUTOSENS - MIN_HOURS); - ratio = autosensContrib * (ratio - 1) + 1; - - if (autosensContrib != 1d) { - ratioLimit += "(" + deviationsArraySize + " of " + MIN_HOURS_FULL_AUTOSENS * 12 + " values) "; - } - - if (ratio != rawRatio) { - ratioLimit += "Ratio limited from " + rawRatio + " to " + ratio; - if (L.isEnabled(L.AUTOSENS)) - log.debug(ratioLimit); - } - - AutosensResult output = new AutosensResult(); - output.ratio = Round.roundTo(ratio, 0.01); - output.carbsAbsorbed = Round.roundTo(carbsAbsorbed, 0.01); - output.pastSensitivity = pastSensitivity; - output.ratioLimit = ratioLimit; - output.sensResult = sensResult; - return output; - } - - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt new file mode 100644 index 0000000000..540f669e02 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt @@ -0,0 +1,58 @@ +package info.nightscout.androidaps.plugins.sensitivity + +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.SensitivityInterface +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin +import info.nightscout.androidaps.utils.Round +import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP + +abstract class AbstractSensitivityPlugin(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, val sp: SP) : PluginBase(pluginDescription, aapsLogger, resourceHelper), SensitivityInterface { + + abstract override fun detectSensitivity(plugin: IobCobCalculatorPlugin, fromTime: Long, toTime: Long): AutosensResult + + fun fillResult(ratio: Double, carbsAbsorbed: Double, pastSensitivity: String, + ratioLimit: String, sensResult: String, deviationsArraySize: Int): AutosensResult { + return fillResult(ratio, carbsAbsorbed, pastSensitivity, ratioLimit, sensResult, + deviationsArraySize, + SafeParse.stringToDouble(sp.getString(R.string.key_openapsama_autosens_min, "0.7")), + SafeParse.stringToDouble(sp.getString(R.string.key_openapsama_autosens_max, "1.2"))) + } + + fun fillResult(ratio: Double, carbsAbsorbed: Double, pastSensitivity: String, + ratioLimit: String, sensResult: String, deviationsArraySize: Int, + ratioMin: Double, ratioMax: Double): AutosensResult { + var ratio = ratio + var ratioLimit = ratioLimit + val rawRatio = ratio + ratio = Math.max(ratio, ratioMin) + ratio = Math.min(ratio, ratioMax) + + //If not-excluded data <= MIN_HOURS -> don't do Autosens + //If not-excluded data >= MIN_HOURS_FULL_AUTOSENS -> full Autosens + //Between MIN_HOURS and MIN_HOURS_FULL_AUTOSENS: gradually increase autosens + val autosensContrib = (Math.min(Math.max(SensitivityInterface.MIN_HOURS, deviationsArraySize / 12.0), + SensitivityInterface.MIN_HOURS_FULL_AUTOSENS) - SensitivityInterface.MIN_HOURS) / (SensitivityInterface.MIN_HOURS_FULL_AUTOSENS - SensitivityInterface.MIN_HOURS) + ratio = autosensContrib * (ratio - 1) + 1 + if (autosensContrib != 1.0) { + ratioLimit += "(" + deviationsArraySize + " of " + SensitivityInterface.MIN_HOURS_FULL_AUTOSENS * 12 + " values) " + } + if (ratio != rawRatio) { + ratioLimit += "Ratio limited from $rawRatio to $ratio" + aapsLogger.debug(LTag.AUTOSENS, ratioLimit) + } + val output = AutosensResult() + output.ratio = Round.roundTo(ratio, 0.01) + output.carbsAbsorbed = Round.roundTo(carbsAbsorbed, 0.01) + output.pastSensitivity = pastSensitivity + output.ratioLimit = ratioLimit + output.sensResult = sensResult + return output + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java index 81d58ba74d..321a75b6e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java @@ -2,12 +2,8 @@ package info.nightscout.androidaps.plugins.sensitivity; import androidx.collection.LongSparseArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; import java.util.List; import javax.inject.Inject; @@ -21,15 +17,14 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 24.06.2017. @@ -37,12 +32,14 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; @Singleton public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.AUTOSENS); + + private SP sp; @Inject public SensitivityAAPSPlugin( AAPSLogger aapsLogger, - ResourceHelper resourceHelper + ResourceHelper resourceHelper, + SP sp ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -50,38 +47,37 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_aaps), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, sp ); + this.sp = sp; } @Override public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - String age = SP.getString(R.string.key_age, ""); + String age = sp.getString(R.string.key_age, ""); int defaultHours = 24; if (age.equals(MainApp.gs(R.string.key_adult))) defaultHours = 24; if (age.equals(MainApp.gs(R.string.key_teenage))) defaultHours = 4; if (age.equals(MainApp.gs(R.string.key_child))) defaultHours = 4; - int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours); + int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours); Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { - log.error("No profile"); + getAapsLogger().error("No profile"); return new AutosensResult(); } if (autosensDataTable == null || autosensDataTable.size() < 4) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -146,8 +142,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { String ratioLimit = ""; String sensResult = ""; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Records: " + index + " " + pastSensitivity); + getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); @@ -163,18 +158,16 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { sensResult = "Sensitivity normal"; } - if (L.isEnabled(L.AUTOSENS)) - log.debug(sensResult); + getAapsLogger().debug(LTag.AUTOSENS, sensResult); AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, deviationsArray.size()); - if (L.isEnabled(L.AUTOSENS)) { - log.debug("Sensitivity to: {}, percentile: {} ratio: {} mealCOB: ", - new Date(toTime).toLocaleString(), - percentile, output.ratio, ratio, current.cob); - log.debug("Sensitivity to: deviations " + Arrays.toString(deviations)); - } + getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " + + DateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob); + getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: deviations " + Arrays.toString(deviations)); return output; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java index 6fe086d387..8575ef0056 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java @@ -1,13 +1,10 @@ package info.nightscout.androidaps.plugins.sensitivity; +import androidx.annotation.NonNull; import androidx.collection.LongSparseArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; import java.util.List; import javax.inject.Inject; @@ -21,26 +18,29 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 24.06.2017. */ @Singleton public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.AUTOSENS); + + private ProfileFunction profileFunction; @Inject public SensitivityOref0Plugin( AAPSLogger aapsLogger, - ResourceHelper resourceHelper + ResourceHelper resourceHelper, + SP sp, + ProfileFunction profileFunction ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -48,33 +48,32 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_oref0) .description(R.string.description_sensitivity_oref0), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, sp ); + this.profileFunction = profileFunction; } - @Override + @NonNull @Override public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); int hoursForDetection = 24; - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = profileFunction.getProfile(); if (profile == null) { - log.error("No profile"); + getAapsLogger().error("No profile"); return new AutosensResult(); } if (autosensDataTable == null || autosensDataTable.size() < 4) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -135,19 +134,17 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { double sens = profile.getIsfMgdl(); - double ratio = 1; + double ratio; String ratioLimit = ""; - String sensResult = ""; + String sensResult; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Records: " + index + " " + pastSensitivity); + getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); for (double i = 0.9; i > 0.1; i = i - 0.02) { if (IobCobCalculatorPlugin.percentile(deviations, (i + 0.02)) >= 0 && IobCobCalculatorPlugin.percentile(deviations, i) < 0) { - if (L.isEnabled(L.AUTOSENS)) - log.debug(Math.round(100 * i) + "% of non-meal deviations negative (target 45%-50%)"); + getAapsLogger().debug(LTag.AUTOSENS, Math.round(100 * i) + "% of non-meal deviations negative (target 45%-50%)"); } } double pSensitive = IobCobCalculatorPlugin.percentile(deviations, 0.50); @@ -165,17 +162,17 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { sensResult = "Sensitivity normal"; } - if (L.isEnabled(L.AUTOSENS)) - log.debug(sensResult); + getAapsLogger().debug(LTag.AUTOSENS, sensResult); ratio = 1 + (basalOff / profile.getMaxDailyBasal()); AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, deviationsArray.size()); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Sensitivity to: {} ratio: {} mealCOB: {}", - new Date(toTime).toLocaleString(), output.ratio, current.cob); + getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " + + DateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob); return output; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java index 8f47ae1757..6edc42ec91 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java @@ -2,12 +2,8 @@ package info.nightscout.androidaps.plugins.sensitivity; import androidx.collection.LongSparseArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; import java.util.List; import javax.inject.Inject; @@ -21,26 +17,26 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 19.06.2018. */ @Singleton public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.AUTOSENS); @Inject public SensitivityOref1Plugin( AAPSLogger aapsLogger, - ResourceHelper resourceHelper + ResourceHelper resourceHelper, + SP sp ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -49,7 +45,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { .enableByDefault(true) .preferencesId(R.xml.pref_absorption_oref1) .description(R.string.description_sensitivity_oref1), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, sp ); } @@ -62,21 +58,19 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { - log.error("No profile"); + getAapsLogger().error("No profile"); return new AutosensResult(); } if (autosensDataTable == null || autosensDataTable.size() < 4) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } // the current AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -135,12 +129,10 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { // when we have less than 8h worth of deviation data, add up to 90m of zero deviations // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely - if (L.isEnabled(L.AUTOSENS)) - log.debug("Using most recent " + deviationsArray.size() + " deviations"); + getAapsLogger().debug(LTag.AUTOSENS, "Using most recent " + deviationsArray.size() + " deviations"); if (deviationsArray.size() < 96) { int pad = (int) Math.round((1 - (double) deviationsArray.size() / 96) * 18); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Adding " + pad + " more zero deviations"); + getAapsLogger().debug(LTag.AUTOSENS, "Adding " + pad + " more zero deviations"); for (int d = 0; d < pad; d++) { //process.stderr.write("."); deviationsArray.add(0d); @@ -156,8 +148,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { String ratioLimit = ""; String sensResult = ""; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Records: " + index + " " + pastSensitivity); + getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); /* Not used in calculation @@ -187,17 +178,17 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { sensResult = "Sensitivity normal"; } - if (L.isEnabled(L.AUTOSENS)) - log.debug(sensResult); + getAapsLogger().debug(LTag.AUTOSENS, sensResult); ratio = 1 + (basalOff / profile.getMaxDailyBasal()); AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, deviationsArray.size()); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Sensitivity to: {} ratio: {} mealCOB: {}", - new Date(toTime).toLocaleString(), output.ratio, current.cob); + getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " + + DateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob); return output; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java index f02f73a120..3a560eca21 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java @@ -2,10 +2,6 @@ package info.nightscout.androidaps.plugins.sensitivity; import androidx.collection.LongSparseArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Date; import java.util.List; import javax.inject.Inject; @@ -19,27 +15,31 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 24.06.2017. */ @Singleton public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.AUTOSENS); + + private SP sp; + private ResourceHelper resourceHelper; + private ProfileFunction profileFunction; @Inject public SensitivityWeightedAveragePlugin( AAPSLogger aapsLogger, - ResourceHelper resourceHelper + ResourceHelper resourceHelper, + SP sp, + ProfileFunction profileFunction ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -47,39 +47,39 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_weighted_average), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, sp ); + this.sp = sp; + this.resourceHelper = resourceHelper; + this.profileFunction = profileFunction; } @Override public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - String age = SP.getString(R.string.key_age, ""); + String age = sp.getString(R.string.key_age, ""); int defaultHours = 24; - if (age.equals(MainApp.gs(R.string.key_adult))) defaultHours = 24; - if (age.equals(MainApp.gs(R.string.key_teenage))) defaultHours = 4; - if (age.equals(MainApp.gs(R.string.key_child))) defaultHours = 4; - int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours); + if (age.equals(resourceHelper.gs(R.string.key_adult))) defaultHours = 24; + if (age.equals(resourceHelper.gs(R.string.key_teenage))) defaultHours = 4; + if (age.equals(resourceHelper.gs(R.string.key_child))) defaultHours = 4; + int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours); if (autosensDataTable == null || autosensDataTable.size() < 4) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = profileFunction.getProfile(); if (profile == null) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("No profile available"); + getAapsLogger().debug(LTag.AUTOSENS, "No profile available"); return new AutosensResult(); } @@ -143,12 +143,10 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin } if (data.size() == 0) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); + getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); return new AutosensResult(); } else { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); + getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); } double weightedsum = 0; @@ -172,8 +170,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin String ratioLimit = ""; String sensResult; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Records: " + index + " " + pastSensitivity); + getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); double average = weightedsum / weights; double basalOff = average * (60 / 5.0) / sens; @@ -187,15 +184,15 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin sensResult = "Sensitivity normal"; } - if (L.isEnabled(L.AUTOSENS)) - log.debug(sensResult); + getAapsLogger().debug(LTag.AUTOSENS, sensResult); AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, data.size()); - if (L.isEnabled(L.AUTOSENS)) - log.debug("Sensitivity to: {} weightedaverage: {} ratio: {} mealCOB: {}", new Date(toTime).toLocaleString(), - average, output.ratio, current.cob); + getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " + + DateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob); return output; } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.java deleted file mode 100644 index 4a7fba4287..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package info.nightscout.androidaps.plugins.sensitivity; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import info.AAPSMocker; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, SP.class}) -public class AbstractSensitivityPluginTest { - - private class SensitivityTestClass extends AbstractSensitivityPlugin { - - public SensitivityTestClass() { - super(null); - } - - public SensitivityTestClass(PluginDescription pluginDescription) { - super(pluginDescription); - } - - @Override - public AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime) { - return null; - } - } - - @Test - public void fillResultTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - - SensitivityTestClass sut = new SensitivityTestClass(); - - AutosensResult ar = sut.fillResult(1d, 1d, "1", - "1.2", "1", 12, 0.7d, 1.2d); - assertEquals(1, ar.ratio, 0.01); - - ar = sut.fillResult(1.2d, 1d, "1", - "1.2", "1", 40, 0.7d, 1.2d); - assertEquals(1.16, ar.ratio, 0.01); - - ar = sut.fillResult(1.2d, 1d, "1", - "1.2", "1", 50, 0.7d, 1.2d); - assertEquals(1.2, ar.ratio, 0.01); - - ar = sut.fillResult(1.2d, 1d, "1", - "1.2", "1", 50, 0.7d, 1.1d); - assertEquals(1.1, ar.ratio, 0.01); - } - - -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt new file mode 100644 index 0000000000..9bc37ae383 --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.plugins.sensitivity + +import info.TestBase +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.powermock.modules.junit4.PowerMockRunner + +@RunWith(PowerMockRunner::class) +class AbstractSensitivityPluginTest : TestBase() { + + @Mock lateinit var pluginDescription: PluginDescription + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var sp: SP + + private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, sp: SP) : AbstractSensitivityPlugin(pluginDescription, aapsLogger, resourceHelper, sp) { + + override fun detectSensitivity(plugin: IobCobCalculatorPlugin, fromTime: Long, toTime: Long): AutosensResult { + return AutosensResult() + } + } + + @Test + fun fillResultTest() { + val sut = SensitivityTestClass(pluginDescription, aapsLogger, resourceHelper, sp) + var ar = sut.fillResult(1.0, 1.0, "1", + "1.2", "1", 12, 0.7, 1.2) + Assert.assertEquals(1.0, ar.ratio, 0.01) + ar = sut.fillResult(1.2, 1.0, "1", + "1.2", "1", 40, 0.7, 1.2) + Assert.assertEquals(1.16, ar.ratio, 0.01) + ar = sut.fillResult(1.2, 1.0, "1", + "1.2", "1", 50, 0.7, 1.2) + Assert.assertEquals(1.2, ar.ratio, 0.01) + ar = sut.fillResult(1.2, 1.0, "1", + "1.2", "1", 50, 0.7, 1.1) + Assert.assertEquals(1.1, ar.ratio, 0.01) + } +} \ No newline at end of file From a3ee216b215eafe9137bb26ad7c2e9d7057cf3f8 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 7 Mar 2020 17:34:39 +0100 Subject: [PATCH 038/100] New Crowdin translations (#2485) * New translations strings.xml (Italian) * New translations strings.xml (Italian) * New translations strings.xml (Italian) * New translations strings.xml (French) * New translations strings.xml (Italian) * New translations objectives.xml (Italian) * New translations strings.xml (Italian) * New translations insight_alert_titles.xml (Italian) * New translations insight_exceptions.xml (Italian) * New translations strings.xml (Italian) --- app/src/main/res/values-fr-rFR/strings.xml | 4 ++-- .../values-it-rIT/insight_alert_titles.xml | 4 ++-- .../res/values-it-rIT/insight_exceptions.xml | 5 ++-- app/src/main/res/values-it-rIT/objectives.xml | 2 +- app/src/main/res/values-it-rIT/strings.xml | 24 +++++++++---------- 5 files changed, 19 insertions(+), 20 deletions(-) diff --git a/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml index 269ec85497..5dc5649fca 100644 --- a/app/src/main/res/values-fr-rFR/strings.xml +++ b/app/src/main/res/values-fr-rFR/strings.xml @@ -1425,10 +1425,10 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Âge invalide Poids invalide %1$s: ∑: %2$.2f Bol: %3$.2f Bas: %4$.2f]]> - %1$s: Bas: %2$02d%% Médian: %3$02d%% Haut: %4$02d%%]]> + %1$s: Bas: %2$02d%% Cible: %3$02d%% Haut: %4$02d%%]]> Moyenne DTI - TIR + Cible Gly Moniteur d\'activité Voulez-vous réinitialiser les stats d\'activité ? Statistiques diff --git a/app/src/main/res/values-it-rIT/insight_alert_titles.xml b/app/src/main/res/values-it-rIT/insight_alert_titles.xml index 0e3e09339f..123334b48d 100644 --- a/app/src/main/res/values-it-rIT/insight_alert_titles.xml +++ b/app/src/main/res/values-it-rIT/insight_alert_titles.xml @@ -9,8 +9,8 @@ Batteria quasi scarica Ora/data non valida Fine della garanzia - TBR annullato - Bolo annullato + TBR cancellato + Bolo cancellato Avviso di prestito Cartuccia non inserita Cartuccia vuota diff --git a/app/src/main/res/values-it-rIT/insight_exceptions.xml b/app/src/main/res/values-it-rIT/insight_exceptions.xml index fa33f5f7f2..fc68ba559f 100644 --- a/app/src/main/res/values-it-rIT/insight_exceptions.xml +++ b/app/src/main/res/values-it-rIT/insight_exceptions.xml @@ -1,5 +1,4 @@ - Connessione fallita Connessione persa @@ -7,9 +6,9 @@ Creazione socket fallita Timeout Numero massimo tipo di bolo già in esecuzione - Nessun TBR attivo da annullare + Nessun TBR attivo da cancellare Nessun TBR attivo da modificare - Nessun bolo da annullare + Nessun bolo da cancellare Micro già in questo stato Modalità di esecuzione non consentita diff --git a/app/src/main/res/values-it-rIT/objectives.xml b/app/src/main/res/values-it-rIT/objectives.xml index b34fde69ad..d8026431c0 100644 --- a/app/src/main/res/values-it-rIT/objectives.xml +++ b/app/src/main/res/values-it-rIT/objectives.xml @@ -24,7 +24,7 @@ Glicemia disponibile in NS Stato micro disponibile in NS Attivazioni manuali - Compiuto: %1$s + Completato: %1$s Impara a controllare AndroidAPS Esegui varie azioni in AndroidAPS Imposta il profilo \"90%\" per 10 min (premi a lungo sul nome profilo nella sezione Panoramica) diff --git a/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/values-it-rIT/strings.xml index 1d1fdc86ed..191ec45424 100644 --- a/app/src/main/res/values-it-rIT/strings.xml +++ b/app/src/main/res/values-it-rIT/strings.xml @@ -119,7 +119,7 @@ Trattamenti Quale plugin dovrebbe essere utilizzato per la gestione del trattamento? Profilo - Quale profilo dovrebbe usare AndroidAPS? + Quale profilo AndroidAPS dovrebbe usare? APS Quale algoritmo APS dovrebbe apportare aggiustamenti terapeutici? Generale @@ -247,7 +247,7 @@ OK Percentuale Assoluto - Cancellare basale temporanea + Cancella basale temporanea Comunicazioni SMS In attesa del risultato Numeri di telefono consentiti @@ -343,8 +343,8 @@ Per stoppare il bolo esteso rispondi col codice %1$s Basale temporanea cancellata Bolo esteso cancellato - Cancellazione basale temporanea fallita - Cancellazione bolo esteso fallita + Basale temporanea: cancellazione fallita + Bolo esteso: cancellazione fallita Comando sconosciuto o risposta errata Calcolatore Rapido Impostazioni Calcolatore Rapido @@ -638,8 +638,8 @@ Abilita SMB Utilizza Super Micro Boli al posto della basale temporanea per un\'azione più veloce Rilevazione dei pasti Non Annunciati - Momento picco Curva IOB - Momento del picco [min] + Tempo picco Curva IOB + Tempo del picco [min] Free-Peak Oref Rapid-Acting Oref Ultra-Rapid Oref @@ -771,7 +771,7 @@ Normale Necessario aggiornare orologio micro Attenzione - Avviso TBR CANCELLATO confermato + Avviso TBR CANCELLATO: confermato Il micro potrebbe non essere raggiungibile. Nessun bolo erogato Erogazione bolo fallita. Sembra che nessun bolo sia stato erogato. Per sicurezza, controlla il micro per evitare un doppio bolo e se è tutto ok, erogalo di nuovo. Come protezione da eventuali \"bug\", i boli non vengono ripetuti automaticamente. Solo la quantità di %1$.2f U del bolo richiesto di %2$.2f U è stata erogata a causa di un errore. Controlla il micro per verificare quanto accaduto e intraprendi le azioni necessarie. @@ -890,7 +890,7 @@ Micro in pausa Max tempo assorbimento pasto [h] Tempo entro il quale ogni pasto si considera assorbito. Eventuali carboidrati rimanenti verranno tagliati fuori. - Offset + Tempo Finestre tratt.nto: mostra campo note Avanti Indietro @@ -1161,10 +1161,10 @@ vincolo di archiviazione interna Libera almeno %1$d MB dalla memoria interna! Loop disabilitato! Formato errato - Codice errato. Comando annullato. + Codice errato. Comando cancellato. Non configurato Cambio profilo creato - Tempo di ripetizione + Tempo ricorrente Ogni Mai %1$dmin @@ -1395,8 +1395,8 @@ %1$dg On Off - Cancella completato - Cancella avviato + Cancella completamento + Cancella avvio Rilevazione tempo Vuoi resettare l\'avvio dell\'obiettivo? Potresti perdere i tuoi progressi. Nessun micro selezionato From 07aa6f20394d1f8493b7f75020c6b22fc7ed2165 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 7 Mar 2020 20:18:52 +0100 Subject: [PATCH 039/100] fix LocalProfile upload --- .../androidaps/plugins/general/nsclient/NSUpload.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java index 0bc15d1d45..ab6cae3e71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java @@ -396,7 +396,7 @@ public class NSUpload { public static void uploadProfileStore(JSONObject profileStore) { if (SP.getBoolean(R.string.key_ns_uploadlocalprofile, false)) { - UploadQueue.add(new DbRequest("dbAdd", "profile", String.valueOf(profileStore))); + UploadQueue.add(new DbRequest("dbAdd", "profile", profileStore)); } } From 14bda9cf719770cdd3d638475190482254bfd0a6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 7 Mar 2020 20:37:08 +0100 Subject: [PATCH 040/100] hide overview_accepttempbutton by default --- app/src/main/res/layout/overview_fragment.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/res/layout/overview_fragment.xml b/app/src/main/res/layout/overview_fragment.xml index 467c8c171a..35ddd5eed4 100644 --- a/app/src/main/res/layout/overview_fragment.xml +++ b/app/src/main/res/layout/overview_fragment.xml @@ -477,7 +477,8 @@ app:layout_constraintBottom_toTopOf="@id/overview_buttons_layout" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" - app:layout_constraintTop_toBottomOf="@id/overview_toppart_scrollbar" /> + app:layout_constraintTop_toBottomOf="@id/overview_toppart_scrollbar" + android:visibility="gone"/> Date: Sat, 7 Mar 2020 20:50:49 +0100 Subject: [PATCH 041/100] scrollable buttons in landscape mode --- .../general/overview/OverviewFragment.java | 4 +- .../layout/overview_fragment_landscape.xml | 584 ++++++++++++++++++ 2 files changed, 586 insertions(+), 2 deletions(-) create mode 100644 app/src/main/res/layout/overview_fragment_landscape.xml diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 0976755f06..a00317eff3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -221,8 +221,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } else if (Config.NSCLIENT) { view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false); shorttextmode = true; - } else if (smallHeight || landscape) { // now testing the same layout for small displays as well - view = inflater.inflate(R.layout.overview_fragment, container, false); + } else if (smallHeight || landscape) { + view = inflater.inflate(R.layout.overview_fragment_landscape, container, false); } else { view = inflater.inflate(R.layout.overview_fragment, container, false); } diff --git a/app/src/main/res/layout/overview_fragment_landscape.xml b/app/src/main/res/layout/overview_fragment_landscape.xml new file mode 100644 index 0000000000..edaa1df7a5 --- /dev/null +++ b/app/src/main/res/layout/overview_fragment_landscape.xml @@ -0,0 +1,584 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From a53f173751d06b446dd581202abb02eedfa15869 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 8 Mar 2020 20:49:29 +0100 Subject: [PATCH 042/100] fix some warnings --- .../nightscout/androidaps/activities/SurveyActivity.kt | 2 +- .../general/automation/dialogs/EditActionDialog.kt | 8 ++++---- .../java/info/nightscout/androidaps/utils/OKDialog.kt | 2 -- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt index bf07eda9af..d72e43441e 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -84,7 +84,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { .addOnCompleteListener(this) { task -> if (task.isSuccessful) { log.debug("signInAnonymously:success") - val user = auth.currentUser // TODO: do we need this, seems unused? + // val user = auth.currentUser // TODO: do we need this, seems unused? val database = FirebaseDatabase.getInstance().reference database.child("survey").child(r.id).setValue(r) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt index e738b7f94c..63a053f29f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt @@ -44,11 +44,11 @@ class EditActionDialog : DialogFragmentWithDate() { return true } - override fun onSaveInstanceState(bundle: Bundle) { - super.onSaveInstanceState(bundle) + override fun onSaveInstanceState(savedInstanceState: Bundle) { + super.onSaveInstanceState(savedInstanceState) action?.let { - bundle.putInt("actionPosition", actionPosition) - bundle.putString("action", it.toJSON()) + savedInstanceState.putInt("actionPosition", actionPosition) + savedInstanceState.putString("action", it.toJSON()) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt b/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt index 1d22c380ca..830053bef0 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt @@ -62,13 +62,11 @@ object OKDialog { } @JvmStatic - @JvmOverloads fun showConfirmation(activity: Activity, message: String, ok: Runnable?) { showConfirmation(activity, MainApp.gs(R.string.confirmation), message, ok, null) } @JvmStatic - @JvmOverloads fun showConfirmation(activity: Activity, message: Spanned, ok: Runnable?) { showConfirmation(activity, MainApp.gs(R.string.confirmation), message, ok, null) } From 72ba6815d8f32efd642770a432c35a0979c98ca1 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 8 Mar 2020 22:42:36 +0100 Subject: [PATCH 043/100] More Injections --- .../activities/DialogAppCompatActivity.kt | 4 +- .../dependencyInjection/AppComponent.kt | 10 ++ .../dependencyInjection/AppModule.kt | 17 ++- .../androidaps/interfaces/Constraint.java | 54 +++---- .../androidaps/interfaces/PluginBase.kt | 4 +- .../androidaps/interfaces/PumpPluginBase.kt | 4 +- .../plugins/aps/loop/APSResult.java | 141 +++++++++--------- .../plugins/aps/loop/LoopFragment.kt | 4 +- .../plugins/aps/loop/LoopPlugin.java | 10 +- .../DetermineBasalAdapterAMAJS.java | 31 ++-- .../openAPSAMA/DetermineBasalResultAMA.java | 13 +- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 6 +- .../openAPSMA/DetermineBasalAdapterMAJS.java | 12 +- .../aps/openAPSMA/DetermineBasalResultMA.java | 13 +- .../aps/openAPSMA/OpenAPSMAPlugin.java | 6 +- .../DetermineBasalAdapterSMBJS.java | 41 ++--- .../openAPSSMB/DetermineBasalResultSMB.java | 20 +-- .../aps/openAPSSMB/OpenAPSSMBFragment.kt | 2 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 11 +- .../configBuilder/ConfigBuilderPlugin.java | 4 +- .../configBuilder/ConstraintChecker.kt | 10 -- .../constraints/dstHelper/DstHelperPlugin.kt | 6 +- .../objectives/ObjectivesPlugin.kt | 16 +- .../phoneChecker/PhoneCheckerPlugin.kt | 4 +- .../constraints/safety/SafetyPlugin.java | 86 ++++++----- .../SignatureVerifierPlugin.kt | 28 ++-- .../storage/StorageConstraintPlugin.kt | 6 +- .../versionChecker/VersionCheckerPlugin.kt | 8 +- .../plugins/general/actions/ActionsPlugin.kt | 8 +- .../general/automation/AutomationPlugin.kt | 5 +- .../general/careportal/CareportalPlugin.kt | 9 +- .../dataBroadcaster/DataBroadcastPlugin.kt | 4 +- .../plugins/general/food/FoodPlugin.kt | 8 +- .../general/maintenance/MaintenancePlugin.kt | 4 +- .../general/nsclient/NSClientPlugin.java | 7 +- .../general/nsclient/data/NSDeviceStatus.java | 5 +- .../general/overview/OverviewFragment.java | 4 +- .../general/overview/OverviewPlugin.kt | 5 +- .../PersistentNotificationPlugin.kt | 4 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 4 +- .../general/tidepool/TidepoolPlugin.kt | 4 +- .../plugins/general/wear/WearPlugin.kt | 4 +- .../xdripStatusline/StatusLinePlugin.kt | 8 +- .../plugins/insulin/InsulinOrefBasePlugin.kt | 4 +- .../insulin/InsulinOrefFreePeakPlugin.kt | 4 +- .../insulin/InsulinOrefRapidActingPlugin.kt | 4 +- .../InsulinOrefUltraRapidActingPlugin.kt | 4 +- .../iob/iobCobCalculator/AutosensData.java | 15 +- .../IobCobCalculatorPlugin.java | 2 +- .../profile/local/LocalProfilePlugin.kt | 6 +- .../plugins/profile/ns/NSProfilePlugin.kt | 5 +- .../plugins/pump/combo/ComboPlugin.java | 9 +- .../pump/common/PumpPluginAbstract.java | 5 +- .../pump/danaR/AbstractDanaRPlugin.java | 21 +-- .../plugins/pump/danaR/DanaRPlugin.java | 9 +- .../plugins/pump/danaR/DanaRPump.kt | 3 + .../pump/danaR/comm/MessageHashTableR.kt | 8 +- .../pump/danaR/comm/MsgBolusStart.java | 44 ------ .../plugins/pump/danaR/comm/MsgBolusStart.kt | 35 +++++ .../danaR/comm/MsgBolusStartWithSpeed.java | 45 ------ .../pump/danaR/comm/MsgBolusStartWithSpeed.kt | 37 +++++ .../danaR/comm/MsgSetExtendedBolusStart.java | 45 ------ .../danaR/comm/MsgSetExtendedBolusStart.kt | 37 +++++ .../danaR/services/DanaRExecutionService.java | 8 +- .../pump/danaRKorean/DanaRKoreanPlugin.java | 7 +- .../comm/MessageHashTableRKorean.kt | 6 +- .../danaRKorean/comm/MsgSettingBasal_k.kt | 1 - .../services/DanaRKoreanExecutionService.java | 6 +- .../plugins/pump/danaRS/DanaRSPlugin.java | 12 +- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 6 +- .../pump/danaRv2/comm/MessageHashTableRv2.kt | 8 +- .../services/DanaRv2ExecutionService.java | 8 +- .../pump/insight/LocalInsightPlugin.java | 13 +- .../plugins/pump/mdi/MDIPlugin.java | 5 +- .../pump/medtronic/MedtronicPumpPlugin.java | 5 +- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 4 +- .../sensitivity/AbstractSensitivityPlugin.kt | 26 +++- .../sensitivity/SensitivityAAPSPlugin.java | 4 +- .../sensitivity/SensitivityOref0Plugin.java | 4 +- .../sensitivity/SensitivityOref1Plugin.java | 4 +- .../SensitivityWeightedAveragePlugin.java | 4 +- .../androidaps/plugins/source/DexcomPlugin.kt | 6 +- .../plugins/source/EversensePlugin.kt | 5 +- .../androidaps/plugins/source/GlimpPlugin.kt | 5 +- .../androidaps/plugins/source/MM640gPlugin.kt | 5 +- .../plugins/source/NSClientSourcePlugin.kt | 5 +- .../plugins/source/PoctechPlugin.kt | 5 +- .../plugins/source/RandomBgPlugin.kt | 5 +- .../androidaps/plugins/source/TomatoPlugin.kt | 5 +- .../androidaps/plugins/source/XdripPlugin.kt | 5 +- .../plugins/treatments/TreatmentsPlugin.java | 20 +-- .../nightscout/androidaps/utils/OKDialog.kt | 24 ++- .../androidaps/utils/stats/TddCalculator.kt | 4 +- app/src/test/java/info/AAPSMocker.java | 8 - .../plugins/pump/danaRS/DanaRSPluginTest.kt | 8 +- 95 files changed, 681 insertions(+), 556 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/DialogAppCompatActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/DialogAppCompatActivity.kt index a1c6dd1236..e2aa70d960 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/DialogAppCompatActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/DialogAppCompatActivity.kt @@ -1,10 +1,10 @@ package info.nightscout.androidaps.activities import android.content.Context -import androidx.appcompat.app.AppCompatActivity +import dagger.android.support.DaggerAppCompatActivity import info.nightscout.androidaps.utils.LocaleHelper -open class DialogAppCompatActivity : AppCompatActivity() { +open class DialogAppCompatActivity : DaggerAppCompatActivity() { public override fun attachBaseContext(newBase: Context) { super.attachBaseContext(LocaleHelper.wrap(newBase)) } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 1bf03a66e9..9ab4df8497 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -8,7 +8,12 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.BgReading +import info.nightscout.androidaps.plugins.aps.loop.APSResult +import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA +import info.nightscout.androidaps.plugins.aps.openAPSMA.DetermineBasalResultMA import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* import info.nightscout.androidaps.plugins.general.automation.AutomationEvent import info.nightscout.androidaps.plugins.general.automation.actions.* @@ -40,6 +45,11 @@ interface AppComponent : AndroidInjector { fun injectProfileStore(profileStore: ProfileStore) fun injectPumpEnactResult(pumpEnactResult: PumpEnactResult) + fun injectAPSResult(apsResult: APSResult) + fun injectDetermineBasalResultSMB(determineBasalResultSMB: DetermineBasalResultSMB) + fun injectDetermineBasalResultMA(determineBasalResultMA: DetermineBasalResultMA) + fun injectDetermineBasalResultAMA(determineBasalResultAMA: DetermineBasalResultAMA) + fun injectDetermineBasalAdapterSMBJS(determineBasalAdapterSMBJS: DetermineBasalAdapterSMBJS) fun injectCommandQueue(commandQueue: CommandQueue) fun injectCommandBolus(commandBolus: CommandBolus) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index fdcf2ad72b..a70ce7bdd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -7,7 +7,6 @@ import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.PumpEnactResult @@ -15,9 +14,13 @@ import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.AAPSLoggerDebug import info.nightscout.androidaps.logging.AAPSLoggerProduction +import info.nightscout.androidaps.plugins.aps.loop.APSResult +import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA +import info.nightscout.androidaps.plugins.aps.openAPSMA.DetermineBasalResultMA import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation @@ -81,13 +84,21 @@ open class AppModule { @ContributesAndroidInjector fun pumpEnactResultInjector(): PumpEnactResult + @ContributesAndroidInjector fun apsResultInjector(): APSResult + @ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB + @ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA + @ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA + @ContributesAndroidInjector fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS + @ContributesAndroidInjector fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector fun commandBolusInjector(): CommandBolus + @ContributesAndroidInjector fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus @ContributesAndroidInjector fun commandCancelTempBasalInjector(): CommandCancelTempBasal @ContributesAndroidInjector fun commandExtendedBolusInjector(): CommandExtendedBolus + @ContributesAndroidInjector fun commandInsightSetTBROverNotificationInjector(): CommandInsightSetTBROverNotification @@ -123,6 +134,7 @@ open class AppModule { @ContributesAndroidInjector fun triggerIobInjector(): TriggerIob @ContributesAndroidInjector fun triggerLocationInjector(): TriggerLocation @ContributesAndroidInjector fun triggerProfilePercentInjector(): TriggerProfilePercent + @ContributesAndroidInjector fun triggerPumpLastConnectionInjector(): TriggerPumpLastConnection @@ -139,6 +151,7 @@ open class AppModule { @ContributesAndroidInjector fun actionLoopSuspendInjector(): ActionLoopSuspend @ContributesAndroidInjector fun actionNotificationInjector(): ActionNotification @ContributesAndroidInjector fun actionProfileSwitchInjector(): ActionProfileSwitch + @ContributesAndroidInjector fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java b/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java index 7f154e9804..11a7d7b699 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java @@ -1,26 +1,21 @@ package info.nightscout.androidaps.interfaces; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.List; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; /** * Created by mike on 19.03.2018. */ public class Constraint { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.CONSTRAINTS); + private T value; + private T originalValue; - T value; - T originalValue; - - List reasons = new ArrayList<>(); - List mostLimiting = new ArrayList<>(); + private List reasons = new ArrayList<>(); + private List mostLimiting = new ArrayList<>(); public Constraint(T value) { this.value = value; @@ -35,27 +30,24 @@ public class Constraint { return originalValue; } - public Constraint set(T value) { + public Constraint set(AAPSLogger aapsLogger, T value) { this.value = value; this.originalValue = value; - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Setting value " + value); + aapsLogger.debug(LTag.CONSTRAINTS, "Setting value " + value); return this; } - public Constraint set(T value, String reason, Object from) { - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); + public Constraint set(AAPSLogger aapsLogger, T value, String reason, Object from) { + aapsLogger.debug(LTag.CONSTRAINTS, "Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); this.value = value; addReason(reason, from); addMostLimingReason(reason, from); return this; } - public Constraint setIfDifferent(T value, String reason, Object from) { + public Constraint setIfDifferent(AAPSLogger aapsLogger, T value, String reason, Object from) { if (!this.value.equals(value)) { - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); + aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); this.value = value; addReason(reason, from); addMostLimingReason(reason, from); @@ -63,10 +55,9 @@ public class Constraint { return this; } - public Constraint setIfSmaller(T value, String reason, Object from) { + public Constraint setIfSmaller(AAPSLogger aapsLogger, T value, String reason, Object from) { if (value.compareTo(this.value) < 0) { - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); + aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); this.value = value; mostLimiting.clear(); addMostLimingReason(reason, from); @@ -77,10 +68,9 @@ public class Constraint { return this; } - public Constraint setIfGreater(T value, String reason, Object from) { + public Constraint setIfGreater(AAPSLogger aapsLogger, T value, String reason, Object from) { if (value.compareTo(this.value) > 0) { - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); + aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]"); this.value = value; mostLimiting.clear(); addMostLimingReason(reason, from); @@ -105,31 +95,29 @@ public class Constraint { return this; } - public String getReasons() { + public String getReasons(AAPSLogger aapsLogger) { StringBuilder sb = new StringBuilder(); int count = 0; for (String r : reasons) { if (count++ != 0) sb.append("\n"); sb.append(r); } - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); + aapsLogger.debug(LTag.CONSTRAINTS, "Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); return sb.toString(); } - public List getReasonList() { + private List getReasonList() { return reasons; } - public String getMostLimitedReasons() { + public String getMostLimitedReasons(AAPSLogger aapsLogger) { StringBuilder sb = new StringBuilder(); int count = 0; for (String r : mostLimiting) { if (count++ != 0) sb.append("\n"); sb.append(r); } - if (L.isEnabled(L.CONSTRAINTS)) - log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); + aapsLogger.debug(LTag.CONSTRAINTS, "Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); return sb.toString(); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt index 384d3731c3..316942f7fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.interfaces import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -12,7 +13,8 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper abstract class PluginBase( val pluginDescription: PluginDescription, val aapsLogger: AAPSLogger, - val resourceHelper: ResourceHelper + val resourceHelper: ResourceHelper, + val injector: HasAndroidInjector ) { enum class State { diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt index b72667f19b..c4e2384e90 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt @@ -1,15 +1,17 @@ package info.nightscout.androidaps.interfaces import android.os.SystemClock +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.utils.resources.ResourceHelper abstract class PumpPluginBase( pluginDescription: PluginDescription, + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, val commandQueue: CommandQueueProvider -) : PluginBase(pluginDescription, aapsLogger, resourceHelper) { +) : PluginBase(pluginDescription, aapsLogger, resourceHelper, injector) { override fun onStart() { super.onStart() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java index 7d091efbdc..0c91d0723c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java @@ -6,35 +6,47 @@ import android.text.Spanned; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; -import info.nightscout.androidaps.MainApp; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 09.06.2016. */ public class APSResult { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.APS); + @Inject public AAPSLogger aapsLogger; + @Inject ConstraintChecker constraintChecker; + @Inject SP sp; + @Inject ActivePluginProvider activePluginProvider; + @Inject TreatmentsPlugin treatmentsPlugin; + @Inject ProfileFunction profileFunction; + @Inject ResourceHelper resourceHelper; + + @Inject + public APSResult(HasAndroidInjector injector) { + injector.androidInjector().inject(this); + } public long date = 0; public String reason; @@ -88,68 +100,65 @@ public class APSResult { @Override public String toString() { - final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + final PumpInterface pump = activePluginProvider.getActivePump(); if (isChangeRequested()) { String ret; // rate if (rate == 0 && duration == 0) - ret = MainApp.gs(R.string.canceltemp) + "\n"; + ret = resourceHelper.gs(R.string.canceltemp) + "\n"; else if (rate == -1) - ret = MainApp.gs(R.string.let_temp_basal_run) + "\n"; + ret = resourceHelper.gs(R.string.let_temp_basal_run) + "\n"; else if (usePercent) - ret = MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent) + "% " + + ret = resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent) + "% " + "(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)\n" + - MainApp.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n"; + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n"; else - ret = MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + + ret = resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) \n" + - MainApp.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n"; + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n"; // smb if (smb != 0) ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U\n"); // reason - ret += MainApp.gs(R.string.reason) + ": " + reason; + ret += resourceHelper.gs(R.string.reason) + ": " + reason; return ret; } else - return MainApp.gs(R.string.nochangerequested); + return resourceHelper.gs(R.string.nochangerequested); } public Spanned toSpanned() { - final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + final PumpInterface pump = activePluginProvider.getActivePump(); if (isChangeRequested()) { String ret; // rate if (rate == 0 && duration == 0) - ret = MainApp.gs(R.string.canceltemp) + "
"; + ret = resourceHelper.gs(R.string.canceltemp) + "
"; else if (rate == -1) - ret = MainApp.gs(R.string.let_temp_basal_run) + "
"; + ret = resourceHelper.gs(R.string.let_temp_basal_run) + "
"; else if (usePercent) - ret = "" + MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent) + "% " + + ret = "" + resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent) + "% " + "(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)
" + - "" + MainApp.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min
"; + "" + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min
"; else - ret = "" + MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + + ret = "" + resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100d) + "%)
" + - "" + MainApp.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min
"; + "" + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min
"; // smb if (smb != 0) ret += ("" + "SMB" + ": " + DecimalFormatter.toPumpSupportedBolus(smb) + " U
"); // reason - ret += "" + MainApp.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">"); + ret += "" + resourceHelper.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">"); return Html.fromHtml(ret); } else - return Html.fromHtml(MainApp.gs(R.string.nochangerequested)); + return Html.fromHtml(resourceHelper.gs(R.string.nochangerequested)); } - public APSResult() { - } - - public APSResult clone() { - APSResult newResult = new APSResult(); + public APSResult newAndClone(HasAndroidInjector injector) { + APSResult newResult = new APSResult(injector); doClone(newResult); return newResult; } @@ -165,7 +174,7 @@ public class APSResult { try { newResult.json = new JSONObject(json.toString()); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } newResult.hasPredictions = hasPredictions; newResult.smb = smb; @@ -186,7 +195,7 @@ public class APSResult { json.put("reason", reason); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return json; } @@ -249,7 +258,7 @@ public class APSResult { } } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return array; } @@ -282,66 +291,60 @@ public class APSResult { } } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return latest; } public boolean isChangeRequested() { - Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); + Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); // closed loop mode: handle change at driver level if (closedLoopEnabled.value()) { - if (L.isEnabled(L.APS)) - log.debug("DEFAULT: Closed mode"); + aapsLogger.debug(LTag.APS, "DEFAULT: Closed mode"); return tempBasalRequested || bolusRequested; } // open loop mode: try to limit request if (!tempBasalRequested && !bolusRequested) { - if (L.isEnabled(L.APS)) - log.debug("FALSE: No request"); + aapsLogger.debug(LTag.APS, "FALSE: No request"); return false; } long now = System.currentTimeMillis(); - TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - Profile profile = ProfileFunctions.getInstance().getProfile(); + TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now); + PumpInterface pump = activePluginProvider.getActivePump(); + Profile profile = profileFunction.getProfile(); if (profile == null) { - log.error("FALSE: No Profile"); + aapsLogger.error("FALSE: No Profile"); return false; } if (usePercent) { if (activeTemp == null && percent == 100) { - if (L.isEnabled(L.APS)) - log.debug("FALSE: No temp running, asking cancel temp"); + aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp"); return false; } if (activeTemp != null && Math.abs(percent - activeTemp.tempBasalConvertedToPercent(now, profile)) < pump.getPumpDescription().basalStep) { - if (L.isEnabled(L.APS)) - log.debug("FALSE: Temp equal"); + aapsLogger.debug(LTag.APS, "FALSE: Temp equal"); return false; } // always report zerotemp if (percent == 0) { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Zero temp"); + aapsLogger.debug(LTag.APS, "TRUE: Zero temp"); return true; } // always report hightemp - if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) { + if (pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) { double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); if (percent == pumpLimit) { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Pump limit"); + aapsLogger.debug(LTag.APS, "TRUE: Pump limit"); return true; } } // report change bigger than 30% - double percentMinChangeChange = SP.getDouble(R.string.key_loop_openmode_min_change, 30d); + double percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30d); percentMinChangeChange /= 100d; double lowThreshold = 1 - percentMinChangeChange; double highThreshold = 1 + percentMinChangeChange; @@ -350,42 +353,36 @@ public class APSResult { change = percent / (double) activeTemp.tempBasalConvertedToPercent(now, profile); if (change < lowThreshold || change > highThreshold) { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Outside allowed range " + (change * 100d) + "%"); + aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + (change * 100d) + "%"); return true; } else { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Inside allowed range " + (change * 100d) + "%"); + aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + (change * 100d) + "%"); return false; } } else { if (activeTemp == null && rate == pump.getBaseBasalRate()) { - if (L.isEnabled(L.APS)) - log.debug("FALSE: No temp running, asking cancel temp"); + aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp"); return false; } if (activeTemp != null && Math.abs(rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) { - if (L.isEnabled(L.APS)) - log.debug("FALSE: Temp equal"); + aapsLogger.debug(LTag.APS, "FALSE: Temp equal"); return false; } // always report zerotemp if (rate == 0) { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Zero temp"); + aapsLogger.debug(LTag.APS, "TRUE: Zero temp"); return true; } // always report hightemp - if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { + if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); if (rate == pumpLimit) { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Pump limit"); + aapsLogger.debug(LTag.APS, "TRUE: Pump limit"); return true; } } // report change bigger than 30% - double percentMinChangeChange = SP.getDouble(R.string.key_loop_openmode_min_change, 30d); + double percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30d); percentMinChangeChange /= 100d; double lowThreshold = 1 - percentMinChangeChange; double highThreshold = 1 + percentMinChangeChange; @@ -394,12 +391,10 @@ public class APSResult { change = rate / activeTemp.tempBasalConvertedToAbsolute(now, profile); if (change < lowThreshold || change > highThreshold) { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Outside allowed range " + (change * 100d) + "%"); + aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + (change * 100d) + "%"); return true; } else { - if (L.isEnabled(L.APS)) - log.debug("TRUE: Inside allowed range " + (change * 100d) + "%"); + aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + (change * 100d) + "%"); return false; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index abef5de7de..5abe8c354b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt @@ -7,6 +7,7 @@ import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui import info.nightscout.androidaps.plugins.bus.RxBusWrapper @@ -22,6 +23,7 @@ import kotlinx.android.synthetic.main.loop_fragment.* import javax.inject.Inject class LoopFragment : DaggerFragment() { + @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @@ -96,7 +98,7 @@ class LoopFragment : DaggerFragment() { val allConstraints = Constraint(0.0) constraintsProcessed.rateConstraint?.let { rateConstraint -> allConstraints.copyReasons(rateConstraint) } constraintsProcessed.smbConstraint?.let { smbConstraint -> allConstraints.copyReasons(smbConstraint) } - allConstraints.mostLimitedReasons + allConstraints.getMostLimitedReasons(aapsLogger) } ?: "" loop_constraints?.text = constraints } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 89ffb05c70..7cca957301 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -22,6 +22,7 @@ import javax.inject.Inject; import javax.inject.Singleton; import dagger.Lazy; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -73,6 +74,7 @@ import io.reactivex.schedulers.Schedulers; @Singleton public class LoopPlugin extends PluginBase { + private final HasAndroidInjector injector; private final SP sp; private final RxBusWrapper rxBus; private final ConstraintChecker constraintChecker; @@ -114,6 +116,7 @@ public class LoopPlugin extends PluginBase { @Inject public LoopPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, SP sp, @@ -135,8 +138,9 @@ public class LoopPlugin extends PluginBase { .shortName(R.string.loop_shortname) .preferencesId(R.xml.pref_loop) .description(R.string.description_loop), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); + this.injector = injector; this.sp = sp; this.rxBus = rxBus; this.constraintChecker = constraintChecker; @@ -311,7 +315,7 @@ public class LoopPlugin extends PluginBase { Constraint loopEnabled = constraintChecker.isLoopInvocationAllowed(); if (!loopEnabled.value()) { - String message = resourceHelper.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); + String message = resourceHelper.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(getAapsLogger()); getAapsLogger().debug(LTag.APS, message); rxBus.send(new EventLoopSetLastRunGui(message)); return; @@ -355,7 +359,7 @@ public class LoopPlugin extends PluginBase { result.percent = (int) (result.rate / profile.getBasal() * 100); // check rate for constrais - final APSResult resultAfterConstraints = result.clone(); + final APSResult resultAfterConstraints = result.newAndClone(injector); resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate); resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java index ca0cee394d..62741c9b68 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java @@ -17,7 +17,9 @@ import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; +import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -34,13 +36,15 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; public class DetermineBasalAdapterAMAJS { - private final AAPSLogger aapsLogger; + private HasAndroidInjector injector; + @Inject AAPSLogger aapsLogger; + @Inject ConstraintChecker constraintChecker; + @Inject SP sp; - - private ScriptReader mScriptReader = null; + private ScriptReader mScriptReader; private JSONObject mProfile; private JSONObject mGlucoseStatus; @@ -58,9 +62,10 @@ public class DetermineBasalAdapterAMAJS { private String scriptDebug = ""; - public DetermineBasalAdapterAMAJS(ScriptReader scriptReader, AAPSLogger aapsLogger) { + DetermineBasalAdapterAMAJS(ScriptReader scriptReader, HasAndroidInjector injector) { + injector.androidInjector().inject(this); mScriptReader = scriptReader; - this.aapsLogger = aapsLogger; + this.injector = injector; } @Nullable @@ -125,7 +130,7 @@ public class DetermineBasalAdapterAMAJS { String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); aapsLogger.debug(LTag.APS, "Result: " + result); try { - determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result), aapsLogger); + determineBasalResultAMA = new DetermineBasalResultAMA(injector, jsResult, new JSONObject(result)); } catch (JSONException e) { aapsLogger.error(LTag.APS, "Unhandled exception", e); } @@ -204,17 +209,17 @@ public class DetermineBasalAdapterAMAJS { mProfile.put("target_bg", targetBg); mProfile.put("carb_ratio", profile.getIc()); mProfile.put("sens", profile.getIsfMgdl()); - mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)); - mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)); + mProfile.put("max_daily_safety_multiplier", sp.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)); + mProfile.put("current_basal_safety_multiplier", sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)); mProfile.put("skip_neutral_temps", true); mProfile.put("current_basal", basalrate); mProfile.put("temptargetSet", tempTargetSet); - mProfile.put("autosens_adjust_targets", SP.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true)); + mProfile.put("autosens_adjust_targets", sp.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true)); //align with max-absorption model in AMA sensitivity if (mealData.usedMinCarbsImpact > 0) { mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); } else { - mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); + mProfile.put("min_5m_carbimpact", sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); } if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) { @@ -240,7 +245,7 @@ public class DetermineBasalAdapterAMAJS { mGlucoseStatus = new JSONObject(); mGlucoseStatus.put("glucose", glucoseStatus.glucose); - if (SP.getBoolean(R.string.key_always_use_shortavg, false)) { + if (sp.getBoolean(R.string.key_always_use_shortavg, false)) { mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta); } else { mGlucoseStatus.put("delta", glucoseStatus.delta); @@ -253,7 +258,7 @@ public class DetermineBasalAdapterAMAJS { mMealData.put("boluses", mealData.boluses); mMealData.put("mealCOB", mealData.mealCOB); - if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { + if (constraintChecker.isAutosensModeEnabled().value()) { mAutosensData = new JSONObject(); mAutosensData.put("ratio", autosensDataRatio); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java index 3986be9117..0bf4839f84 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java @@ -4,6 +4,7 @@ import org.json.JSONException; import org.json.JSONObject; import org.mozilla.javascript.NativeObject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; @@ -15,8 +16,8 @@ public class DetermineBasalResultAMA extends APSResult { private double eventualBG; private double snoozeBG; - DetermineBasalResultAMA(NativeObject result, JSONObject j, AAPSLogger aapsLogger) { - this(aapsLogger); + DetermineBasalResultAMA(HasAndroidInjector injector, NativeObject result, JSONObject j) { + this(injector); date = DateUtil.now(); json = j; if (result.containsKey("error")) { @@ -47,14 +48,14 @@ public class DetermineBasalResultAMA extends APSResult { bolusRequested = false; } - private DetermineBasalResultAMA(AAPSLogger aapsLogger) { + private DetermineBasalResultAMA(HasAndroidInjector injector) { + super(injector); hasPredictions = true; - this.aapsLogger = aapsLogger; } @Override - public DetermineBasalResultAMA clone() { - DetermineBasalResultAMA newResult = new DetermineBasalResultAMA(aapsLogger); + public DetermineBasalResultAMA newAndClone(HasAndroidInjector injector) { + DetermineBasalResultAMA newResult = new DetermineBasalResultAMA(injector); doClone(newResult); newResult.eventualBG = eventualBG; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index a59f5f4eb7..68548b49a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -5,6 +5,7 @@ import org.json.JSONException; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -58,6 +59,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { @Inject public OpenAPSAMAPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ConstraintChecker constraintChecker, @@ -75,7 +77,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { .shortName(R.string.oaps_shortname) .preferencesId(R.xml.pref_openapsama) .description(R.string.description_ama), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); this.aapsLogger = aapsLogger; this.rxBus = rxBus; @@ -119,7 +121,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; - determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(mainApp), aapsLogger); + determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(mainApp), getInjector()); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java index 657d1baab6..183daa4c2a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java @@ -15,7 +15,9 @@ import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; +import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -33,7 +35,8 @@ import info.nightscout.androidaps.utils.SP; public class DetermineBasalAdapterMAJS { - private final AAPSLogger aapsLogger; + private HasAndroidInjector injector; + @Inject AAPSLogger aapsLogger; private ScriptReader mScriptReader; private JSONObject mProfile; private JSONObject mGlucoseStatus; @@ -47,9 +50,10 @@ public class DetermineBasalAdapterMAJS { private String storedProfile = null; private String storedMeal_data = null; - DetermineBasalAdapterMAJS(ScriptReader scriptReader, AAPSLogger aapsLogger) { + DetermineBasalAdapterMAJS(ScriptReader scriptReader, HasAndroidInjector injector) { + injector.androidInjector().inject(this); mScriptReader = scriptReader; - this.aapsLogger = aapsLogger; + this.injector = injector; } @Nullable @@ -105,7 +109,7 @@ public class DetermineBasalAdapterMAJS { if (L.isEnabled(L.APS)) aapsLogger.debug(LTag.APS, "Result: " + result); try { - determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result), aapsLogger); + determineBasalResultMA = new DetermineBasalResultMA(injector, jsResult, new JSONObject(result)); } catch (JSONException e) { aapsLogger.error(LTag.APS, "Unhandled exception", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java index 60877fd773..298b313540 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java @@ -4,6 +4,7 @@ import org.json.JSONException; import org.json.JSONObject; import org.mozilla.javascript.NativeObject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; @@ -15,8 +16,8 @@ public class DetermineBasalResultMA extends APSResult { private double snoozeBG; private String mealAssist; - DetermineBasalResultMA(NativeObject result, JSONObject j, AAPSLogger aapsLogger) { - this(aapsLogger); + DetermineBasalResultMA(HasAndroidInjector injector, NativeObject result, JSONObject j) { + this(injector); json = j; if (result.containsKey("error")) { reason = (String) result.get("error"); @@ -49,13 +50,13 @@ public class DetermineBasalResultMA extends APSResult { } } - private DetermineBasalResultMA(AAPSLogger aapsLogger) { - this.aapsLogger = aapsLogger; + private DetermineBasalResultMA(HasAndroidInjector injector) { + super(injector); } @Override - public DetermineBasalResultMA clone() { - DetermineBasalResultMA newResult = new DetermineBasalResultMA(aapsLogger); + public DetermineBasalResultMA newAndClone(HasAndroidInjector injector) { + DetermineBasalResultMA newResult = new DetermineBasalResultMA(injector); doClone(newResult); newResult.eventualBG = eventualBG; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java index 0d5a6e2612..4617f684a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java @@ -5,6 +5,7 @@ import org.json.JSONException; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -57,6 +58,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { @Inject public OpenAPSMAPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ConstraintChecker constraintChecker, @@ -74,7 +76,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { .shortName(R.string.oaps_shortname) .preferencesId(R.xml.pref_openapsma) .description(R.string.description_ma), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); this.constraintChecker = constraintChecker; @@ -118,7 +120,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterMAJS determineBasalAdapterMAJS; - determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(mainApp), getAapsLogger()); + determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(mainApp), getInjector()); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index 5d0ec02213..f47cb88777 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -17,7 +17,9 @@ import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; +import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -34,12 +36,14 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; +import info.nightscout.androidaps.utils.sharedPreferences.SP; public class DetermineBasalAdapterSMBJS { - private final AAPSLogger aapsLogger; - + private final HasAndroidInjector injector; + @Inject AAPSLogger aapsLogger; + @Inject ConstraintChecker constraintChecker; + @Inject SP sp; private ScriptReader mScriptReader; private JSONObject mProfile; @@ -67,9 +71,10 @@ public class DetermineBasalAdapterSMBJS { * Main code */ - DetermineBasalAdapterSMBJS(ScriptReader scriptReader, AAPSLogger aapsLogger) { + DetermineBasalAdapterSMBJS(ScriptReader scriptReader, HasAndroidInjector injector) { mScriptReader = scriptReader; - this.aapsLogger = aapsLogger; + this.injector = injector; + injector.androidInjector().inject(this); } @@ -143,7 +148,7 @@ public class DetermineBasalAdapterSMBJS { String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); aapsLogger.debug(LTag.APS, "Result: " + result); try { - determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result), aapsLogger); + determineBasalResultSMB = new DetermineBasalResultSMB(injector, new JSONObject(result)); } catch (JSONException e) { aapsLogger.error(LTag.APS, "Unhandled exception", e); } @@ -231,8 +236,8 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("target_bg", targetBg); mProfile.put("carb_ratio", profile.getIc()); mProfile.put("sens", profile.getIsfMgdl()); - mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)); - mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)); + mProfile.put("max_daily_safety_multiplier", sp.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)); + mProfile.put("current_basal_safety_multiplier", sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)); // TODO AS-FIX // mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)); @@ -258,18 +263,18 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableUAM", uamAllowed); mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable); - boolean smbEnabled = SP.getBoolean(MainApp.gs(R.string.key_use_smb), false); - mProfile.put("enableSMB_with_COB", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_COB, false)); - mProfile.put("enableSMB_with_temptarget", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_temptarget, false)); - mProfile.put("allowSMB_with_high_temptarget", smbEnabled && SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false)); - mProfile.put("enableSMB_always", smbEnabled && SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering); - mProfile.put("enableSMB_after_carbs", smbEnabled && SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); - mProfile.put("maxSMBBasalMinutes", SP.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes)); + boolean smbEnabled = sp.getBoolean(MainApp.gs(R.string.key_use_smb), false); + mProfile.put("enableSMB_with_COB", smbEnabled && sp.getBoolean(R.string.key_enableSMB_with_COB, false)); + mProfile.put("enableSMB_with_temptarget", smbEnabled && sp.getBoolean(R.string.key_enableSMB_with_temptarget, false)); + mProfile.put("allowSMB_with_high_temptarget", smbEnabled && sp.getBoolean(R.string.key_allowSMB_with_high_temptarget, false)); + mProfile.put("enableSMB_always", smbEnabled && sp.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering); + mProfile.put("enableSMB_after_carbs", smbEnabled && sp.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); + mProfile.put("maxSMBBasalMinutes", sp.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes)); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); mProfile.put("temptargetSet", tempTargetSet); - mProfile.put("autosens_max", SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_max, "1.2"))); + mProfile.put("autosens_max", SafeParse.stringToDouble(sp.getString(R.string.key_openapsama_autosens_max, "1.2"))); if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) { mProfile.put("out_units", "mmol/L"); @@ -295,7 +300,7 @@ public class DetermineBasalAdapterSMBJS { mGlucoseStatus = new JSONObject(); mGlucoseStatus.put("glucose", glucoseStatus.glucose); - if (SP.getBoolean(R.string.key_always_use_shortavg, false)) { + if (sp.getBoolean(R.string.key_always_use_shortavg, false)) { mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta); } else { mGlucoseStatus.put("delta", glucoseStatus.delta); @@ -314,7 +319,7 @@ public class DetermineBasalAdapterSMBJS { mMealData.put("lastCarbTime", mealData.lastCarbTime); - if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { + if (constraintChecker.isAutosensModeEnabled().value()) { mAutosensData = new JSONObject(); mAutosensData.put("ratio", autosensDataRatio); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java index f259ed2fa4..dae170d5d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java @@ -3,19 +3,24 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; import org.json.JSONException; import org.json.JSONObject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.utils.DateUtil; public class DetermineBasalResultSMB extends APSResult { - private final AAPSLogger aapsLogger; private double eventualBG; private double snoozeBG; - DetermineBasalResultSMB(JSONObject result, AAPSLogger aapsLogger) { - this(aapsLogger); + private DetermineBasalResultSMB(HasAndroidInjector injector) { + super(injector); + hasPredictions = true; + } + + DetermineBasalResultSMB(HasAndroidInjector injector, JSONObject result) { + this(injector); date = DateUtil.now(); json = result; try { @@ -60,14 +65,9 @@ public class DetermineBasalResultSMB extends APSResult { } } - private DetermineBasalResultSMB(AAPSLogger aapsLogger) { - hasPredictions = true; - this.aapsLogger = aapsLogger; - } - @Override - public DetermineBasalResultSMB clone() { - DetermineBasalResultSMB newResult = new DetermineBasalResultSMB(aapsLogger); + public DetermineBasalResultSMB newAndClone(HasAndroidInjector injector) { + DetermineBasalResultSMB newResult = new DetermineBasalResultSMB(injector); doClone(newResult); newResult.eventualBG = eventualBG; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt index 0ff3ae11c8..ec60365f2e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt @@ -95,7 +95,7 @@ class OpenAPSSMBFragment : DaggerFragment() { openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterSMBJS.mealDataParam) openapsma_scriptdebugdata.text = determineBasalAdapterSMBJS.scriptDebug openAPSSMBPlugin.lastAPSResult?.inputConstraints?.let { - openapsma_constraints.text = it.reasons + openapsma_constraints.text = it.getReasons(aapsLogger) } } if (openAPSSMBPlugin.lastAPSRun != 0L) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index f64ceca7c9..64833bb9e3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -6,6 +6,7 @@ import org.json.JSONException; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -45,6 +46,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; @Singleton public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { + private final HasAndroidInjector injector; private final ConstraintChecker constraintChecker; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; @@ -62,6 +64,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr @Inject public OpenAPSSMBPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ConstraintChecker constraintChecker, @@ -79,9 +82,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr .shortName(R.string.smb_shortname) .preferencesId(R.xml.pref_openapssmb) .description(R.string.description_smb), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); - + this.injector = injector; this.constraintChecker = constraintChecker; this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; @@ -123,7 +126,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS; - determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(mainApp), getAapsLogger()); + determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(mainApp), injector); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); @@ -303,7 +306,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr @NotNull @Override public Constraint isSuperBolusEnabled(Constraint value) { - value.set(false); + value.set(getAapsLogger(), false); return value; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index 322f9a7a33..56426b9cec 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -12,6 +12,7 @@ import javax.inject.Inject; import javax.inject.Singleton; import dagger.Lazy; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventAppInitialized; @@ -105,6 +106,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi Lazy treatmentsPlugin, Lazy sensitivityOref0Plugin, Lazy sensitivityOref1Plugin, + HasAndroidInjector injector, SP sp, RxBusWrapper rxBus, AAPSLogger aapsLogger, @@ -121,7 +123,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi .pluginName(R.string.configbuilder) .shortName(R.string.configbuilder_shortname) .description(R.string.description_config_builder), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); this.insulinOrefRapidActingPlugin = insulinOrefRapidActingPlugin; this.localProfilePlugin = localProfilePlugin; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt index 68dcb9d5a8..cc529e4883 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt @@ -12,16 +12,6 @@ import javax.inject.Singleton @Singleton class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : ConstraintsInterface { - init { - instance = this - } - - companion object { - @JvmStatic - @Deprecated("Get via Dagger. Will be removed once fully transitioned to Dagger") - lateinit var instance: ConstraintChecker //TODO: remove as soon as Dagger is fully set up - } - fun isLoopInvocationAllowed(): Constraint = isLoopInvocationAllowed(Constraint(true)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt index 197bb1a1f8..40c6b32b5a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt @@ -19,7 +19,7 @@ import javax.inject.Singleton @Singleton class DstHelperPlugin @Inject constructor( - private var injector: HasAndroidInjector, + injector: HasAndroidInjector, aapsLogger: AAPSLogger, private var rxBus: RxBusWrapper, resourceHelper: ResourceHelper, @@ -32,7 +32,7 @@ class DstHelperPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.dst_plugin_name), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ConstraintsInterface { companion object { @@ -75,7 +75,7 @@ class DstHelperPlugin @Inject constructor( } else { aapsLogger.debug(LTag.CONSTRAINTS, "Loop already suspended") } - value.set(false, "DST in last 3 hours.", this) + value.set(aapsLogger, false, "DST in last 3 hours.", this) } return value } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index 4c62bfc319..a43e4385d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -25,7 +25,7 @@ import javax.inject.Singleton @Singleton class ObjectivesPlugin @Inject constructor( - private val injector: HasAndroidInjector, + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val configBuilderPlugin: ConfigBuilderPlugin, @@ -39,7 +39,7 @@ class ObjectivesPlugin @Inject constructor( .pluginName(R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ConstraintsInterface { var objectives: MutableList = ArrayList() @@ -151,37 +151,37 @@ class ObjectivesPlugin @Inject constructor( */ override fun isLoopInvocationAllowed(value: Constraint): Constraint { if (!objectives[FIRST_OBJECTIVE].isStarted) - value.set(false, resourceHelper.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this) + value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this) return value } override fun isClosedLoopAllowed(value: Constraint): Constraint { if (!objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted) - value.set(false, resourceHelper.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) + value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) return value } override fun isAutosensModeEnabled(value: Constraint): Constraint { if (!objectives[AUTOSENS_OBJECTIVE].isStarted) - value.set(false, resourceHelper.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this) + value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this) return value } override fun isAMAModeEnabled(value: Constraint): Constraint { if (!objectives[AMA_OBJECTIVE].isStarted) - value.set(false, resourceHelper.gs(R.string.objectivenotstarted, AMA_OBJECTIVE + 1), this) + value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, AMA_OBJECTIVE + 1), this) return value } override fun isSMBModeEnabled(value: Constraint): Constraint { if (!objectives[SMB_OBJECTIVE].isStarted) - value.set(false, resourceHelper.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this) + value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this) return value } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { if (objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted && !objectives[MAXIOB_ZERO_CL_OBJECTIVE].isAccomplished) - maxIob.set(0.0, resourceHelper.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) + maxIob.set(aapsLogger, 0.0, resourceHelper.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) return maxIob } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt index 0acdbce7e5..749f7f795c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.constraints.phoneChecker import android.content.Context import android.os.Build import com.scottyab.rootbeer.RootBeer +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.ConstraintsInterface import info.nightscout.androidaps.interfaces.PluginBase @@ -15,6 +16,7 @@ import javax.inject.Singleton @Singleton class PhoneCheckerPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val context: Context @@ -24,7 +26,7 @@ class PhoneCheckerPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.phonechecker), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ConstraintsInterface { var phoneRooted: Boolean = false diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index 586a12fefb..5d903489ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -5,6 +5,7 @@ import androidx.annotation.NonNull; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -49,14 +50,19 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @Inject ActivePluginProvider activePlugin; @Inject - public SafetyPlugin(AAPSLogger aapsLogger, ResourceHelper resourceHelper) { + public SafetyPlugin( + HasAndroidInjector injector, + AAPSLogger aapsLogger, + ResourceHelper resourceHelper + ) { super(new PluginDescription() - .mainType(PluginType.CONSTRAINTS) - .neverVisible(true) - .alwaysEnabled(true) - .showInList(false) - .pluginName(R.string.safety) - .preferencesId(R.xml.pref_safety), aapsLogger, resourceHelper + .mainType(PluginType.CONSTRAINTS) + .neverVisible(true) + .alwaysEnabled(true) + .showInList(false) + .pluginName(R.string.safety) + .preferencesId(R.xml.pref_safety), + aapsLogger, resourceHelper, injector ); } @@ -66,7 +72,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @NonNull @Override public Constraint isLoopInvocationAllowed(@NonNull Constraint value) { if (!activePlugin.getActivePumpPlugin().getPumpDescription().isTempBasalCapable) - value.set(false, resourceHelper.gs(R.string.pumpisnottempbasalcapable), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.pumpisnottempbasalcapable), this); return value; } @@ -74,18 +80,18 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { public Constraint isClosedLoopAllowed(@NonNull Constraint value) { String mode = sp.getString(R.string.key_aps_mode, "open"); if (!mode.equals("closed")) - value.set(false, resourceHelper.gs(R.string.closedmodedisabledinpreferences), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.closedmodedisabledinpreferences), this); if (!MainApp.isEngineeringModeOrRelease()) { if (value.value()) { Notification n = new Notification(Notification.TOAST_ALARM, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL); rxBus.send(new EventNewNotification(n)); } - value.set(false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), this); } PumpInterface pump = activePlugin.getActivePumpPlugin(); if (pump != null && !pump.isFakingTempsByExtendedBoluses() && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { - value.set(false, MainApp.gs(R.string.closed_loop_disabled_with_eb), this); + value.set(getAapsLogger(), false, MainApp.gs(R.string.closed_loop_disabled_with_eb), this); } return value; } @@ -94,7 +100,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { public Constraint isAutosensModeEnabled(@NonNull Constraint value) { boolean enabled = sp.getBoolean(R.string.key_openapsama_useautosens, false); if (!enabled) - value.set(false, resourceHelper.gs(R.string.autosensdisabledinpreferences), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.autosensdisabledinpreferences), this); return value; } @@ -102,10 +108,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { public Constraint isSMBModeEnabled(@NonNull Constraint value) { boolean enabled = sp.getBoolean(R.string.key_use_smb, false); if (!enabled) - value.set(false, resourceHelper.gs(R.string.smbdisabledinpreferences), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.smbdisabledinpreferences), this); Constraint closedLoop = constraintChecker.isClosedLoopAllowed(); if (!closedLoop.value()) - value.set(false, resourceHelper.gs(R.string.smbnotallowedinopenloopmode), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.smbnotallowedinopenloopmode), this); return value; } @@ -113,10 +119,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { public Constraint isUAMEnabled(@NonNull Constraint value) { boolean enabled = sp.getBoolean(R.string.key_use_uam, false); if (!enabled) - value.set(false, resourceHelper.gs(R.string.uamdisabledinpreferences), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.uamdisabledinpreferences), this); boolean oref1Enabled = sensitivityOref1Plugin.isEnabled(PluginType.SENSITIVITY); if (!oref1Enabled) - value.set(false, resourceHelper.gs(R.string.uamdisabledoref1notselected), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.uamdisabledoref1notselected), this); return value; } @@ -126,7 +132,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { if (bgSource != null) { if (!bgSource.advancedFilteringSupported()) - value.set(false, resourceHelper.gs(R.string.smbalwaysdisabled), this); + value.set(getAapsLogger(), false, resourceHelper.gs(R.string.smbalwaysdisabled), this); } return value; } @@ -134,7 +140,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @NonNull @Override public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingbasalratio), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + absoluteRate.setIfGreater(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbasalratio), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); if (Config.APS) { double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d); @@ -142,30 +148,30 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { maxBasal = profile.getMaxDailyBasal(); absoluteRate.addReason(resourceHelper.gs(R.string.increasingmaxbasal), this); } - absoluteRate.setIfSmaller(maxBasal, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxBasal, resourceHelper.gs(R.string.maxvalueinpreferences)), this); + absoluteRate.setIfSmaller(getAapsLogger(), maxBasal, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxBasal, resourceHelper.gs(R.string.maxvalueinpreferences)), this); // Check percentRate but absolute rate too, because we know real current basal in pump Double maxBasalMult = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d); double maxFromBasalMult = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100; - absoluteRate.setIfSmaller(maxFromBasalMult, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromBasalMult, resourceHelper.gs(R.string.maxbasalmultiplier)), this); + absoluteRate.setIfSmaller(getAapsLogger(), maxFromBasalMult, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromBasalMult, resourceHelper.gs(R.string.maxbasalmultiplier)), this); Double maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d); double maxFromDaily = Math.floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100; - absoluteRate.setIfSmaller(maxFromDaily, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromDaily, resourceHelper.gs(R.string.maxdailybasalmultiplier)), this); + absoluteRate.setIfSmaller(getAapsLogger(), maxFromDaily, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromDaily, resourceHelper.gs(R.string.maxdailybasalmultiplier)), this); } - absoluteRate.setIfSmaller(HardLimits.maxBasal(), String.format(resourceHelper.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), resourceHelper.gs(R.string.hardlimit)), this); + absoluteRate.setIfSmaller(getAapsLogger(), HardLimits.maxBasal(), String.format(resourceHelper.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), resourceHelper.gs(R.string.hardlimit)), this); PumpInterface pump = activePlugin.getActivePumpPlugin(); // check for pump max if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); - absoluteRate.setIfSmaller(pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(getAapsLogger(), pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); } // do rounding if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { - absoluteRate.set(Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep)); + absoluteRate.set(getAapsLogger(), Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep)); } return absoluteRate; } @@ -192,11 +198,11 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue(); } - percentRate.set(percentRateAfterConst, String.format(resourceHelper.gs(R.string.limitingpercentrate), percentRateAfterConst, resourceHelper.gs(R.string.pumplimit)), this); + percentRate.set(getAapsLogger(), percentRateAfterConst, String.format(resourceHelper.gs(R.string.limitingpercentrate), percentRateAfterConst, resourceHelper.gs(R.string.pumplimit)), this); if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) { double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose(); - percentRate.setIfSmaller((int) pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); + percentRate.setIfSmaller(getAapsLogger(), (int) pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this); } return percentRate; @@ -204,44 +210,44 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @NonNull @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + insulin.setIfGreater(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); - insulin.setIfSmaller(maxBolus, String.format(resourceHelper.gs(R.string.limitingbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); + insulin.setIfSmaller(getAapsLogger(), maxBolus, String.format(resourceHelper.gs(R.string.limitingbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); - insulin.setIfSmaller(HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); + insulin.setIfSmaller(getAapsLogger(), HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); PumpInterface pump = activePlugin.getActivePumpPlugin(); if (pump != null) { double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value()); - insulin.setIfDifferent(rounded, resourceHelper.gs(R.string.pumplimit), this); + insulin.setIfDifferent(getAapsLogger(), rounded, resourceHelper.gs(R.string.pumplimit), this); } return insulin; } @NonNull @Override public Constraint applyExtendedBolusConstraints(Constraint insulin) { - insulin.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingextendedbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + insulin.setIfGreater(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingextendedbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this); Double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3d); - insulin.setIfSmaller(maxBolus, String.format(resourceHelper.gs(R.string.limitingextendedbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); + insulin.setIfSmaller(getAapsLogger(), maxBolus, String.format(resourceHelper.gs(R.string.limitingextendedbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this); - insulin.setIfSmaller(HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingextendedbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); + insulin.setIfSmaller(getAapsLogger(), HardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingextendedbolus), HardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this); PumpInterface pump = activePlugin.getActivePumpPlugin(); if (pump != null) { double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value()); - insulin.setIfDifferent(rounded, resourceHelper.gs(R.string.pumplimit), this); + insulin.setIfDifferent(getAapsLogger(), rounded, resourceHelper.gs(R.string.pumplimit), this); } return insulin; } @NonNull @Override public Constraint applyCarbsConstraints(Constraint carbs) { - carbs.setIfGreater(0, String.format(resourceHelper.gs(R.string.limitingcarbs), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + carbs.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingcarbs), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); Integer maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48); - carbs.setIfSmaller(maxCarbs, String.format(resourceHelper.gs(R.string.limitingcarbs), maxCarbs, resourceHelper.gs(R.string.maxvalueinpreferences)), this); + carbs.setIfSmaller(getAapsLogger(), maxCarbs, String.format(resourceHelper.gs(R.string.limitingcarbs), maxCarbs, resourceHelper.gs(R.string.maxvalueinpreferences)), this); return carbs; } @@ -253,14 +259,14 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { maxIobPref = sp.getDouble(R.string.key_openapssmb_max_iob, 3d); else maxIobPref = sp.getDouble(R.string.key_openapsma_max_iob, 1.5d); - maxIob.setIfSmaller(maxIobPref, String.format(resourceHelper.gs(R.string.limitingiob), maxIobPref, resourceHelper.gs(R.string.maxvalueinpreferences)), this); + maxIob.setIfSmaller(getAapsLogger(), maxIobPref, String.format(resourceHelper.gs(R.string.limitingiob), maxIobPref, resourceHelper.gs(R.string.maxvalueinpreferences)), this); if (openAPSMAPlugin.isEnabled(PluginType.APS)) - maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); + maxIob.setIfSmaller(getAapsLogger(), HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); if (openAPSAMAPlugin.isEnabled(PluginType.APS)) - maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); + maxIob.setIfSmaller(getAapsLogger(), HardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this); if (openAPSSMBPlugin.isEnabled(PluginType.APS)) - maxIob.setIfSmaller(HardLimits.maxIobSMB(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobSMB(), resourceHelper.gs(R.string.hardlimit)), this); + maxIob.setIfSmaller(getAapsLogger(), HardLimits.maxIobSMB(), String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.maxIobSMB(), resourceHelper.gs(R.string.hardlimit)), this); return maxIob; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt index 005ab8f086..0faa87decf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.constraints.signatureVerifier import android.content.Context import android.content.pm.PackageManager +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.ConstraintsInterface @@ -9,14 +10,11 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.L -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP -import org.slf4j.LoggerFactory import org.spongycastle.util.encoders.Hex import java.io.* import java.net.URL @@ -35,6 +33,7 @@ import javax.inject.Singleton */ @Singleton class SignatureVerifierPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val sp: SP, @@ -46,13 +45,12 @@ class SignatureVerifierPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.signature_verifier), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ConstraintsInterface { private val REVOKED_CERTS_URL = "https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/src/main/assets/revoked_certs.txt" private val UPDATE_INTERVAL = TimeUnit.DAYS.toMillis(1) - private val log = StacktraceLoggerWrapper.getLogger(L.CORE) private val lock: Any = arrayOfNulls(0) private var revokedCertsFile: File? = null private var revokedCerts: List? = null @@ -65,7 +63,7 @@ class SignatureVerifierPlugin @Inject constructor( try { downloadAndSaveRevokedCerts() } catch (e: IOException) { - log.error("Could not download revoked certs", e) + aapsLogger.error("Could not download revoked certs", e) } } if (hasIllegalSignature()) showNotification() @@ -75,14 +73,14 @@ class SignatureVerifierPlugin @Inject constructor( override fun isLoopInvocationAllowed(value: Constraint): Constraint { if (hasIllegalSignature()) { showNotification() - value.set(false) + value.set(aapsLogger, false) } if (shouldDownloadCerts()) { Thread(Runnable { try { downloadAndSaveRevokedCerts() } catch (e: IOException) { - log.error("Could not download revoked certs", e) + aapsLogger.error("Could not download revoked certs", e) } }).start() } @@ -114,9 +112,9 @@ class SignatureVerifierPlugin @Inject constructor( } } } catch (e: PackageManager.NameNotFoundException) { - log.error("Error in SignatureVerifierPlugin", e) + aapsLogger.error("Error in SignatureVerifierPlugin", e) } catch (e: NoSuchAlgorithmException) { - log.error("Error in SignatureVerifierPlugin", e) + aapsLogger.error("Error in SignatureVerifierPlugin", e) } return false } @@ -132,15 +130,15 @@ class SignatureVerifierPlugin @Inject constructor( val digest = MessageDigest.getInstance("SHA256") val fingerprint = digest.digest(signature.toByteArray()) val hash = Hex.toHexString(fingerprint) - log.debug("Found signature: $hash") - log.debug("Found signature (short): " + singleCharMap(fingerprint)) + aapsLogger.debug("Found signature: $hash") + aapsLogger.debug("Found signature (short): " + singleCharMap(fingerprint)) hashes.add(singleCharMap(fingerprint)) } } } catch (e: PackageManager.NameNotFoundException) { - log.error("Error in SignatureVerifierPlugin", e) + aapsLogger.error("Error in SignatureVerifierPlugin", e) } catch (e: NoSuchAlgorithmException) { - log.error("Error in SignatureVerifierPlugin", e) + aapsLogger.error("Error in SignatureVerifierPlugin", e) } return hashes } @@ -181,7 +179,7 @@ class SignatureVerifierPlugin @Inject constructor( if (revokedCerts == null) revokedCerts = readRevokedCertsInAssets() synchronized(lock) { this.revokedCerts = parseRevokedCertsFile(revokedCerts) } } catch (e: IOException) { - log.error("Error in SignatureVerifierPlugin", e) + aapsLogger.error("Error in SignatureVerifierPlugin", e) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt index 9dc8e11a48..fb1bb534e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.constraints.storage import android.os.Environment import android.os.StatFs +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Constraint @@ -21,6 +22,7 @@ import javax.inject.Singleton @Singleton open class StorageConstraintPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val rxBus: RxBusWrapper @@ -30,14 +32,14 @@ open class StorageConstraintPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.storage), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ConstraintsInterface { override fun isClosedLoopAllowed(value: Constraint): Constraint { val diskFree = availableInternalMemorySize aapsLogger.debug(LTag.CONSTRAINTS, "Internal storage free (Mb):$diskFree") if (diskFree < Constants.MINIMUM_FREE_SPACE) { - value[false, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE)] = this + value[aapsLogger, false, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE)] = this val notification = Notification(Notification.DISKFULL, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt index e068dfb25d..ca5902395a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.constraints.versionChecker +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.Constraint @@ -21,6 +22,7 @@ import kotlin.math.roundToInt @Singleton class VersionCheckerPlugin @Inject constructor( + injector: HasAndroidInjector, private val sp: SP, resourceHelper: ResourceHelper, private val versionCheckerUtils: VersionCheckerUtils, @@ -32,7 +34,7 @@ class VersionCheckerPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.versionChecker), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ConstraintsInterface { enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) { @@ -56,7 +58,7 @@ class VersionCheckerPlugin @Inject constructor( checkWarning() versionCheckerUtils.triggerCheckVersion() return if (isOldVersion(gracePeriod.veryOld.daysToMillis())) - value.set(false, resourceHelper.gs(R.string.very_old_version), this) + value.set(aapsLogger,false, resourceHelper.gs(R.string.very_old_version), this) else value } @@ -90,7 +92,7 @@ class VersionCheckerPlugin @Inject constructor( override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint = if (isOldVersion(gracePeriod.old.daysToMillis())) - maxIob.set(0.toDouble(), resourceHelper.gs(R.string.old_version), this) + maxIob.set(aapsLogger, 0.0, resourceHelper.gs(R.string.old_version), this) else maxIob diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt index f266040520..91125a9e1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.actions +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.PluginBase @@ -11,7 +12,10 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class ActionsPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: ResourceHelper +class ActionsPlugin @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ActionsFragment::class.qualifiedName) @@ -20,5 +24,5 @@ class ActionsPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: .pluginName(R.string.actions) .shortName(R.string.actions_shortname) .description(R.string.description_actions), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index 320314462c..9052055573 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -41,7 +41,7 @@ import javax.inject.Singleton @Singleton class AutomationPlugin @Inject constructor( - private val injector: HasAndroidInjector, + injector: HasAndroidInjector, resourceHelper: ResourceHelper, private val context: Context, private val sp: SP, @@ -55,7 +55,8 @@ class AutomationPlugin @Inject constructor( .pluginName(R.string.automation) .shortName(R.string.automation_short) .preferencesId(R.xml.pref_automation) - .description(R.string.automation_description), aapsLogger, resourceHelper + .description(R.string.automation_description), + aapsLogger, resourceHelper, injector ) { private var disposable: CompositeDisposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt index b79dc7157b..e3328aefc9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.careportal +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.PluginBase @@ -11,7 +12,10 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class CareportalPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: ResourceHelper +class CareportalPlugin @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(CareportalFragment::class.java.name) @@ -20,6 +24,5 @@ class CareportalPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelpe .visibleByDefault(Config.NSCLIENT) .enableByDefault(Config.NSCLIENT) .description(R.string.description_careportal), - aapsLogger, resourceHelper - + aapsLogger, resourceHelper, injector ) \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index c7b24addae..990bb96e46 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -5,6 +5,7 @@ import android.content.Intent import android.content.pm.ResolveInfo import android.os.Bundle import dagger.Lazy +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.data.IobTotal @@ -41,6 +42,7 @@ import javax.inject.Singleton @Singleton class DataBroadcastPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val context: Context, @@ -59,7 +61,7 @@ class DataBroadcastPlugin @Inject constructor( .alwaysEnabled(true) .neverVisible(true) .showInList(false), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { private val disposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index 7928fca509..9c41df2666 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.food +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription @@ -10,14 +11,17 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class FoodPlugin @Inject constructor(aapsLogger: AAPSLogger, resourceHelper: ResourceHelper +class FoodPlugin @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(FoodFragment::class.java.name) .pluginName(R.string.food) .shortName(R.string.food_short) .description(R.string.description_food), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { var service: FoodService? = null diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index 08a7275fb4..79b7c3d54b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.maintenance import android.content.Intent import android.net.Uri import androidx.core.content.FileProvider +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.MainApp @@ -23,6 +24,7 @@ import javax.inject.Singleton @Singleton class MaintenancePlugin @Inject constructor( + injector: HasAndroidInjector, private val mainApp: MainApp, resourceHelper: ResourceHelper, private val sp: SP, @@ -37,7 +39,7 @@ class MaintenancePlugin @Inject constructor( .shortName(R.string.maintenance_shortname) .preferencesId(R.xml.pref_maintenance) .description(R.string.description_maintenance), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { fun sendLogs() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index 804ea823e6..f256a2d759 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -15,7 +15,6 @@ import androidx.preference.PreferenceScreen; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; @@ -23,6 +22,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -73,10 +73,11 @@ public class NSClientPlugin extends PluginBase { public NSClientService nsClientService = null; - private NsClientReceiverDelegate nsClientReceiverDelegate = new NsClientReceiverDelegate(); + private NsClientReceiverDelegate nsClientReceiverDelegate = new NsClientReceiverDelegate(); @Inject public NSClientPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper @@ -88,7 +89,7 @@ public class NSClientPlugin extends PluginBase { .shortName(R.string.nsclientinternal_shortname) .preferencesId(R.xml.pref_nsclientinternal) .description(R.string.description_ns_client), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); this.aapsLogger = aapsLogger; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java index 08013c9801..eccc28cead 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java @@ -14,6 +14,7 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -457,8 +458,8 @@ public class NSDeviceStatus { return Html.fromHtml(string.toString()); } - public static APSResult getAPSResult() { - APSResult result = new APSResult(); + public static APSResult getAPSResult(HasAndroidInjector injector) { + APSResult result = new APSResult(injector); result.json = deviceStatusOpenAPSData.suggested; result.date = deviceStatusOpenAPSData.clockSuggested; return result; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 554c3a98e7..0a21468800 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -45,6 +45,7 @@ import java.util.concurrent.TimeUnit; import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; @@ -127,6 +128,7 @@ import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.utils.DateUtil.now; public class OverviewFragment extends DaggerFragment implements View.OnClickListener, View.OnLongClickListener { + @Inject HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @Inject SP sp; @Inject RxBusWrapper rxBus; @@ -1400,7 +1402,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList if (Config.APS) apsResult = loopPlugin.lastRun.constraintsProcessed; else - apsResult = NSDeviceStatus.getAPSResult(); + apsResult = NSDeviceStatus.getAPSResult(injector); int predHours = (int) (Math.ceil(apsResult.getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000)); predHours = Math.min(2, predHours); predHours = Math.max(0, predHours); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 90dd1279be..219b56d025 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.overview +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.PluginBase @@ -20,6 +21,7 @@ import javax.inject.Singleton @Singleton class OverviewPlugin @Inject constructor( + injector: HasAndroidInjector, private val notificationStore: NotificationStore, private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBusWrapper, @@ -33,7 +35,8 @@ class OverviewPlugin @Inject constructor( .pluginName(R.string.overview) .shortName(R.string.overview_shortname) .preferencesId(R.xml.pref_overview) - .description(R.string.description_overview), aapsLogger, resourceHelper + .description(R.string.description_overview), + aapsLogger, resourceHelper, injector ) { private var disposable: CompositeDisposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index 8e7b8f6bbc..b33cec1518 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -9,6 +9,7 @@ import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.RemoteInput import androidx.core.app.TaskStackBuilder +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.MainApp @@ -35,6 +36,7 @@ import javax.inject.Singleton @Singleton class PersistentNotificationPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private var profileFunction: ProfileFunction, @@ -52,7 +54,7 @@ class PersistentNotificationPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .description(R.string.description_persistent_notification), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { // For Android Auto diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index dbd4b68074..bc0e2792b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -7,6 +7,7 @@ import android.text.TextUtils import androidx.preference.EditTextPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R @@ -46,6 +47,7 @@ import javax.inject.Singleton @Singleton class SmsCommunicatorPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val sp: SP, @@ -64,7 +66,7 @@ class SmsCommunicatorPlugin @Inject constructor( .shortName(R.string.smscommunicator_shortname) .preferencesId(R.xml.pref_smscommunicator) .description(R.string.description_sms_communicator), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { private val disposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt index 572c309c94..2a7db292a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt @@ -4,6 +4,7 @@ import android.content.Context import android.text.Spanned import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventNetworkChange @@ -41,6 +42,7 @@ import javax.inject.Singleton @Singleton class TidepoolPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val rxBus: RxBusWrapper, @@ -56,7 +58,7 @@ class TidepoolPlugin @Inject constructor( .fragmentClass(TidepoolFragment::class.qualifiedName) .preferencesId(R.xml.pref_tidepool) .description(R.string.description_tidepool), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { private var disposable: CompositeDisposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index ba8be65201..62c964238c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.general.wear import android.content.Intent import dagger.Lazy +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.* @@ -26,6 +27,7 @@ import javax.inject.Singleton @Singleton class WearPlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val sp: SP, @@ -41,7 +43,7 @@ class WearPlugin @Inject constructor( .shortName(R.string.wear_shortname) .preferencesId(R.xml.pref_wear) .description(R.string.description_wear), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ) { private val disposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index 14f862c12b..b88c54ea6f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.xdripStatusline import android.content.Context import android.content.Intent import android.os.Bundle +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* @@ -28,6 +29,7 @@ import javax.inject.Singleton @Singleton class StatusLinePlugin @Inject constructor( + injector: HasAndroidInjector, private val sp: SP, private val profileFunction: ProfileFunction, resourceHelper: ResourceHelper, @@ -45,7 +47,9 @@ class StatusLinePlugin @Inject constructor( .shortName(R.string.xdripstatus_shortname) .neverVisible(true) .preferencesId(R.xml.pref_xdripstatus) - .description(R.string.description_xdrip_status_line), aapsLogger, resourceHelper) { + .description(R.string.description_xdrip_status_line), + aapsLogger, resourceHelper, injector +) { private val disposable = CompositeDisposable() private var lastLoopStatus = false @@ -54,8 +58,10 @@ class StatusLinePlugin @Inject constructor( //broadcast related constants @Suppress("SpellCheckingInspection") private const val EXTRA_STATUSLINE = "com.eveningoutpost.dexdrip.Extras.Statusline" + @Suppress("SpellCheckingInspection") private const val ACTION_NEW_EXTERNAL_STATUSLINE = "com.eveningoutpost.dexdrip.ExternalStatusline" + @Suppress("SpellCheckingInspection", "unused") private const val RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_EXTERNAL_STATUSLINE" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt index 4cefb53116..e5a92588c3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.insulin +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Iob import info.nightscout.androidaps.interfaces.InsulinInterface @@ -21,6 +22,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper * */ abstract class InsulinOrefBasePlugin( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, val profileFunction: ProfileFunction, val rxBus: RxBusWrapper, aapsLogger: AAPSLogger @@ -29,7 +31,7 @@ abstract class InsulinOrefBasePlugin( .fragmentClass(InsulinFragment::class.java.name) .shortName(R.string.insulin_shortname) .visibleByDefault(false), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), InsulinInterface { private var lastWarned: Long = 0 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index 4448be63fd..1ae2869b6e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.insulin +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -15,11 +16,12 @@ import javax.inject.Singleton */ @Singleton class InsulinOrefFreePeakPlugin @Inject constructor( + injector: HasAndroidInjector, private val sp: SP, resourceHelper: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBusWrapper, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { override fun getId(): Int { return InsulinInterface.OREF_FREE_PEAK diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt index 8aed4d24aa..eea3df68ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.insulin +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -14,10 +15,11 @@ import javax.inject.Singleton */ @Singleton class InsulinOrefRapidActingPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBusWrapper, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { override fun getId(): Int { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt index 8e33910983..e2048d7a65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.insulin +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -14,10 +15,11 @@ import javax.inject.Singleton */ @Singleton class InsulinOrefUltraRapidActingPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBusWrapper, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { override fun getId(): Int = InsulinInterface.OREF_ULTRA_RAPID_ACTING diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java index d3d11d1d48..e6eebaa799 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensData.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -13,8 +10,8 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; @@ -28,8 +25,8 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; public class AutosensData implements DataPointWithLabelInterface { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.AUTOSENS); + @Inject AAPSLogger aapsLogger; @Inject SP sp; @Inject ResourceHelper resourceHelper; @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; @@ -60,8 +57,7 @@ public class AutosensData implements DataPointWithLabelInterface { double sens = profile.getIsfMgdl(t.date); double ic = profile.getIc(t.date); min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Min 5m carbs impact for " + carbs + "g @" + DateUtil.dateAndTimeString(t.date) + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); + aapsLogger.debug(LTag.AUTOSENS, "Min 5m carbs impact for " + carbs + "g @" + DateUtil.dateAndTimeString(t.date) + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); } else { min5minCarbImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); } @@ -139,8 +135,7 @@ public class AutosensData implements DataPointWithLabelInterface { activeCarbsList.remove(i--); if (c.remaining > 0) cob -= c.remaining; - if (L.isEnabled(L.AUTOSENS)) - log.debug("Removing carbs at " + DateUtil.dateAndTimeString(toTime) + " after " + maxAbsorptionHours + "h > " + c.toString()); + aapsLogger.debug(LTag.AUTOSENS, "Removing carbs at " + DateUtil.dateAndTimeString(toTime) + " after " + maxAbsorptionHours + "h > " + c.toString()); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index d9ab1b18d2..88c9453bc2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -110,7 +110,7 @@ public class IobCobCalculatorPlugin extends PluginBase { .showInList(false) .neverVisible(true) .alwaysEnabled(true), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ); this.plugin = this; this.injector = injector; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index dde640f0d1..d0bec3b5d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.profile.local import android.app.Activity +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile @@ -31,6 +32,7 @@ import kotlin.math.max @Singleton class LocalProfilePlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBusWrapper, resourceHelper: ResourceHelper, @@ -42,7 +44,9 @@ class LocalProfilePlugin @Inject constructor( .enableByDefault(true) .pluginName(R.string.localprofile) .shortName(R.string.localprofile_shortname) - .description(R.string.description_profile_local), aapsLogger, resourceHelper), ProfileInterface { + .description(R.string.description_profile_local), + aapsLogger, resourceHelper, injector +), ProfileInterface { var rawProfile: ProfileStore? = null diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt index 848ea2d1d8..69c3e4dc3d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.profile.ns import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.data.ProfileStore @@ -22,6 +23,7 @@ import javax.inject.Singleton @Singleton class NSProfilePlugin @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBusWrapper, resourceHelper: ResourceHelper, @@ -35,7 +37,7 @@ class NSProfilePlugin @Inject constructor( .alwaysVisible(Config.NSCLIENT) .showInList(!Config.NSCLIENT) .description(R.string.description_profile_nightscout), - aapsLogger, resourceHelper + aapsLogger, resourceHelper, injector ), ProfileInterface { private var profile: ProfileStore? = null @@ -47,6 +49,7 @@ class NSProfilePlugin @Inject constructor( fun handleNewData(intent: Intent) { val bundles = intent.extras ?: return + @Suppress("SpellCheckingInspection") val activeProfile = bundles.getString("activeprofile") val profileString = bundles.getString("profile") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index ea99ed273a..57d8b399a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -7,7 +7,6 @@ import androidx.annotation.Nullable; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Calendar; @@ -20,6 +19,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -138,6 +138,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr @Inject public ComboPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, MainApp maiApp, @@ -154,7 +155,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr .pluginName(R.string.combopump) .shortName(R.string.combopump_shortname) .description(R.string.description_pump_combo), - aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, resourceHelper, commandQueue ); this.rxBus = rxBus; this.resourceHelper = resourceHelper; @@ -1391,14 +1392,14 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr @Override public Constraint isLoopInvocationAllowed(Constraint value) { if (!validBasalRateProfileSelectedOnPump) - value.set(false, MainApp.gs(R.string.novalidbasalrate), this); + value.set(getAapsLogger(), false, MainApp.gs(R.string.novalidbasalrate), this); return value; } @Override public Constraint applyMaxIOBConstraints(Constraint maxIob) { if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis()) - maxIob.setIfSmaller(0d, String.format(MainApp.gs(R.string.limitingmaxiob), 0d, MainApp.gs(R.string.unsafeusage)), this); + maxIob.setIfSmaller(getAapsLogger(), 0d, String.format(MainApp.gs(R.string.limitingmaxiob), 0d, MainApp.gs(R.string.unsafeusage)), this); return maxIob; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index dcc19b66b4..ee449b36b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory; import java.util.Date; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -71,9 +72,9 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI protected boolean displayConnectionMessages = false; - protected PumpPluginAbstract(PluginDescription pluginDescription, PumpType pumpType, ResourceHelper resourceHelper, AAPSLogger aapsLogger, CommandQueueProvider commandQueue) { + protected PumpPluginAbstract(PluginDescription pluginDescription, PumpType pumpType, HasAndroidInjector injector, ResourceHelper resourceHelper, AAPSLogger aapsLogger, CommandQueueProvider commandQueue) { - super(pluginDescription, aapsLogger, resourceHelper, commandQueue); + super(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue); pumpDescription.setPumpDescription(pumpType); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index 94d3f7ffb0..ac6d0f19c3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -5,11 +5,11 @@ import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -28,7 +28,6 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.ManufacturerType; @@ -60,10 +59,13 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump public PumpDescription pumpDescription = new PumpDescription(); protected DanaRPump danaRPump; + protected ConstraintChecker constraintChecker; protected AbstractDanaRPlugin( + HasAndroidInjector injector, DanaRPump danaRPump, ResourceHelper resourceHelper, + ConstraintChecker constraintChecker, AAPSLogger aapsLogger, CommandQueueProvider commandQueue) { super(new PluginDescription() @@ -73,9 +75,10 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump .shortName(R.string.danarpump_shortname) .preferencesId(R.xml.pref_danars) .description(R.string.description_pump_dana_r), - aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, resourceHelper, commandQueue ); this.danaRPump = danaRPump; + this.constraintChecker = constraintChecker; } @Override @@ -178,7 +181,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = danaRPump; PumpEnactResult result = new PumpEnactResult(); - percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -227,7 +230,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = danaRPump; - insulin = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); @@ -408,21 +411,21 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @Override public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { - absoluteRate.setIfSmaller(danaRPump.getMaxBasal(), String.format(MainApp.gs(R.string.limitingbasalratio), danaRPump.getMaxBasal(), MainApp.gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), String.format(MainApp.gs(R.string.limitingbasalratio), danaRPump.getMaxBasal(), MainApp.gs(R.string.pumplimit)), this); return absoluteRate; } @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(getAapsLogger(), 0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); return percentRate; } @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller(danaRPump.getMaxBolus(), String.format(MainApp.gs(R.string.limitingbolus), danaRPump.getMaxBolus(), MainApp.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), String.format(MainApp.gs(R.string.limitingbolus), danaRPump.getMaxBolus(), MainApp.gs(R.string.pumplimit)), this); return insulin; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index 03b1ae6af9..8919d993b3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -11,6 +11,7 @@ import androidx.annotation.NonNull; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -28,7 +29,6 @@ import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -53,6 +53,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { @Inject public DanaRPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, MainApp maiApp, @@ -63,7 +64,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { CommandQueueProvider commandQueue, DanaRPump danaRPump ) { - super(danaRPump, resourceHelper, aapsLogger, commandQueue); + super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue); this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.mainApp = maiApp; @@ -171,7 +172,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; if (!result.success) - result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStartWithSpeed.errorCode); + result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, danaRPump.getMessageStartErrorCode()); else result.comment = resourceHelper.gs(R.string.virtualpump_resultok); aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); @@ -293,7 +294,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours // What is current rate of extended bolusing in u/h? - aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Extended bolus in progress: " + (activeExtended != null) + " rate: " + danaRPump.getExtendedBolusAbsoluteRate()+ "U/h duration remaining: " + danaRPump.getExtendedBolusRemainingMinutes() + "min"); + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Extended bolus in progress: " + (activeExtended != null) + " rate: " + danaRPump.getExtendedBolusAbsoluteRate() + "U/h duration remaining: " + danaRPump.getExtendedBolusRemainingMinutes() + "min"); aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Rate to set: " + extendedRateToSet + "U/h"); // Compare with extended rate in progress diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt index 8a6e93fcc3..ac0732ff44 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt @@ -113,6 +113,9 @@ class DanaRPump @Inject constructor( return if (units == UNITS_MGDL) Constants.MGDL else Constants.MMOL } + // last start bolus erroCode + var messageStartErrorCode: Int = 0 + fun createConvertedProfile(): ProfileStore? { pumpProfiles?.let { val json = JSONObject() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt index e020d44236..56574a13f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt @@ -5,6 +5,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin @@ -18,6 +19,7 @@ class MessageHashTableR @Inject constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, resourceHelper: ResourceHelper, + constraintChecker: ConstraintChecker, danaRPump: DanaRPump, danaRPlugin: DanaRPlugin, danaRKoreanPlugin: DanaRKoreanPlugin, @@ -30,8 +32,8 @@ class MessageHashTableR @Inject constructor( init { put(MsgBolusStop()) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart()) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusStartWithSpeed()) // 0x0104 CMD_MEALINS_START_DATA_SPEED + put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA + put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED put(MsgBolusProgress()) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)) // 0x0205 CMD_PUMP_EXERCISE_MODE @@ -47,7 +49,7 @@ class MessageHashTableR @Inject constructor( put(MsgSetCarbsEntry()) // 0x0402 CMD_PUMPSET_HIS_S put(MsgSetTempBasalStop()) // 0x0403 CMD_PUMPSET_EXERCISE_STOP put(MsgSetExtendedBolusStop()) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart()) // 0x0407 CMD_PUMPSET_EXPANS_INS_S + put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S put(MsgError()) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS put(MsgPCCommStart()) // 0x3001 CMD_CONNECT put(MsgPCCommStop()) // 0x3002 CMD_DISCONNECT diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java deleted file mode 100644 index 97ab648610..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java +++ /dev/null @@ -1,44 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; - -public class MsgBolusStart extends MessageBase { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - - public static int errorCode; - - public MsgBolusStart() { - SetCommand(0x0102); - } - - public MsgBolusStart(double amount) { - this(); - - // HARDCODED LIMIT - amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); - - AddParamInt((int) (amount * 100)); - - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Bolus start : " + amount); - } - - @Override - public void handleMessage(byte[] bytes) { - errorCode = intFromBuff(bytes, 0, 1); - if (errorCode != 2) { - failed = true; - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Messsage response: " + errorCode + " FAILED!!"); - } else { - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Messsage response: " + errorCode + " OK"); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt new file mode 100644 index 0000000000..bfb55661ab --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt @@ -0,0 +1,35 @@ +package info.nightscout.androidaps.plugins.pump.danaR.comm + +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump + +class MsgBolusStart( + private val aapsLogger: AAPSLogger, + constraintChecker: ConstraintChecker, + private val danaRPump: DanaRPump, + private var amount: Double +) : MessageBase() { + + init { + SetCommand(0x0102) + // HARDCODED LIMIT + amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + AddParamInt((amount * 100).toInt()) + aapsLogger.debug(LTag.PUMPBTCOMM, "Bolus start : $amount") + } + + override fun handleMessage(bytes: ByteArray) { + val errorCode = intFromBuff(bytes, 0, 1) + if (errorCode != 2) { + failed = true + aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode FAILED!!") + } else { + aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode OK") + } + danaRPump.messageStartErrorCode = errorCode + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java deleted file mode 100644 index f609d1daba..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java +++ /dev/null @@ -1,45 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; - -public class MsgBolusStartWithSpeed extends MessageBase { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - - public static int errorCode; - - public MsgBolusStartWithSpeed() { - SetCommand(0x0104); - } - - public MsgBolusStartWithSpeed(double amount, int speed) { - this(); - - // HARDCODED LIMIT - amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); - - AddParamInt((int) (amount * 100)); - AddParamByte((byte) speed); - - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Bolus start : " + amount + " speed: " + speed); - } - - @Override - public void handleMessage(byte[] bytes) { - errorCode = intFromBuff(bytes, 0, 1); - if (errorCode != 2) { - failed = true; - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Messsage response: " + errorCode + " FAILED!!"); - } else { - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Messsage response: " + errorCode + " OK"); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt new file mode 100644 index 0000000000..f8490121ef --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.plugins.pump.danaR.comm + +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump + +class MsgBolusStartWithSpeed( + private val aapsLogger: AAPSLogger, + constraintChecker: ConstraintChecker, + private val danaRPump: DanaRPump, + private var amount: Double, + speed: Int +) : MessageBase() { + + init { + SetCommand(0x0104) + // HARDCODED LIMIT + amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + AddParamInt((amount * 100).toInt()) + AddParamByte(speed.toByte()) + aapsLogger.debug(LTag.PUMPBTCOMM, "Bolus start : $amount speed: $speed") + } + + override fun handleMessage(bytes: ByteArray) { + val errorCode = intFromBuff(bytes, 0, 1) + if (errorCode != 2) { + failed = true + aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode FAILED!!") + } else { + aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode OK") + } + danaRPump.messageStartErrorCode = errorCode + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java deleted file mode 100644 index b7cc8eefd3..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java +++ /dev/null @@ -1,45 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; - -public class MsgSetExtendedBolusStart extends MessageBase { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - - public MsgSetExtendedBolusStart() { - SetCommand(0x0407); - if (L.isEnabled(L.PUMPCOMM)) - log.debug("New message"); - } - - public MsgSetExtendedBolusStart(double amount, byte halfhours) { - this(); - - // HARDCODED LIMITS - if (halfhours < 1) halfhours = 1; - if (halfhours > 16) halfhours = 16; - Constraint constrainedAmount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)); - AddParamInt((int) (constrainedAmount.value() * 100)); - AddParamByte(halfhours); - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Set extended bolus start: " + (((int) (amount * 100)) / 100d) + "U halfhours: " + (int) halfhours); - } - - @Override - public void handleMessage(byte[] bytes) { - int result = intFromBuff(bytes, 0, 1); - if (result != 1) { - failed = true; - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Set extended bolus start result: " + result + " FAILED!!!"); - } else { - if (L.isEnabled(L.PUMPCOMM)) - log.debug("Set extended bolus start result: " + result); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.kt new file mode 100644 index 0000000000..23da6ede84 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.plugins.pump.danaR.comm + +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker + +class MsgSetExtendedBolusStart( + private val aapsLogger: AAPSLogger, + constraintChecker: ConstraintChecker, + private var amount: Double, + private var halfhours: Byte + +) : MessageBase() { + + init { + SetCommand(0x0407) + aapsLogger.debug(LTag.PUMPBTCOMM, "New message") + // HARDCODED LIMITS + if (halfhours < 1) halfhours = 1 + if (halfhours > 16) halfhours = 16 + amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + AddParamInt((amount * 100).toInt()) + AddParamByte(halfhours) + aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start: " + (amount * 100).toInt() / 100.0 + "U halfhours: " + halfhours.toInt()) + } + + override fun handleMessage(bytes: ByteArray) { + val result = intFromBuff(bytes, 0, 1) + if (result != 1) { + failed = true + aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start result: $result FAILED!!!") + } else { + aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start result: $result") + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index 3964328ffc..cdaab36c50 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -27,6 +27,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -81,6 +82,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; + @Inject ConstraintChecker constraintChecker; @Inject DanaRPump danaRPump; @Inject DanaRPlugin danaRPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; @@ -287,7 +289,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); - mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); + mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -315,9 +317,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); MessageBase start; if (preferencesSpeed == 0) - start = new MsgBolusStart(amount); + start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount); else - start = new MsgBolusStartWithSpeed(amount, preferencesSpeed); + start = new MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, amount, preferencesSpeed); MsgBolusStop stop = new MsgBolusStop(amount, t); if (carbs > 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java index ec92e503c1..9f80b1fc30 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java @@ -11,6 +11,7 @@ import androidx.annotation.NonNull; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -30,7 +31,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStart; import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -55,6 +55,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { @Inject public DanaRKoreanPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, DanaRPump danaRPump, @@ -66,7 +67,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { CommandQueueProvider commandQueue ) { - super(danaRPump, resourceHelper, aapsLogger, commandQueue); + super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue); this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.mainApp = maiApp; @@ -174,7 +175,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; if (!result.success) - result.comment = resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, MsgBolusStart.errorCode); + result.comment = resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaRPump.getMessageStartErrorCode()); else result.comment = resourceHelper.gs(R.string.virtualpump_resultok); aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt index 920c9d27a5..3face0c2df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt @@ -5,6 +5,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaR.comm.* @@ -19,6 +20,7 @@ class MessageHashTableRKorean @Inject constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, resourceHelper: ResourceHelper, + constraintChecker: ConstraintChecker, danaRPump: DanaRPump, danaRPlugin: DanaRPlugin, danaRKoreanPlugin: DanaRKoreanPlugin, @@ -31,7 +33,7 @@ class MessageHashTableRKorean @Inject constructor( init { put(MsgBolusStop()) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart()) // 0x0102 CMD_MEALINS_START_DATA + put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA put(MsgBolusProgress()) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)) // 0x0205 CMD_PUMP_EXERCISE_MODE @@ -45,7 +47,7 @@ class MessageHashTableRKorean @Inject constructor( put(MsgSetCarbsEntry()) // 0x0402 CMD_PUMPSET_HIS_S put(MsgSetTempBasalStop()) // 0x0403 CMD_PUMPSET_EXERCISE_STOP put(MsgSetExtendedBolusStop()) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart()) // 0x0407 CMD_PUMPSET_EXPANS_INS_S + put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S put(MsgError()) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS put(MsgPCCommStart()) // 0x3001 CMD_CONNECT put(MsgPCCommStop()) // 0x3002 CMD_DISCONNECT diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt index 0b6d4fd6ab..13b29aba9c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt @@ -11,7 +11,6 @@ class MsgSettingBasal_k( private val aapsLogger: AAPSLogger, private val danaRPump: DanaRPump, private val danaRKoreanPlugin: DanaRKoreanPlugin - ) : MessageBase() { init { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index a8db0b7fe4..6a59b320cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -27,6 +27,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -73,6 +74,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; + @Inject ConstraintChecker constraintChecker; @Inject DanaRPump danaRPump; @Inject DanaRPlugin danaRPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; @@ -277,7 +279,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); - mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); + mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -302,7 +304,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (BolusProgressDialog.stopPressed) return false; mBolusingTreatment = t; - MsgBolusStart start = new MsgBolusStart(amount); + MsgBolusStart start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount); MsgBolusStop stop = new MsgBolusStop(amount, t); if (carbs > 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 9c69e4c7d2..9c4509c092 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -18,6 +18,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -99,6 +100,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @Inject public DanaRSPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, Context context, @@ -117,7 +119,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR .shortName(R.string.danarspump_shortname) .preferencesId(R.xml.pref_danars) .description(R.string.description_pump_dana_rs), - aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, resourceHelper, commandQueue ); this.context = context; this.rxBus = rxBus; @@ -257,15 +259,15 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @NonNull @Override public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfSmaller(danaRPump.getMaxBasal(), resourceHelper.gs(R.string.limitingbasalratio, danaRPump.getMaxBasal(), resourceHelper.gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), resourceHelper.gs(R.string.limitingbasalratio, danaRPump.getMaxBasal(), resourceHelper.gs(R.string.pumplimit)), this); return absoluteRate; } @NonNull @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(getAapsLogger(), 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); return percentRate; } @@ -274,7 +276,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @NonNull @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller(danaRPump.getMaxBolus(), resourceHelper.gs(R.string.limitingbolus, danaRPump.getMaxBolus(), resourceHelper.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), resourceHelper.gs(R.string.limitingbolus, danaRPump.getMaxBolus(), resourceHelper.gs(R.string.pumplimit)), this); return insulin; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index ebd46d14f9..50db0d1f8c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -11,6 +11,7 @@ import androidx.annotation.NonNull; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -55,6 +56,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { @Inject public DanaRv2Plugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, MainApp maiApp, @@ -66,7 +68,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { CommandQueueProvider commandQueue ) { - super(danaRPump, resourceHelper, aapsLogger, commandQueue); + super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue); this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.mainApp = maiApp; @@ -188,7 +190,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; if (!result.success) - result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStartWithSpeed.errorCode); + result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, danaRPump.getMessageStartErrorCode()); else result.comment = resourceHelper.gs(R.string.virtualpump_resultok); aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt index 7daa347b34..80e32d1941 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt @@ -5,6 +5,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaR.comm.* @@ -20,6 +21,7 @@ class MessageHashTableRv2 @Inject constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, resourceHelper: ResourceHelper, + constraintChecker: ConstraintChecker, danaRPump: DanaRPump, danaRPlugin: DanaRPlugin, danaRKoreanPlugin: DanaRKoreanPlugin, @@ -33,8 +35,8 @@ class MessageHashTableRv2 @Inject constructor( init { put(MsgBolusStop()) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart()) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusStartWithSpeed()) // 0x0104 CMD_MEALINS_START_DATA_SPEED + put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA + put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED put(MsgBolusProgress()) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING put(MsgStatusTempBasal_v2(aapsLogger, danaRPump)) // 0x0205 CMD_PUMP_EXERCISE_MODE @@ -49,7 +51,7 @@ class MessageHashTableRv2 @Inject constructor( put(MsgSetCarbsEntry()) // 0x0402 CMD_PUMPSET_HIS_S put(MsgSetTempBasalStop()) // 0x0403 CMD_PUMPSET_EXERCISE_STOP put(MsgSetExtendedBolusStop()) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart()) // 0x0407 CMD_PUMPSET_EXPANS_INS_S + put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S put(MsgError()) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS put(MsgPCCommStart()) // 0x3001 CMD_CONNECT put(MsgPCCommStop()) // 0x3002 CMD_DISCONNECT diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 3041cf255d..1c4fcd6096 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -29,6 +29,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -89,6 +90,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; + @Inject ConstraintChecker constraintChecker; @Inject DanaRPump danaRPump; @Inject DanaRPlugin danaRPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; @@ -358,7 +360,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); - mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); + mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended_v2(aapsLogger, danaRPump)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -384,9 +386,9 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { final int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); MessageBase start; if (preferencesSpeed == 0) - start = new MsgBolusStart(amount); + start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount); else - start = new MsgBolusStartWithSpeed(amount, preferencesSpeed); + start = new MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, amount, preferencesSpeed); MsgBolusStop stop = new MsgBolusStop(amount, t); if (carbs > 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index bbe64d907a..fd4bba0fd1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -13,7 +13,6 @@ import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Calendar; @@ -25,6 +24,7 @@ import java.util.TimeZone; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; @@ -198,6 +198,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @Inject public LocalInsightPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, @@ -213,7 +214,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, .description(R.string.description_pump_insight_local) .fragmentClass(LocalInsightFragment.class.getName()) .preferencesId(Config.APS ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol), - aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, resourceHelper, commandQueue ); @@ -1596,22 +1597,22 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - percentRate.setIfGreater(0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); return percentRate; } @Override public Constraint applyBolusConstraints(Constraint insulin) { if (!limitsFetched) return insulin; - insulin.setIfSmaller(maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); if (insulin.value() < minimumBolusAmount) { //TODO: Add function to Constraints or use different approach // This only works if the interface of the InsightPlugin is called last. // If not, another constraint could theoretically set the value between 0 and minimumBolusAmount - insulin.set(0d, String.format(resourceHelper.gs(R.string.limitingbolus), minimumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); + insulin.set(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbolus), minimumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); } return insulin; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java index c1419c25b8..95b83e4e71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java @@ -5,13 +5,13 @@ import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -49,6 +49,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @Inject public MDIPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, @@ -58,7 +59,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { .mainType(PluginType.PUMP) .pluginName(R.string.mdi) .description(R.string.description_pump_mdi), - aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, resourceHelper, commandQueue ); pumpDescription.isBolusCapable = true; pumpDescription.bolusStep = 0.5d; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index 9e1f588a41..155813defe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -10,7 +10,6 @@ import androidx.annotation.NonNull; import org.joda.time.LocalDateTime; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; @@ -27,6 +26,7 @@ import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.ErrorHelperActivity; @@ -130,6 +130,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Inject public MedtronicPumpPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, MainApp maiApp, @@ -148,7 +149,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .shortName(R.string.medtronic_name_short) // .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 - resourceHelper, aapsLogger, commandQueue + injector, resourceHelper, aapsLogger, commandQueue ); this.plugin = this; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index ced9a618b0..3590a97ffa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.pump.virtual import android.os.SystemClock +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.R @@ -41,6 +42,7 @@ import kotlin.math.min @Singleton class VirtualPumpPlugin @Inject constructor( + injector:HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBusWrapper, private var fabricPrivacy: FabricPrivacy, @@ -57,7 +59,7 @@ class VirtualPumpPlugin @Inject constructor( .preferencesId(R.xml.pref_virtualpump) .neverVisible(Config.NSCLIENT) .description(R.string.description_pump_virtual), - aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, resourceHelper, commandQueue ), PumpInterface { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt index 540f669e02..43e8b89a5d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.sensitivity +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription @@ -12,8 +13,17 @@ import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP +import kotlin.math.max +import kotlin.math.min -abstract class AbstractSensitivityPlugin(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, val sp: SP) : PluginBase(pluginDescription, aapsLogger, resourceHelper), SensitivityInterface { +abstract class AbstractSensitivityPlugin( + pluginDescription: PluginDescription, + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: + ResourceHelper, + val sp: SP +) : PluginBase(pluginDescription, aapsLogger, resourceHelper, injector), SensitivityInterface { abstract override fun detectSensitivity(plugin: IobCobCalculatorPlugin, fromTime: Long, toTime: Long): AutosensResult @@ -25,19 +35,19 @@ abstract class AbstractSensitivityPlugin(pluginDescription: PluginDescription, a SafeParse.stringToDouble(sp.getString(R.string.key_openapsama_autosens_max, "1.2"))) } - fun fillResult(ratio: Double, carbsAbsorbed: Double, pastSensitivity: String, - ratioLimit: String, sensResult: String, deviationsArraySize: Int, + fun fillResult(ratioParam: Double, carbsAbsorbed: Double, pastSensitivity: String, + ratioLimitParam: String, sensResult: String, deviationsArraySize: Int, ratioMin: Double, ratioMax: Double): AutosensResult { - var ratio = ratio - var ratioLimit = ratioLimit + var ratio = ratioParam + var ratioLimit = ratioLimitParam val rawRatio = ratio - ratio = Math.max(ratio, ratioMin) - ratio = Math.min(ratio, ratioMax) + ratio = max(ratio, ratioMin) + ratio = min(ratio, ratioMax) //If not-excluded data <= MIN_HOURS -> don't do Autosens //If not-excluded data >= MIN_HOURS_FULL_AUTOSENS -> full Autosens //Between MIN_HOURS and MIN_HOURS_FULL_AUTOSENS: gradually increase autosens - val autosensContrib = (Math.min(Math.max(SensitivityInterface.MIN_HOURS, deviationsArraySize / 12.0), + val autosensContrib = (min(max(SensitivityInterface.MIN_HOURS, deviationsArraySize / 12.0), SensitivityInterface.MIN_HOURS_FULL_AUTOSENS) - SensitivityInterface.MIN_HOURS) / (SensitivityInterface.MIN_HOURS_FULL_AUTOSENS - SensitivityInterface.MIN_HOURS) ratio = autosensContrib * (ratio - 1) + 1 if (autosensContrib != 1.0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java index 321a75b6e5..da8e7ff064 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java @@ -9,6 +9,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -37,6 +38,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { @Inject public SensitivityAAPSPlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp @@ -47,7 +49,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_aaps), - aapsLogger, resourceHelper, sp + injector, aapsLogger, resourceHelper, sp ); this.sp = sp; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java index 8575ef0056..5dfc0e888e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref0Plugin.java @@ -10,6 +10,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -37,6 +38,7 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { @Inject public SensitivityOref0Plugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp, @@ -48,7 +50,7 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_oref0) .description(R.string.description_sensitivity_oref0), - aapsLogger, resourceHelper, sp + injector, aapsLogger, resourceHelper, sp ); this.profileFunction = profileFunction; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java index 6edc42ec91..63286fd858 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java @@ -9,6 +9,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -34,6 +35,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { @Inject public SensitivityOref1Plugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp @@ -45,7 +47,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { .enableByDefault(true) .preferencesId(R.xml.pref_absorption_oref1) .description(R.string.description_sensitivity_oref1), - aapsLogger, resourceHelper, sp + injector, aapsLogger, resourceHelper, sp ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java index 3a560eca21..d42ac85436 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java @@ -7,6 +7,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -36,6 +37,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin @Inject public SensitivityWeightedAveragePlugin( + HasAndroidInjector injector, AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp, @@ -47,7 +49,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_weighted_average), - aapsLogger, resourceHelper, sp + injector, aapsLogger, resourceHelper, sp ); this.sp = sp; this.resourceHelper = resourceHelper; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index 7a34e3eff0..64201bd363 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent import android.content.pm.PackageManager import androidx.core.content.ContextCompat +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -10,7 +11,6 @@ import info.nightscout.androidaps.activities.RequestDexcomPermissionActivity import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source -import info.nightscout.androidaps.dialogs.CareDialog import info.nightscout.androidaps.interfaces.BgSourceInterface import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription @@ -27,6 +27,7 @@ import javax.inject.Singleton @Singleton class DexcomPlugin @Inject constructor( + injector: HasAndroidInjector, private val sp: SP, private val mainApp: MainApp, resourceHelper: ResourceHelper, @@ -38,7 +39,8 @@ class DexcomPlugin @Inject constructor( .shortName(R.string.dexcom_short) .preferencesId(R.xml.pref_bgsourcedexcom) .description(R.string.description_source_dexcom), - aapsLogger, resourceHelper), BgSourceInterface { + aapsLogger, resourceHelper, injector +), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { return true diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index bb4ff464d9..49e6ddbab8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -26,6 +27,7 @@ import javax.inject.Singleton @Singleton class EversensePlugin @Inject constructor( + injector: HasAndroidInjector, private val sp: SP, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger @@ -36,8 +38,7 @@ class EversensePlugin @Inject constructor( .shortName(R.string.eversense_shortname) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_eversense), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt index 8810dc1e31..c2cd1d84e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -17,6 +18,7 @@ import javax.inject.Singleton @Singleton class GlimpPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() @@ -25,8 +27,7 @@ class GlimpPlugin @Inject constructor( .pluginName(R.string.Glimp) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_glimp), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt index 1a79c9a333..4d082c0133 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -18,6 +19,7 @@ import javax.inject.Singleton @Singleton class MM640gPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() @@ -25,8 +27,7 @@ class MM640gPlugin @Inject constructor( .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.MM640g) .description(R.string.description_source_mm640g), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt index c3159b97e9..aa498105a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -22,6 +23,7 @@ import javax.inject.Singleton @Singleton class NSClientSourcePlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP @@ -30,8 +32,7 @@ class NSClientSourcePlugin @Inject constructor( .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.nsclientbg) .description(R.string.description_source_ns_client), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { private var lastBGTimeStamp: Long = 0 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index fb61989e10..c33cfaee0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -22,6 +23,7 @@ import javax.inject.Singleton @Singleton class PoctechPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP @@ -31,8 +33,7 @@ class PoctechPlugin @Inject constructor( .pluginName(R.string.poctech) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_poctech), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index fbcff9b031..4e0192fc4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent import android.os.Handler +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -24,6 +25,7 @@ import kotlin.math.sin @Singleton class RandomBgPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, private var virtualPumpPlugin: VirtualPumpPlugin @@ -33,8 +35,7 @@ class RandomBgPlugin @Inject constructor( .pluginName(R.string.randombg) .shortName(R.string.randombg_short) .description(R.string.description_source_randombg), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { private val loopHandler = Handler() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index de10ce0ebf..db4c658614 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -18,6 +19,7 @@ import javax.inject.Singleton @Singleton class TomatoPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP @@ -28,8 +30,7 @@ class TomatoPlugin @Inject constructor( .preferencesId(R.xml.pref_bgsource) .shortName(R.string.tomato_short) .description(R.string.description_source_tomato), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { override fun advancedFilteringSupported(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt index 47fe68a2fc..aaf38b93b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -18,6 +19,7 @@ import javax.inject.Singleton @Singleton class XdripPlugin @Inject constructor( + injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() @@ -25,8 +27,7 @@ class XdripPlugin @Inject constructor( .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.xdrip) .description(R.string.description_source_xdrip), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ), BgSourceInterface { private var advancedFiltering = false diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 0c6832fdbc..cc5b11510f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -16,6 +16,7 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -98,13 +99,15 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final ProfileIntervals profiles = new ProfileIntervals<>(); @Inject - public TreatmentsPlugin(AAPSLogger aapsLogger, - RxBusWrapper rxBus, - ResourceHelper resourceHelper, - MainApp mainApp, - SP sp, - ProfileFunction profileFunction, - ConfigBuilderPlugin configBuilderPlugin + public TreatmentsPlugin( + HasAndroidInjector injector, + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + ResourceHelper resourceHelper, + MainApp mainApp, + SP sp, + ProfileFunction profileFunction, + ConfigBuilderPlugin configBuilderPlugin ) { super(new PluginDescription() .mainType(PluginType.TREATMENT) @@ -113,8 +116,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .shortName(R.string.treatments_shortname) .alwaysEnabled(true) .description(R.string.description_treatments), - aapsLogger, - resourceHelper + aapsLogger, resourceHelper, injector ); this.resourceHelper = resourceHelper; this.mainApp = mainApp; diff --git a/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt b/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt index 830053bef0..4ce0071900 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.utils +import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.DialogInterface @@ -16,18 +17,19 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R object OKDialog { + @SuppressLint("InflateParams") @JvmStatic @JvmOverloads fun show(context: Context, title: String, message: String, runnable: Runnable? = null) { var notEmptytitle = title - if (notEmptytitle.isEmpty()) notEmptytitle = MainApp.gs(R.string.message) + if (notEmptytitle.isEmpty()) notEmptytitle = context.getString(R.string.message) val titleLayout = LayoutInflater.from(context).inflate(R.layout.dialog_alert_custom, null) (titleLayout.findViewById(R.id.alertdialog_title) as TextView).text = notEmptytitle (titleLayout.findViewById(R.id.alertdialog_icon) as ImageView).setImageResource(R.drawable.ic_check_while_48dp) AlertDialog.Builder(ContextThemeWrapper(context, R.style.AppTheme)) .setCustomTitle(titleLayout) .setMessage(message) - .setPositiveButton(MainApp.gs(R.string.ok)) { dialog: DialogInterface, _: Int -> + .setPositiveButton(context.getString(R.string.ok)) { dialog: DialogInterface, _: Int -> dialog.dismiss() SystemClock.sleep(100) runOnUiThread(runnable) @@ -41,18 +43,19 @@ object OKDialog { theRunnable?.let { mainHandler.post(it) } } + @SuppressLint("InflateParams") @JvmStatic @JvmOverloads fun show(activity: Activity, title: String, message: Spanned, runnable: Runnable? = null) { var notEmptytitle = title - if (notEmptytitle.isEmpty()) notEmptytitle = MainApp.gs(R.string.message) + if (notEmptytitle.isEmpty()) notEmptytitle = activity.getString(R.string.message) val titleLayout = activity.layoutInflater.inflate(R.layout.dialog_alert_custom, null) (titleLayout.findViewById(R.id.alertdialog_title) as TextView).text = notEmptytitle (titleLayout.findViewById(R.id.alertdialog_icon) as ImageView).setImageResource(R.drawable.ic_check_while_48dp) AlertDialog.Builder(ContextThemeWrapper(activity, R.style.AppTheme)) .setCustomTitle(titleLayout) .setMessage(message) - .setPositiveButton(MainApp.gs(R.string.ok)) { dialog: DialogInterface, _: Int -> + .setPositiveButton(activity.getString(R.string.ok)) { dialog: DialogInterface, _: Int -> dialog.dismiss() SystemClock.sleep(100) runnable?.let { activity.runOnUiThread(it) } @@ -63,14 +66,15 @@ object OKDialog { @JvmStatic fun showConfirmation(activity: Activity, message: String, ok: Runnable?) { - showConfirmation(activity, MainApp.gs(R.string.confirmation), message, ok, null) + showConfirmation(activity, activity.getString(R.string.confirmation), message, ok, null) } @JvmStatic fun showConfirmation(activity: Activity, message: Spanned, ok: Runnable?) { - showConfirmation(activity, MainApp.gs(R.string.confirmation), message, ok, null) + showConfirmation(activity, activity.getString(R.string.confirmation), message, ok, null) } + @SuppressLint("InflateParams") @JvmStatic @JvmOverloads fun showConfirmation(activity: Activity, title: String, message: Spanned, ok: Runnable?, cancel: Runnable? = null) { @@ -95,6 +99,7 @@ object OKDialog { .setCanceledOnTouchOutside(false) } + @SuppressLint("InflateParams") @JvmStatic fun showConfirmation(activity: Activity, title: String, message: String, ok: Runnable?, cancel: Runnable? = null) { val titleLayout = activity.layoutInflater.inflate(R.layout.dialog_alert_custom, null) @@ -120,9 +125,10 @@ object OKDialog { @JvmStatic @JvmOverloads fun showConfirmation(context: Context, message: Spanned, ok: Runnable?, cancel: Runnable? = null) { - showConfirmation(context, MainApp.gs(R.string.confirmation), message, ok, cancel) + showConfirmation(context, context.getString(R.string.confirmation), message, ok, cancel) } + @SuppressLint("InflateParams") @JvmStatic @JvmOverloads fun showConfirmation(context: Context, title: String, message: Spanned, ok: Runnable?, cancel: Runnable? = null) { @@ -150,9 +156,10 @@ object OKDialog { @JvmStatic @JvmOverloads fun showConfirmation(context: Context, message: String, ok: Runnable?, cancel: Runnable? = null) { - showConfirmation(context, MainApp.gs(R.string.confirmation), message, ok, cancel) + showConfirmation(context, context.getString(R.string.confirmation), message, ok, cancel) } + @SuppressLint("InflateParams") @JvmStatic @JvmOverloads fun showConfirmation(context: Context, title: String, message: String, ok: Runnable?, cancel: Runnable? = null) { @@ -176,6 +183,7 @@ object OKDialog { .setCanceledOnTouchOutside(false) } + @SuppressLint("InflateParams") @JvmStatic @JvmOverloads fun showConfirmation(context: Context, title: String, message: String, ok: DialogInterface.OnClickListener?, cancel: DialogInterface.OnClickListener? = null) { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 2553c1a816..2d13e492dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.utils.stats import android.text.Spanned import android.util.LongSparseArray +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.TDD @@ -21,6 +22,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class TddCalculator @Inject constructor( + injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBusWrapper, resourceHelper: ResourceHelper, @@ -28,7 +30,7 @@ class TddCalculator @Inject constructor( val sp: SP, val configBuilderPlugin: ConfigBuilderPlugin, val profileFunction: ProfileFunction -) : TreatmentsPlugin(aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, configBuilderPlugin) { +) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, configBuilderPlugin) { init { service = TreatmentService() // plugin is not started diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java index 544473dbaa..a775f4ab9d 100644 --- a/app/src/test/java/info/AAPSMocker.java +++ b/app/src/test/java/info/AAPSMocker.java @@ -180,14 +180,6 @@ public class AAPSMocker { when(ConfigBuilderPlugin.getPlugin()).thenReturn(configBuilderPlugin); } - public static ConstraintChecker mockConstraintsChecker() { - PowerMockito.mockStatic(ConstraintChecker.class); - constraintChecker = mock(ConstraintChecker.class); - when(ConstraintChecker.getInstance()) - .thenReturn(constraintChecker); - return constraintChecker; - } - public static void mockSP() { PowerMockito.mockStatic(SP.class); when(SP.getLong(anyInt(), anyLong())).thenReturn(0L); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt index 8fab2d46bb..5c764bb6f4 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt @@ -47,8 +47,8 @@ class DanaRSPluginTest : DanaRSTestBase() { val c = Constraint(Constants.REALLYHIGHBASALRATE) danaRSPlugin.applyBasalConstraints(c, AAPSMocker.getValidProfile()) Assert.assertEquals(java.lang.Double.valueOf(0.8), c.value(), 0.0001) - Assert.assertEquals("DanaRS: limitingbasalratio", c.reasons) - Assert.assertEquals("DanaRS: limitingbasalratio", c.mostLimitedReasons) + Assert.assertEquals("DanaRS: limitingbasalratio", c.getReasons(aapsLogger)) + Assert.assertEquals("DanaRS: limitingbasalratio", c.getMostLimitedReasons(aapsLogger)) } @Test @@ -59,8 +59,8 @@ class DanaRSPluginTest : DanaRSTestBase() { val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) danaRSPlugin.applyBasalPercentConstraints(c, AAPSMocker.getValidProfile()) Assert.assertEquals(200, c.value()) - Assert.assertEquals("DanaRS: limitingpercentrate", c.reasons) - Assert.assertEquals("DanaRS: limitingpercentrate", c.mostLimitedReasons) + Assert.assertEquals("DanaRS: limitingpercentrate", c.getReasons(aapsLogger)) + Assert.assertEquals("DanaRS: limitingpercentrate", c.getMostLimitedReasons(aapsLogger)) } @Before From f19e782c7cd9c5cd5b1bb1e7073db4ee012ecd44 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 9 Mar 2020 00:28:51 +0100 Subject: [PATCH 044/100] ActionLoopDisableTest --- .../androidaps/data/PumpEnactResult.java | 13 ++-- .../plugins/aps/loop/LoopPlugin.java | 26 ++++---- .../automation/actions/ActionLoopDisable.kt | 2 +- .../automation/actions/ActionLoopEnable.kt | 4 +- .../automation/actions/ActionLoopResume.kt | 4 +- .../automation/actions/ActionLoopSuspend.kt | 4 +- .../automation/actions/ActionNotification.kt | 2 +- .../automation/actions/ActionProfileSwitch.kt | 10 +-- .../actions/ActionProfileSwitchPercent.kt | 2 +- .../automation/actions/ActionSendSMS.kt | 2 +- .../actions/ActionStartTempTarget.kt | 2 +- .../actions/ActionStopTempTarget.kt | 2 +- .../plugins/pump/combo/ComboPlugin.java | 66 +++++++++---------- .../pump/common/PumpPluginAbstract.java | 8 +-- .../pump/danaR/AbstractDanaRPlugin.java | 8 +-- .../plugins/pump/danaR/DanaRPlugin.java | 10 +-- .../AbstractDanaRExecutionService.java | 18 +++-- .../danaR/services/DanaRExecutionService.java | 33 ++++------ .../pump/danaRKorean/DanaRKoreanPlugin.java | 10 +-- .../services/DanaRKoreanExecutionService.java | 21 +++--- .../plugins/pump/danaRS/DanaRSPlugin.java | 18 ++--- .../pump/danaRS/services/DanaRSService.java | 10 +-- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 13 ++-- .../services/DanaRv2ExecutionService.java | 43 ++++++------ .../pump/insight/LocalInsightPlugin.java | 25 ++++--- .../plugins/pump/mdi/MDIPlugin.java | 16 ++--- .../pump/medtronic/MedtronicPumpPlugin.java | 42 ++++++------ .../plugins/pump/virtual/VirtualPumpPlugin.kt | 14 ++-- .../androidaps/queue/CommandQueue.kt | 10 +-- .../androidaps/queue/commands/Command.kt | 4 +- .../queue/commands/CommandReadStatus.kt | 2 +- .../queue/commands/CommandSMBBolus.kt | 4 +- .../queue/commands/CommandSetProfile.kt | 2 +- app/src/test/java/info/TestBase.kt | 6 ++ .../actions/ActionLoopDisableTest.kt | 50 ++++++++------ .../plugins/pump/danaRS/DanaRSPluginTest.kt | 4 +- ...S_Packet_Bolus_Set_Step_Bolus_StartTest.kt | 4 +- ...RS_Packet_Bolus_Set_Step_Bolus_StopTest.kt | 1 - ...Packet_Notify_Delivery_Rate_DisplayTest.kt | 2 +- 39 files changed, 263 insertions(+), 254 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index edfe7cfc35..00cfb1e6bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -5,6 +5,7 @@ import org.json.JSONObject; import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -12,8 +13,8 @@ import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; public class PumpEnactResult { - @Inject AAPSLogger aapsLogger; - @Inject ResourceHelper resourceHelper; + @Inject public AAPSLogger aapsLogger; + @Inject public ResourceHelper resourceHelper; public boolean success = false; // request was processed successfully (but possible no change was needed) public boolean enacted = false; // request was processed successfully and change has been made @@ -31,6 +32,10 @@ public class PumpEnactResult { public boolean queued = false; + public PumpEnactResult(HasAndroidInjector injector) { + injector.androidInjector().inject(this); + } + public PumpEnactResult success(boolean success) { this.success = success; return this; @@ -192,8 +197,4 @@ public class PumpEnactResult { } return result; } - - public static PumpEnactResult error(String message) { - return new PumpEnactResult().enacted(false).success(false).comment(message); - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 7cca957301..40ba607cd1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -408,7 +408,7 @@ public class LoopPlugin extends PluginBase { if (resultAfterConstraints.isChangeRequested() && !commandQueue.bolusInQueue() && !commandQueue.isRunning(Command.CommandType.BOLUS)) { - final PumpEnactResult waiting = new PumpEnactResult(); + final PumpEnactResult waiting = new PumpEnactResult(getInjector()); waiting.queued = true; if (resultAfterConstraints.tempBasalRequested) lastRun.tbrSetByPump = waiting; @@ -532,7 +532,7 @@ public class LoopPlugin extends PluginBase { if (!request.tempBasalRequested) { if (callback != null) { - callback.result(new PumpEnactResult().enacted(false).success(true).comment(resourceHelper.gs(R.string.nochangerequested))).run(); + callback.result(new PumpEnactResult(getInjector()).enacted(false).success(true).comment(resourceHelper.gs(R.string.nochangerequested))).run(); } return; } @@ -540,14 +540,14 @@ public class LoopPlugin extends PluginBase { PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); if (pump == null) { if (callback != null) - callback.result(new PumpEnactResult().enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run(); + callback.result(new PumpEnactResult(getInjector()).enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run(); return; } if (!pump.isInitialized()) { getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpNotInitialized)); if (callback != null) { - callback.result(new PumpEnactResult().comment(resourceHelper.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); + callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); } return; } @@ -555,7 +555,7 @@ public class LoopPlugin extends PluginBase { if (pump.isSuspended()) { getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpsuspended)); if (callback != null) { - callback.result(new PumpEnactResult().comment(resourceHelper.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); + callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); } return; } @@ -572,7 +572,7 @@ public class LoopPlugin extends PluginBase { } else { getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly"); if (callback != null) { - callback.result(new PumpEnactResult().percent(request.percent).duration(0) + callback.result(new PumpEnactResult(getInjector()).percent(request.percent).duration(0) .enacted(false).success(true).comment(resourceHelper.gs(R.string.basal_set_correctly))).run(); } } @@ -582,7 +582,7 @@ public class LoopPlugin extends PluginBase { && request.percent == activeTemp.percentRate) { getAapsLogger().debug(LTag.APS, "applyAPSRequest: Temp basal set correctly"); if (callback != null) { - callback.result(new PumpEnactResult().percent(request.percent) + callback.result(new PumpEnactResult(getInjector()).percent(request.percent) .enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes()) .comment(resourceHelper.gs(R.string.let_temp_basal_run))).run(); } @@ -598,7 +598,7 @@ public class LoopPlugin extends PluginBase { } else { getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly"); if (callback != null) { - callback.result(new PumpEnactResult().absolute(request.rate).duration(0) + callback.result(new PumpEnactResult(getInjector()).absolute(request.rate).duration(0) .enacted(false).success(true).comment(resourceHelper.gs(R.string.basal_set_correctly))).run(); } } @@ -608,7 +608,7 @@ public class LoopPlugin extends PluginBase { && Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) { getAapsLogger().debug(LTag.APS, "applyAPSRequest: Temp basal set correctly"); if (callback != null) { - callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile)) + callback.result(new PumpEnactResult(getInjector()).absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile)) .enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes()) .comment(resourceHelper.gs(R.string.let_temp_basal_run))).run(); } @@ -627,7 +627,7 @@ public class LoopPlugin extends PluginBase { PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); if (pump == null) { if (callback != null) - callback.result(new PumpEnactResult().enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run(); + callback.result(new PumpEnactResult(getInjector()).enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run(); return; } @@ -635,7 +635,7 @@ public class LoopPlugin extends PluginBase { if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { getAapsLogger().debug(LTag.APS, "SMB requested but still in 3 min interval"); if (callback != null) { - callback.result(new PumpEnactResult() + callback.result(new PumpEnactResult(getInjector()) .comment(resourceHelper.gs(R.string.smb_frequency_exceeded)) .enacted(false).success(false)).run(); } @@ -645,7 +645,7 @@ public class LoopPlugin extends PluginBase { if (!pump.isInitialized()) { getAapsLogger().debug(LTag.APS, "applySMBRequest: " + resourceHelper.gs(R.string.pumpNotInitialized)); if (callback != null) { - callback.result(new PumpEnactResult().comment(resourceHelper.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); + callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); } return; } @@ -653,7 +653,7 @@ public class LoopPlugin extends PluginBase { if (pump.isSuspended()) { getAapsLogger().debug(LTag.APS, "applySMBRequest: " + resourceHelper.gs(R.string.pumpsuspended)); if (callback != null) { - callback.result(new PumpEnactResult().comment(resourceHelper.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); + callback.result(new PumpEnactResult(getInjector()).comment(resourceHelper.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); } return; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt index b55ce9c177..bc6f7a6fb8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt @@ -36,7 +36,7 @@ class ActionLoopDisable(injector: HasAndroidInjector) : Action(injector) { } }) } else { - callback.result(PumpEnactResult().success(true).comment(R.string.alreadydisabled)).run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadydisabled)).run() } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt index eb40388b44..4b94520523 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt @@ -28,9 +28,9 @@ class ActionLoopEnable(injector: HasAndroidInjector) : Action(injector) { loopPlugin.setPluginEnabled(PluginType.LOOP, true) configBuilderPlugin.storeSettings("ActionLoopEnable") rxBus.send(EventRefreshOverview("ActionLoopEnable")) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } else { - callback.result(PumpEnactResult().success(true).comment(R.string.alreadyenabled))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadyenabled))?.run() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt index 49a4a0dbd8..4e155bcdcc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt @@ -29,9 +29,9 @@ class ActionLoopResume(injector: HasAndroidInjector) : Action(injector) { configBuilderPlugin.storeSettings("ActionLoopResume") loopPlugin.createOfflineEvent(0) rxBus.send(EventRefreshOverview("ActionLoopResume")) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } else { - callback.result(PumpEnactResult().success(true).comment(R.string.notsuspended))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.notsuspended))?.run() } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt index 3e503a4dd3..0bdb33c935 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt @@ -32,9 +32,9 @@ class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) { if (!loopPlugin.isSuspended) { loopPlugin.suspendLoop(minutes.getMinutes()) rxBus.send(EventRefreshOverview("ActionLoopSuspend")) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } else { - callback.result(PumpEnactResult().success(true).comment(R.string.alreadysuspended))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadysuspended))?.run() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt index 8a5c5c0aeb..8260f341e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt @@ -34,7 +34,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) { rxBus.send(EventNewNotification(notification)) NSUpload.uploadError(text.value) rxBus.send(EventRefreshOverview("ActionNotification")) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } override fun toJSON(): String { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt index 7bc47c4cba..3e6406fac0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt @@ -34,27 +34,27 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { //Check for uninitialized profileName if (inputProfileName.value == "") { aapsLogger.error(LTag.AUTOMATION, "Selected profile not initialized") - callback.result(PumpEnactResult().success(false).comment(R.string.error_field_must_not_be_empty))?.run() + callback.result(PumpEnactResult(injector).success(false).comment(R.string.error_field_must_not_be_empty))?.run() return } if (profileFunction.getProfile() == null) { aapsLogger.error(LTag.AUTOMATION, "ProfileFunctions not initialized") - callback.result(PumpEnactResult().success(false).comment(R.string.noprofile))?.run() + callback.result(PumpEnactResult(injector).success(false).comment(R.string.noprofile))?.run() return } if (inputProfileName.value == activeProfileName) { aapsLogger.debug(LTag.AUTOMATION, "Profile is already switched") - callback.result(PumpEnactResult().success(true).comment(R.string.alreadyset))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadyset))?.run() return } val profileStore = activePlugin.activeProfileInterface.profile ?: return if (profileStore.getSpecificProfile(inputProfileName.value) == null) { aapsLogger.error(LTag.AUTOMATION, "Selected profile does not exist! - ${inputProfileName.value}") - callback.result(PumpEnactResult().success(false).comment(R.string.notexists))?.run() + callback.result(PumpEnactResult(injector).success(false).comment(R.string.notexists))?.run() return } activePlugin.activeTreatments.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, DateUtil.now()) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt index 561dd167fa..f45e8d19e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt @@ -38,7 +38,7 @@ class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector override fun doAction(callback: Callback) { activePlugin.activeTreatments.doProfileSwitch(duration.value, pct.value.toInt(), 0) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt index ac92e93d98..5db3c14add 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt @@ -26,7 +26,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) { override fun doAction(callback: Callback) { val result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.value) - callback.result(PumpEnactResult().success(result).comment(if (result) R.string.ok else R.string.danar_error))?.run() + callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.danar_error))?.run() } override fun toJSON(): String { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt index 370678fcee..d7f1b6a4e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt @@ -41,7 +41,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { override fun doAction(callback: Callback) { activePlugin.activeTreatments.addToHistoryTempTarget(tt()) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt index 18118110d0..f7e86f6d73 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt @@ -27,6 +27,6 @@ class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) { .source(Source.USER) .low(0.0).high(0.0) activePlugin.activeTreatments.addToHistoryTempTarget(tempTarget) - callback.result(PumpEnactResult().success(true).comment(R.string.ok))?.run() + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 57d8b399a0..e95f14b1da 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -171,7 +171,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr @Override protected void onStart() { super.onStart(); ruffyScripter = new RuffyScripter(MainApp.instance()); - OPERATION_NOT_SUPPORTED = new PumpEnactResult() + OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector()) .success(false).enacted(false).comment(MainApp.gs(R.string.combo_pump_unsupported_operation)); } @@ -263,7 +263,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr log.error("setNewBasalProfile not initialized"); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.pumpNotInitializedProfileNotSet)); + return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(R.string.pumpNotInitializedProfileNotSet)); } BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile); @@ -271,12 +271,12 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr //dismiss previously "FAILED" overview notifications RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { - return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.combo_force_disabled_notification)); + return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(R.string.combo_force_disabled_notification)); } CommandResult setResult = runCommand(MainApp.gs(R.string.combo_activity_setting_basal_profile), 2, @@ -284,7 +284,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr if (!setResult.success) { Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.failedupdatebasalprofile)); + return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(R.string.failedupdatebasalprofile)); } pump.basalProfile = requestedBasalProfile; @@ -295,7 +295,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr //issue success notification Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60); RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); - return new PumpEnactResult().success(true).enacted(true); + return new PumpEnactResult(getInjector()).success(true).enacted(true); } @Override @@ -493,7 +493,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) { // neither carbs nor bolus requested log.error("deliverTreatment: Invalid input"); - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .bolusDelivered(0d).carbsDelivered(0d) .comment(MainApp.gs(R.string.danar_invalidinput)); } else if (detailedBolusInfo.insulin > 0) { @@ -509,7 +509,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr bolusingEvent.setPercent(100); RxBus.Companion.getINSTANCE().send(bolusingEvent); - return new PumpEnactResult().success(true).enacted(true) + return new PumpEnactResult(getInjector()).success(true).enacted(true) .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) .comment(MainApp.gs(R.string.virtualpump_resultok)); } @@ -527,16 +527,16 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr // check pump is ready and all pump bolus records are known CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1)); if (!stateResult.success) { - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); } if (stateResult.reservoirLevel != -1 && stateResult.reservoirLevel - 0.5 < detailedBolusInfo.insulin) { - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.combo_reservoir_level_insufficient_for_bolus)); } // the commands above ensured a connection was made, which updated this field if (pumpHistoryChanged) { - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.combo_bolus_rejected_due_to_pump_history_change)); } @@ -550,7 +550,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr && previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) { if (L.isEnabled(L.PUMP)) log.debug("Bolus request rejected, same bolus was successfully delivered very recently"); - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.bolus_frequency_exceeded)); } @@ -563,10 +563,10 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr while (previousBolus.timestamp == timeCheckResult.state.pumpTime && maxWaitTimeout > System.currentTimeMillis()) { if (cancelBolus) { - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } if (!timeCheckResult.success) { - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); } if (L.isEnabled(L.PUMP)) @@ -582,7 +582,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr } if (cancelBolus) { - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } Treatment treatment = new Treatment(); @@ -603,7 +603,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr // (reads 2 records to update `recentBoluses` further down) CommandResult postBolusStateResult = runCommand(null, 3, () -> ruffyScripter.readQuickInfo(2)); if (!postBolusStateResult.success) { - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.combo_error_bolus_verification_failed)); } Bolus lastPumpBolus = postBolusStateResult.history != null && !postBolusStateResult.history.bolusHistory.isEmpty() @@ -613,9 +613,9 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr // no bolus delivered? if (lastPumpBolus == null || lastPumpBolus.equals(previousBolus)) { if (cancelBolus) { - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } else { - return new PumpEnactResult() + return new PumpEnactResult(getInjector()) .success(false) .enacted(false) .comment(MainApp.gs(R.string.combo_error_no_bolus_delivered)); @@ -624,7 +624,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr // at least some insulin delivered, so add it to treatments if (!addBolusToTreatments(detailedBolusInfo, lastPumpBolus)) - return new PumpEnactResult().success(false).enacted(true) + return new PumpEnactResult(getInjector()).success(false).enacted(true) .comment(MainApp.gs(R.string.combo_error_updating_treatment_record)); // check pump bolus record has a sane timestamp @@ -641,16 +641,16 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr // only a partial bolus was delivered if (Math.abs(lastPumpBolus.amount - detailedBolusInfo.insulin) > 0.01) { if (cancelBolus) { - return new PumpEnactResult().success(true).enacted(true); + return new PumpEnactResult(getInjector()).success(true).enacted(true); } - return new PumpEnactResult().success(false).enacted(true) + return new PumpEnactResult(getInjector()).success(false).enacted(true) .comment(MainApp.gs(R.string.combo_error_partial_bolus_delivered, lastPumpBolus.amount, detailedBolusInfo.insulin)); } // full bolus was delivered successfully incrementBolusCount(); - return new PumpEnactResult() + return new PumpEnactResult(getInjector()) .success(true) .enacted(lastPumpBolus.amount > 0) .bolusDelivered(lastPumpBolus.amount) @@ -748,7 +748,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min"); if (pumpHistoryChanged && percent > 110) { - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.combo_high_temp_rejected_due_to_pump_history_changes)); } @@ -776,7 +776,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr CommandResult commandResult = runCommand(MainApp.gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes), 3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes)); if (!commandResult.success) { - return new PumpEnactResult().success(false).enacted(false); + return new PumpEnactResult(getInjector()).success(false).enacted(false); } PumpState state = commandResult.state; @@ -793,7 +793,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr } incrementTbrCount(); - return new PumpEnactResult().success(true).enacted(true).isPercent(true) + return new PumpEnactResult(getInjector()).success(true).enacted(true).isPercent(true) .percent(state.tbrPercent).duration(state.tbrRemainingDuration); } @@ -818,16 +818,16 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr if (enforceNew) { CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); if (!stateResult.success) { - return new PumpEnactResult().success(false).enacted(false); + return new PumpEnactResult(getInjector()).success(false).enacted(false); } if (!stateResult.state.tbrActive) { - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } if (L.isEnabled(L.PUMP)) log.debug("cancelTempBasal: hard-cancelling TBR since force requested"); CommandResult cancelResult = runCommand(MainApp.gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr); if (!cancelResult.success) { - return new PumpEnactResult().success(false).enacted(false); + return new PumpEnactResult(getInjector()).success(false).enacted(false); } if (!cancelResult.state.tbrActive) { TemporaryBasal tempBasal = new TemporaryBasal() @@ -835,19 +835,19 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr .duration(0) .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); - return new PumpEnactResult().isTempCancel(true).success(true).enacted(true); + return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true); } else { - return new PumpEnactResult().success(false).enacted(false); + return new PumpEnactResult(getInjector()).success(false).enacted(false); } } else if (activeTemp == null) { - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) && activeTemp.getPlannedRemainingMinutes() <= 15) { // Let fake neutral temp keep run (see below) // Note that since this runs on the queue a connection is opened regardless, but this // case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR). if (L.isEnabled(L.PUMP)) log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); - return new PumpEnactResult().success(true).enacted(true) + return new PumpEnactResult(getInjector()).success(true).enacted(true) .comment("cancelTempBasal skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); @@ -1355,7 +1355,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr @NonNull @Override public PumpEnactResult loadTDDs() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = readHistory(new PumpHistoryRequest().tddHistory(PumpHistoryRequest.FULL)); if (result.success) { List tdds = pump.tddHistory; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index ee449b36b7..26f7328b84 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -410,7 +410,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI // neither carbs nor bolus requested if (isLoggingEnabled()) LOG.error("deliverTreatment: Invalid input"); - return new PumpEnactResult().success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d) + return new PumpEnactResult(getInjector()).success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d) .comment(MainApp.gs(R.string.danar_invalidinput)); } else if (detailedBolusInfo.insulin > 0) { // bolus needed, ask pump to deliver it @@ -431,7 +431,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI if (isLoggingEnabled()) LOG.debug("deliverTreatment: Carb only treatment."); - return new PumpEnactResult().success(true).enacted(true).bolusDelivered(0d) + return new PumpEnactResult(getInjector()).success(true).enacted(true).bolusDelivered(0d) .carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok)); } } finally { @@ -452,8 +452,8 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI protected abstract void triggerUIChange(); - public static PumpEnactResult getOperationNotSupportedWithCustomText(int resourceId) { - return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(resourceId)); + public PumpEnactResult getOperationNotSupportedWithCustomText(int resourceId) { + return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(MainApp.gs(resourceId)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index ac6d0f19c3..93b800bdb9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -95,7 +95,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump // Pump interface @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); if (sExecutionService == null) { log.error("setNewBasalProfile sExecutionService is null"); @@ -180,7 +180,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; @@ -235,7 +235,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); ExtendedBolus runningEB = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { result.enacted = false; @@ -273,7 +273,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public PumpEnactResult cancelExtendedBolus() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); ExtendedBolus runningEB = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); if (runningEB != null) { sExecutionService.extendedBolusStop(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index 8919d993b3..168c985495 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -167,7 +167,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; @@ -181,7 +181,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false); return result; } else { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.bolusDelivered = 0d; result.carbsDelivered = 0d; @@ -199,7 +199,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { //if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) { // connect("setTempBasalAbsolute old data"); //} - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); @@ -336,7 +336,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress() && useExtendedBoluses) { return cancelExtendedBolus(); } - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = true; result.enacted = false; result.comment = resourceHelper.gs(R.string.virtualpump_resultok); @@ -350,7 +350,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { } private PumpEnactResult cancelRealTempBasal() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); if (runningTB != null) { sExecutionService.tempBasalStop(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java index e16ee6b856..f8383bc2f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java @@ -17,13 +17,18 @@ import java.io.IOException; import java.util.Set; import java.util.UUID; +import javax.inject.Inject; + import dagger.android.DaggerService; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventPumpStatusChanged; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase; @@ -51,7 +56,8 @@ import info.nightscout.androidaps.utils.ToastUtils; */ public abstract class AbstractDanaRExecutionService extends DaggerService { - protected Logger log = StacktraceLoggerWrapper.getLogger(L.PUMP); + @Inject HasAndroidInjector injector; + @Inject AAPSLogger aapsLogger; protected String mDevName; @@ -102,8 +108,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String action = intent.getAction(); if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { - if (L.isEnabled(L.PUMP)) - log.debug("Device was disconnected " + device.getName());//Device was disconnected + aapsLogger.debug(LTag.PUMP, "Device was disconnected " + device.getName());//Device was disconnected if (mBTDevice != null && mBTDevice.getName() != null && mBTDevice.getName().equals(device.getName())) { if (mSerialIOThread != null) { mSerialIOThread.disconnect("BT disconnection broadcast"); @@ -164,7 +169,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { try { mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID); } catch (IOException e) { - log.error("Error creating socket: ", e); + aapsLogger.error("Error creating socket: ", e); } break; } @@ -178,8 +183,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { } public void bolusStop() { - if (L.isEnabled(L.PUMP)) - log.debug("bolusStop >>>>> @ " + (mBolusingTreatment == null ? "" : mBolusingTreatment.insulin)); + aapsLogger.debug(LTag.PUMP, "bolusStop >>>>> @ " + (mBolusingTreatment == null ? "" : mBolusingTreatment.insulin)); MsgBolusStop stop = new MsgBolusStop(); stop.forced = true; if (isConnected()) { @@ -194,7 +198,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { } public PumpEnactResult loadHistory(byte type) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(injector); if (!isConnected()) return result; MessageBase msg = null; switch (type) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index cdaab36c50..c7ede2b2ba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -24,7 +24,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; @@ -115,8 +115,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); + aapsLogger.debug(LTag.PUMP, "EventAppExit received"); if (mSerialIOThread != null) mSerialIOThread.disconnect("Application exit"); context.unregisterReceiver(receiver); @@ -155,7 +154,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } catch (IOException e) { //log.error("Unhandled exception", e); if (e.getMessage().contains("socket closed")) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -233,14 +232,12 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { return; } long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 10) { mSerialIOThread.sendMessage(new MsgSetTime(new Date())); mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); } danaRPump.setLastSettingsRead(now); } @@ -249,8 +246,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { rxBus.send(new EventInitializationChanged()); //NSUpload.uploadDeviceStatus(); if (danaRPump.getDailyTotalUnits() > danaRPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { - if (L.isEnabled(L.PUMP)) - log.debug("Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); + aapsLogger.debug(LTag.PUMP, "Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); rxBus.send(new EventNewNotification(reportFail)); @@ -259,7 +255,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } } } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -341,8 +337,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm stop.stopped = true; stop.forced = true; - if (L.isEnabled(L.PUMP)) - log.debug("Communication stopped"); + aapsLogger.debug(LTag.PUMP, "Communication stopped"); } } SystemClock.sleep(300); @@ -385,11 +380,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public void run() { if (danaRPump.getLastBolusTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old t.insulin = danaRPump.getLastBolusAmount(); - if (L.isEnabled(L.PUMP)) - log.debug("Used bolus amount from history: " + danaRPump.getLastBolusAmount()); + aapsLogger.debug(LTag.PUMP, "Used bolus amount from history: " + danaRPump.getLastBolusAmount()); } else { - if (L.isEnabled(L.PUMP)) - log.debug("Bolus amount in history too old: " + DateUtil.dateAndTimeString(danaRPump.getLastBolusTime())); + aapsLogger.debug(LTag.PUMP, "Bolus amount in history too old: " + DateUtil.dateAndTimeString(danaRPump.getLastBolusTime())); } synchronized (o) { o.notify(); @@ -399,7 +392,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { try { o.wait(); } catch (InterruptedException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } } else { @@ -442,11 +435,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public PumpEnactResult setUserOptions() { if (!isConnected()) - return new PumpEnactResult().success(false); + return new PumpEnactResult(injector).success(false); SystemClock.sleep(300); MsgSetUserOptions msg = new MsgSetUserOptions(aapsLogger, danaRPump); mSerialIOThread.sendMessage(msg); SystemClock.sleep(200); - return new PumpEnactResult().success(!msg.failed); + return new PumpEnactResult(injector).success(!msg.failed); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java index 9f80b1fc30..f89a5c532a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java @@ -170,7 +170,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; @@ -184,7 +184,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false); return result; } else { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.bolusDelivered = 0d; result.carbsDelivered = 0d; @@ -202,7 +202,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { //if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) { // connect("setTempBasalAbsolute old data"); //} - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); @@ -339,7 +339,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress() && useExtendedBoluses) { return cancelExtendedBolus(); } - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = true; result.enacted = false; result.comment = resourceHelper.gs(R.string.virtualpump_resultok); @@ -353,7 +353,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { } private PumpEnactResult cancelRealTempBasal() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); if (runningTB != null) { sExecutionService.tempBasalStop(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index 6a59b320cf..b036e45ea0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -24,7 +24,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; @@ -106,8 +106,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); + aapsLogger.debug(LTag.PUMP, "EventAppExit received"); if (mSerialIOThread != null) mSerialIOThread.disconnect("Application exit"); @@ -147,7 +146,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { } catch (IOException e) { //log.error("Unhandled exception", e); if (e.getMessage().contains("socket closed")) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -221,16 +220,14 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { return; } long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 10) { waitForWholeMinute(); // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cutted off anyway) mSerialIOThread.sendMessage(new MsgSetTime(new Date(DateUtil.now() + T.secs(10).msecs()))); mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); } danaRPump.setLastSettingsRead(now); } @@ -239,8 +236,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { rxBus.send(new EventInitializationChanged()); //NSUpload.uploadDeviceStatus(); if (danaRPump.getDailyTotalUnits() > danaRPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { - if (L.isEnabled(L.PUMP)) - log.debug("Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); + aapsLogger.debug(LTag.PUMP, "Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); rxBus.send(new EventNewNotification(reportFail)); @@ -249,7 +245,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { } } } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -325,8 +321,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm stop.stopped = true; stop.forced = true; - if (L.isEnabled(L.PUMP)) - log.debug("Communication stopped"); + aapsLogger.debug(LTag.PUMP, "Communication stopped"); } } SystemClock.sleep(300); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 9c4509c092..8c94de596f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -306,7 +306,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); if (danaRSService == null) { getAapsLogger().error("setNewBasalProfile sExecutionService is null"); @@ -413,7 +413,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; @@ -440,7 +440,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR getAapsLogger().debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); return result; } else { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.bolusDelivered = 0d; result.carbsDelivered = 0d; @@ -469,7 +469,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR // connect("setTempBasalAbsolute old data"); //} - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); @@ -541,7 +541,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @NonNull @Override public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; @@ -593,7 +593,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR private synchronized PumpEnactResult setHighTempBasalPercent(Integer percent) { DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); boolean connectionOK = danaRSService.highTempBasal(percent); if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { result.enacted = true; @@ -620,7 +620,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { result.enacted = false; @@ -655,7 +655,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @NonNull @Override public synchronized PumpEnactResult cancelTempBasal(boolean force) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); if (runningTB != null) { danaRSService.tempBasalStop(); @@ -679,7 +679,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR @NonNull @Override public synchronized PumpEnactResult cancelExtendedBolus() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); if (runningEB != null) { danaRSService.extendedBolusStop(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index ebc1da2efa..efcbd5aa52 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -8,6 +8,7 @@ import android.os.SystemClock; import javax.inject.Inject; import dagger.android.DaggerService; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -86,6 +87,7 @@ import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class DanaRSService extends DaggerService { + @Inject HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @Inject RxBusWrapper rxBus; @Inject SP sp; @@ -260,7 +262,7 @@ public class DanaRSService extends DaggerService { public PumpEnactResult loadEvents() { if (!danaRSPlugin.isInitialized()) { - PumpEnactResult result = new PumpEnactResult().success(false); + PumpEnactResult result = new PumpEnactResult(injector).success(false); result.comment = "pump not initialized"; return result; } @@ -285,13 +287,13 @@ public class DanaRSService extends DaggerService { lastHistoryFetched = 0; aapsLogger.debug(LTag.PUMPCOMM, "Events loaded"); danaRPump.setLastConnection(System.currentTimeMillis()); - return new PumpEnactResult().success(true); + return new PumpEnactResult(injector).success(true); } public PumpEnactResult setUserSettings() { bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)); - return new PumpEnactResult().success(true); + return new PumpEnactResult(injector).success(true); } @@ -485,7 +487,7 @@ public class DanaRSService extends DaggerService { } public PumpEnactResult loadHistory(byte type) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(injector); if (!isConnected()) return result; DanaRS_Packet_History_ msg = null; switch (type) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index 50db0d1f8c..0e800b06a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -29,7 +29,6 @@ import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInf import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2ExecutionService; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -185,7 +184,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; @@ -197,7 +196,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { // remove carbs because it's get from history separately return result; } else { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.bolusDelivered = 0d; result.carbsDelivered = 0d; @@ -225,7 +224,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { // connect("setTempBasalAbsolute old data"); //} - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); @@ -296,7 +295,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; @@ -348,7 +347,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { private PumpEnactResult setHighTempBasalPercent(Integer percent) { DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); boolean connectionOK = sExecutionService.highTempBasal(percent); if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { result.enacted = true; @@ -370,7 +369,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { @NonNull @Override public PumpEnactResult cancelTempBasal(boolean force) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); if (runningTB != null) { sExecutionService.tempBasalStop(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 1c4fcd6096..5a3d83c444 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -12,6 +12,7 @@ import java.util.Date; import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.ErrorHelperActivity; @@ -26,7 +27,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; @@ -87,6 +88,7 @@ import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { + @Inject HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; @@ -130,8 +132,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); + aapsLogger.debug(LTag.PUMP, "EventAppExit received"); if (mSerialIOThread != null) mSerialIOThread.disconnect("Application exit"); @@ -165,7 +166,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } catch (IOException e) { //log.error("Unhandled exception", e); if (e.getMessage().contains("socket closed")) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -230,12 +231,10 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { return; } long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 3) { if (Math.abs(timeDiff) > 60 * 60 * 1.5) { - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds - large difference"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds - large difference"); //If time-diff is very large, warn user until we can synchronize history readings properly Intent i = new Intent(context, ErrorHelperActivity.class); i.putExtra("soundid", R.raw.error); @@ -255,8 +254,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSetTime(new Date(DateUtil.now() + T.secs(10).msecs()))); mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (L.isEnabled(L.PUMP)) - log.debug("Pump time difference: " + timeDiff + " seconds"); + aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); } } @@ -283,8 +281,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { rxBus.send(new EventInitializationChanged()); //NSUpload.uploadDeviceStatus(); if (danaRPump.getDailyTotalUnits() > danaRPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { - if (L.isEnabled(L.PUMP)) - log.debug("Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); + aapsLogger.debug(LTag.PUMP, "Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); rxBus.send(new EventNewNotification(reportFail)); @@ -293,7 +290,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } } } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -329,7 +326,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean tempBasalShortDuration(int percent, int durationInMinutes) { if (durationInMinutes != 15 && durationInMinutes != 30) { - log.error("Wrong duration param"); + aapsLogger.error("Wrong duration param"); return false; } @@ -414,7 +411,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm stop.stopped = true; stop.forced = true; - log.error("Communication stopped"); + aapsLogger.error("Communication stopped"); } } } @@ -459,8 +456,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } public void bolusStop() { - if (L.isEnabled(L.PUMP)) - log.debug("bolusStop >>>>> @ " + (mBolusingTreatment == null ? "" : mBolusingTreatment.insulin)); + aapsLogger.debug(LTag.PUMP, "bolusStop >>>>> @ " + (mBolusingTreatment == null ? "" : mBolusingTreatment.insulin)); MsgBolusStop stop = new MsgBolusStop(); stop.forced = true; if (isConnected()) { @@ -486,18 +482,17 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public PumpEnactResult loadEvents() { if (!danaRv2Plugin.isInitialized()) { - PumpEnactResult result = new PumpEnactResult().success(false); + PumpEnactResult result = new PumpEnactResult(injector).success(false); result.comment = "pump not initialized"; return result; } if (!isConnected()) - return new PumpEnactResult().success(false); + return new PumpEnactResult(injector).success(false); SystemClock.sleep(300); MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(lastHistoryFetched); - if (L.isEnabled(L.PUMP)) - log.debug("Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched)); + aapsLogger.debug(LTag.PUMP, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched)); mSerialIOThread.sendMessage(msg); while (!msg.done && mRfcommSocket.isConnected()) { @@ -509,7 +504,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { else lastHistoryFetched = 0; danaRPump.setLastConnection(System.currentTimeMillis()); - return new PumpEnactResult().success(true); + return new PumpEnactResult(injector).success(true); } public boolean updateBasalsInPump(final Profile profile) { @@ -528,12 +523,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public PumpEnactResult setUserOptions() { if (!isConnected()) - return new PumpEnactResult().success(false); + return new PumpEnactResult(injector).success(false); SystemClock.sleep(300); MsgSetUserOptions msg = new MsgSetUserOptions(aapsLogger, danaRPump); mSerialIOThread.sendMessage(msg); SystemClock.sleep(200); - return new PumpEnactResult().success(!msg.failed); + return new PumpEnactResult(injector).success(!msg.failed); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index fd4bba0fd1..0d4ab7dd3f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -217,7 +217,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, injector, aapsLogger, resourceHelper, commandQueue ); - this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.resourceHelper = resourceHelper; @@ -468,7 +467,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); List profileBlocks = new ArrayList<>(); for (int i = 0; i < profile.getBasalValues().length; i++) { @@ -565,7 +564,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); double insulin = Math.round(detailedBolusInfo.insulin / 0.01) * 0.01; if (insulin > 0) { try { @@ -677,7 +676,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); if (activeBasalRate == null) return result; if (activeBasalRate.getActiveBasalRate() == 0) return result; double percent = 100D / activeBasalRate.getActiveBasalRate() * absoluteRate; @@ -726,7 +725,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); percent = (int) Math.round(((double) percent) / 10d) * 10; if (percent == 100) return cancelTempBasal(true); else if (percent > 250) percent = 250; @@ -781,7 +780,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } public PumpEnactResult setExtendedBolusOnly(Double insulin, Integer durationInMinutes) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); try { DeliverBolusMessage bolusMessage = new DeliverBolusMessage(); bolusMessage.setBolusType(BolusType.EXTENDED); @@ -819,7 +818,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); PumpEnactResult cancelEBResult = null; if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly(); PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); @@ -840,7 +839,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } private PumpEnactResult cancelTempBasalOnly() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); try { alertService.ignore(AlertType.WARNING_36); connectionService.requestMessage(new CancelTBRMessage()).await(); @@ -883,7 +882,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } private PumpEnactResult cancelExtendedBolusOnly() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); try { for (ActiveBolus activeBolus : activeBoluses) { if (activeBolus.getBolusType() == BolusType.EXTENDED || activeBolus.getBolusType() == BolusType.MULTIWAVE) { @@ -1015,7 +1014,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } public PumpEnactResult stopPump() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); try { SetOperatingModeMessage operatingModeMessage = new SetOperatingModeMessage(); operatingModeMessage.setOperatingMode(OperatingMode.STOPPED); @@ -1038,7 +1037,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } public PumpEnactResult startPump() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); try { SetOperatingModeMessage operatingModeMessage = new SetOperatingModeMessage(); operatingModeMessage.setOperatingMode(OperatingMode.STARTED); @@ -1061,7 +1060,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } public PumpEnactResult setTBROverNotification(boolean enabled) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); boolean valueBefore = tbrOverNotificationBlock.isEnabled(); tbrOverNotificationBlock.setEnabled(enabled); try { @@ -1125,7 +1124,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult loadTDDs() { - return new PumpEnactResult().success(true); + return new PumpEnactResult(getInjector()).success(true); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java index 95b83e4e71..c259905a1d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java @@ -78,7 +78,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult loadTDDs() { //no result, could read DB in the future? - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); return result; } @@ -135,7 +135,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult setNewBasalProfile(Profile profile) { // Do nothing here. we are using ConfigBuilderPlugin.getPlugin().getActiveProfile().getProfile(); - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = true; return result; } @@ -167,7 +167,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = true; result.bolusDelivered = detailedBolusInfo.insulin; result.carbsDelivered = detailedBolusInfo.carbs; @@ -182,7 +182,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.comment = MainApp.gs(R.string.pumperror); if (L.isEnabled(L.PUMPCOMM)) @@ -192,7 +192,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.comment = MainApp.gs(R.string.pumperror); if (L.isEnabled(L.PUMPCOMM)) @@ -202,7 +202,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.comment = MainApp.gs(R.string.pumperror); if (L.isEnabled(L.PUMPCOMM)) @@ -212,7 +212,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult cancelTempBasal(boolean force) { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.comment = MainApp.gs(R.string.pumperror); if (L.isEnabled(L.PUMPCOMM)) @@ -222,7 +222,7 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { @NonNull @Override public PumpEnactResult cancelExtendedBolus() { - PumpEnactResult result = new PumpEnactResult(); + PumpEnactResult result = new PumpEnactResult(getInjector()); result.success = false; result.comment = MainApp.gs(R.string.pumperror); if (L.isEnabled(L.PUMPCOMM)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index 155813defe..5cebe46e5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -828,7 +828,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter MedtronicPumpStatus mdtPumpStatus = getMDTPumpStatus(); if (detailedBolusInfo.insulin > mdtPumpStatus.reservoirRemainingUnits) { - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin, @@ -921,13 +921,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.busyTimestamps.add(time); setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true); - return new PumpEnactResult().success(true) // + return new PumpEnactResult(getInjector()).success(true) // .enacted(true) // .bolusDelivered(detailedBolusInfo.insulin) // .carbsDelivered(detailedBolusInfo.carbs); } else { - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered)); @@ -948,11 +948,11 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } if (success) { - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(true) // .enacted(false); } else { - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable)); @@ -988,7 +988,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter setRefreshButtonEnabled(true); - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable)); @@ -1008,7 +1008,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (isLoggingEnabled()) LOG.warn(getLogPrefix() + "setTempBasalAbsolute - Could not read current TBR, canceling operation."); finishAction("TBR"); - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr)); } else { if (isLoggingEnabled()) @@ -1030,7 +1030,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (isLoggingEnabled()) LOG.info(getLogPrefix() + "setTempBasalAbsolute - No enforceNew and same rate. Exiting."); finishAction("TBR"); - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } } // if not the same rate, we cancel and start new @@ -1056,7 +1056,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter finishAction("TBR"); - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr_stop_op)); } } @@ -1088,13 +1088,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter finishAction("TBR"); - return new PumpEnactResult().success(true).enacted(true) // + return new PumpEnactResult(getInjector()).success(true).enacted(true) // .absolute(absoluteRate).duration(durationInMinutes); } else { finishAction("TBR"); - return new PumpEnactResult().success(false).enacted(false) // + return new PumpEnactResult(getInjector()).success(false).enacted(false) // .comment(MainApp.gs(R.string.medtronic_cmd_tbr_could_not_be_delivered)); } @@ -1396,7 +1396,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter setRefreshButtonEnabled(true); - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable)); @@ -1412,13 +1412,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (isLoggingEnabled()) LOG.info(getLogPrefix() + "cancelTempBasal - TBR already canceled."); finishAction("TBR"); - return new PumpEnactResult().success(true).enacted(false); + return new PumpEnactResult(getInjector()).success(true).enacted(false); } } else { if (isLoggingEnabled()) LOG.warn(getLogPrefix() + "cancelTempBasal - Could not read currect TBR, canceling operation."); finishAction("TBR"); - return new PumpEnactResult().success(false).enacted(false) + return new PumpEnactResult(getInjector()).success(false).enacted(false) .comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr)); } @@ -1439,13 +1439,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); - return new PumpEnactResult().success(true).enacted(true) // + return new PumpEnactResult(getInjector()).success(true).enacted(true) // .isTempCancel(true); } else { if (isLoggingEnabled()) LOG.info(getLogPrefix() + "cancelTempBasal - Cancel TBR failed."); - return new PumpEnactResult().success(response).enacted(response) // + return new PumpEnactResult(getInjector()).success(response).enacted(response) // .comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr)); } } @@ -1472,7 +1472,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter // this shouldn't be needed, but let's do check if profile setting we are setting is same as current one if (isProfileSame(profile)) { - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(true) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_not_set_is_same)); @@ -1484,7 +1484,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter setRefreshButtonEnabled(true); - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable)); @@ -1497,7 +1497,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter String profileInvalid = isProfileValid(basalProfile); if (profileInvalid != null) { - return new PumpEnactResult() // + return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(MainApp.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid)); @@ -1512,9 +1512,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter LOG.info(getLogPrefix() + "Basal Profile was set: " + response); if (response) { - return new PumpEnactResult().success(true).enacted(true); + return new PumpEnactResult(getInjector()).success(true).enacted(true); } else { - return new PumpEnactResult().success(response).enacted(response) // + return new PumpEnactResult(getInjector()).success(response).enacted(response) // .comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_could_not_be_set)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 3590a97ffa..4026039f4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -132,7 +132,7 @@ class VirtualPumpPlugin @Inject constructor( } override fun loadTDDs(): PumpEnactResult { //no result, could read DB in the future? - return PumpEnactResult() + return PumpEnactResult(injector) } override fun getCustomActions(): List? { @@ -179,7 +179,7 @@ class VirtualPumpPlugin @Inject constructor( override fun setNewBasalProfile(profile: Profile): PumpEnactResult { lastDataTime = System.currentTimeMillis() // Do nothing here. we are using ConfigBuilderPlugin.getPlugin().getActiveProfile().getProfile(); - val result = PumpEnactResult() + val result = PumpEnactResult(injector) result.success = true val notification = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) @@ -207,7 +207,7 @@ class VirtualPumpPlugin @Inject constructor( } override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { - val result = PumpEnactResult() + val result = PumpEnactResult(injector) result.success = true result.bolusDelivered = detailedBolusInfo.insulin result.carbsDelivered = detailedBolusInfo.carbs @@ -242,7 +242,7 @@ class VirtualPumpPlugin @Inject constructor( .absolute(absoluteRate) .duration(durationInMinutes) .source(Source.USER) - val result = PumpEnactResult() + val result = PumpEnactResult(injector) result.success = true result.enacted = true result.isTempCancel = false @@ -262,7 +262,7 @@ class VirtualPumpPlugin @Inject constructor( .percent(percent) .duration(durationInMinutes) .source(Source.USER) - val result = PumpEnactResult() + val result = PumpEnactResult(injector) result.success = true result.enacted = true result.percent = percent @@ -299,7 +299,7 @@ class VirtualPumpPlugin @Inject constructor( } override fun cancelTempBasal(force: Boolean): PumpEnactResult { - val result = PumpEnactResult() + val result = PumpEnactResult(injector) result.success = true result.isTempCancel = true result.comment = resourceHelper.gs(R.string.virtualpump_resultok) @@ -316,7 +316,7 @@ class VirtualPumpPlugin @Inject constructor( } override fun cancelExtendedBolus(): PumpEnactResult { - val result = PumpEnactResult() + val result = PumpEnactResult(injector) if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress) { val exStop = ExtendedBolus(System.currentTimeMillis()) exStop.source = Source.USER diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index 1192d6ddcc..79fffe95b0 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -96,7 +96,7 @@ class CommandQueue @Inject constructor( var performing: Command? = null private fun executingNowError(): PumpEnactResult = - PumpEnactResult().success(false).enacted(false).comment(resourceHelper.gs(R.string.executingrightnow)) + PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.executingrightnow)) override fun isRunning(type: CommandType): Boolean = performing?.commandType == type @@ -251,7 +251,7 @@ class CommandQueue @Inject constructor( @Synchronized override fun cancelAllBoluses() { if (!isRunning(CommandType.BOLUS)) { - rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult().success(true).enacted(false))) + rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult(injector).success(true).enacted(false))) } removeAll(CommandType.BOLUS) removeAll(CommandType.SMB_BOLUS) @@ -335,13 +335,13 @@ class CommandQueue @Inject constructor( override fun setProfile(profile: Profile, callback: Callback?): Boolean { if (isThisProfileSet(profile)) { aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set") - callback?.result(PumpEnactResult().success(true).enacted(false))?.run() + callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() return false } if (!MainApp.isEngineeringModeOrRelease()) { val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT) rxBus.send(EventNewNotification(notification)) - callback?.result(PumpEnactResult().success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run() + callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run() return false } // Compare with pump limits @@ -350,7 +350,7 @@ class CommandQueue @Inject constructor( if (basalValue.value < activePlugin.get().activePump.pumpDescription.basalMinimumRate) { val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, resourceHelper.gs(R.string.basalvaluebelowminimum), Notification.URGENT) rxBus.send(EventNewNotification(notification)) - callback?.result(PumpEnactResult().success(false).enacted(false).comment(resourceHelper.gs(R.string.basalvaluebelowminimum)))?.run() + callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.basalvaluebelowminimum)))?.run() return false } } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt index b0d5558f67..eac1e6d103 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject abstract class Command( - injector: HasAndroidInjector, + val injector: HasAndroidInjector, val commandType: CommandType, val callback: Callback? = null ) { @@ -42,7 +42,7 @@ abstract class Command( abstract fun status(): String fun cancel() { - val result = PumpEnactResult() + val result = PumpEnactResult(injector) result.success = false result.comment = resourceHelper.gs(R.string.connectiontimedout) aapsLogger.debug(LTag.PUMPQUEUE, "Result cancel") diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt index f4b9dd59cf..6c2e4ca83f 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt @@ -23,7 +23,7 @@ class CommandReadStatus( localAlertUtils.notifyPumpStatusRead() aapsLogger.debug(LTag.PUMPQUEUE, "CommandReadStatus executed. Reason: $reason") val pump = activePlugin.activePump - val result = PumpEnactResult().success(false) + val result = PumpEnactResult(injector).success(false) val lastConnection = pump.lastDataTime() if (lastConnection > System.currentTimeMillis() - T.mins(1).msecs()) result.success(true) callback?.result(result)?.run() diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt index 098244cc61..a52a23bd09 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -24,11 +24,11 @@ class CommandSMBBolus( val lastBolusTime = activePlugin.activeTreatments.lastBolusTime if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > DateUtil.now()) { aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval") - r = PumpEnactResult().enacted(false).success(false).comment("SMB requested but still in 3 min interval") + r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval") } else if (detailedBolusInfo.deliverAt != 0L && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) { r = activePlugin.activePump.deliverTreatment(detailedBolusInfo) } else { - r = PumpEnactResult().enacted(false).success(false).comment("SMB request too old") + r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB request too old") aapsLogger.debug(LTag.PUMPQUEUE, "SMB bolus canceled. deliverAt: " + DateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)) } aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt index 75f8d60369..89521346fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt @@ -26,7 +26,7 @@ class CommandSetProfile constructor( override fun execute() { if (commandQueue.isThisProfileSet(profile)) { aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set. profile: $profile") - callback?.result(PumpEnactResult().success(true).enacted(false))?.run() + callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() return } val r = activePlugin.activePump.setNewBasalProfile(profile) diff --git a/app/src/test/java/info/TestBase.kt b/app/src/test/java/info/TestBase.kt index 235e470e65..182da68d13 100644 --- a/app/src/test/java/info/TestBase.kt +++ b/app/src/test/java/info/TestBase.kt @@ -1,11 +1,17 @@ package info +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.data.Profile +import org.json.JSONObject import org.junit.Rule import org.mockito.Mockito import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoRule open class TestBase { + val validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + val validProfile: Profile = Profile(JSONObject(validProfileJSON), Constants.MGDL) + // Add a JUnit rule that will setup the @Mock annotated vars and log. // Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method. @get:Rule diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt index a96800345b..df36aefb80 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt @@ -1,24 +1,18 @@ package info.nightscout.androidaps.plugins.general.automation.actions -import android.content.Context -import com.google.common.base.Optional -import dagger.Lazy import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.TestBase import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PumpDescription +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction -import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -26,6 +20,7 @@ import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.eq import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` @@ -36,6 +31,7 @@ import org.powermock.modules.junit4.PowerMockRunner @PrepareForTest(VirtualPumpPlugin::class, RxBusWrapper::class) class ActionLoopDisableTest : TestBase() { + @Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var rxBus: RxBusWrapper @Mock lateinit var sp: SP @Mock lateinit var resourceHelper: ResourceHelper @@ -46,6 +42,22 @@ class ActionLoopDisableTest : TestBase() { lateinit var sut: ActionLoopDisable + private var injector: HasAndroidInjector = HasAndroidInjector { + AndroidInjector { + if (it is ActionLoopDisable) { + it.loopPlugin = loopPlugin + it.resourceHelper = resourceHelper + it.configBuilderPlugin = configBuilderPlugin + it.commandQueue = commandQueue + it.rxBus = rxBus + } + if (it is PumpEnactResult) { + it.aapsLogger = aapsLogger + it.resourceHelper = resourceHelper + } + } + } + @Before fun setup() { @@ -56,14 +68,7 @@ class ActionLoopDisableTest : TestBase() { `when`(resourceHelper.gs(R.string.disableloop)).thenReturn("Disable loop") `when`(resourceHelper.gs(R.string.alreadydisabled)).thenReturn("Disable loop") - sut = ActionLoopDisable(HasAndroidInjector { AndroidInjector { Unit } }) // do nothing injector - .also { // inject the mocks - it.loopPlugin = loopPlugin - it.resourceHelper = resourceHelper - it.configBuilderPlugin = configBuilderPlugin - it.commandQueue = commandQueue - it.rxBus = rxBus - } + sut = ActionLoopDisable(injector) // do nothing injector } @Test @@ -83,15 +88,22 @@ class ActionLoopDisableTest : TestBase() { @Test fun doActionTest() { + `when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) sut.doAction(object : Callback() { override fun run() {} }) - Mockito.verify(loopPlugin, Mockito.times(1)).setPluginEnabled(PluginType.LOOP, true) + Mockito.verify(loopPlugin, Mockito.times(1)).setPluginEnabled(PluginType.LOOP, false) + Mockito.verify(configBuilderPlugin, Mockito.times(1)).storeSettings("ActionLoopDisable") + Mockito.verify(commandQueue, Mockito.times(1)).cancelTempBasal(eq(true), anyObject()) - // another call should keep it disabled + `when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false) + + // another call should keep it disabled, no new invocation sut.doAction(object : Callback() { override fun run() {} }) - Mockito.verify(loopPlugin, Mockito.times(2)).setPluginEnabled(PluginType.LOOP, true) + Mockito.verify(loopPlugin, Mockito.times(1)).setPluginEnabled(PluginType.LOOP, false) + Mockito.verify(configBuilderPlugin, Mockito.times(1)).storeSettings("ActionLoopDisable") + Mockito.verify(commandQueue, Mockito.times(1)).cancelTempBasal(eq(true), anyObject()) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt index 5c764bb6f4..3974fb86d8 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt @@ -1,6 +1,8 @@ package info.nightscout.androidaps.plugins.pump.danaRS import android.content.Context +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector import info.AAPSMocker import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp @@ -74,6 +76,6 @@ class DanaRSPluginTest : DanaRSTestBase() { Mockito.`when`(resourceHelper.gs(eq(R.string.limitingpercentrate), anyObject(), anyObject())).thenReturn("limitingpercentrate") rxBus = RxBusWrapper() - danaRSPlugin = DanaRSPlugin(aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump) + danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt index 0dcc525ef4..207691d5e8 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt @@ -1,6 +1,8 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm import android.content.Context +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.bus.RxBusWrapper @@ -47,7 +49,7 @@ class DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest : DanaRSTestBase() { @Before fun mock() { - danaRSPlugin = DanaRSPlugin(aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump) + danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt index dc2757724c..508caefb80 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt index c09a81a368..4ab7e2c73a 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt @@ -67,7 +67,7 @@ class DanaRS_Packet_Notify_Delivery_Rate_DisplayTest : DanaRSTestBase() { @Before fun mock() { - danaRSPlugin = DanaRSPlugin(aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump) + danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump) danaRSPlugin.bolusingTreatment = Treatment(treatmentInjector) } } \ No newline at end of file From 5cab10f51f5c9883d08ccdb96d17bdccbbc1e61f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 9 Mar 2020 00:29:46 +0100 Subject: [PATCH 045/100] More tests --- .../plugins/aps/loop/APSResultTest.kt | 209 ++++++++++++++++++ .../AbstractSensitivityPluginTest.kt | 4 +- 2 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt new file mode 100644 index 0000000000..c4c06d6449 --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt @@ -0,0 +1,209 @@ +package info.nightscout.androidaps.plugins.aps.loop + +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector +import info.TestBase +import info.nightscout.androidaps.db.TemporaryBasal +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.PumpDescription +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito.`when` +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner + +@RunWith(PowerMockRunner::class) +@PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class) +class APSResultTest : TestBase() { + + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var constraintChecker: ConstraintChecker + @Mock lateinit var sp: SP + @Mock lateinit var activePluginProvider: ActivePluginProvider + @Mock lateinit var treatmentsPlugin: TreatmentsPlugin + @Mock lateinit var profileFunction: ProfileFunction + @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin + private var closedLoopEnabled = Constraint(false) + private val pumpDescription = PumpDescription() + + @Test + fun changeRequestedTest() { + + val apsResult = APSResult(HasAndroidInjector { AndroidInjector { Unit } }) + .also { + it.aapsLogger = aapsLogger + it.constraintChecker = constraintChecker + it.sp = sp + it.activePluginProvider = activePluginProvider + it.treatmentsPlugin = treatmentsPlugin + it.profileFunction = profileFunction + it.resourceHelper = resourceHelper + } + + // BASAL RATE IN TEST PROFILE IS 1U/h + + // **** PERCENT pump **** + pumpDescription.setPumpDescription(PumpType.Cellnovo1) // % based + apsResult.usePercent(true) + + // closed loop mode return original request + closedLoopEnabled.set(aapsLogger, true) + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) + apsResult.tempBasalRequested(false) + Assert.assertEquals(false, apsResult.isChangeRequested) + apsResult.tempBasalRequested(true).percent(200).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // open loop + closedLoopEnabled.set(aapsLogger, false) + // no change requested + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) + apsResult.tempBasalRequested(false) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request 100% when no temp is running + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) + apsResult.tempBasalRequested(true).percent(100).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request equal temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30)) + apsResult.tempBasalRequested(true).percent(70).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request zero temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(10).duration(30)) + apsResult.tempBasalRequested(true).percent(0).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // request high temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(190).duration(30)) + apsResult.tempBasalRequested(true).percent(200).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // request slightly different temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30)) + apsResult.tempBasalRequested(true).percent(80).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request different temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30)) + apsResult.tempBasalRequested(true).percent(120).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // it should work with absolute temps too + // request different temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.0).duration(30)) + apsResult.tempBasalRequested(true).percent(100).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(2.0).duration(30)) + apsResult.tempBasalRequested(true).percent(50).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // **** ABSOLUTE pump **** + virtualPumpPlugin.pumpDescription.setPumpDescription(PumpType.Medtronic_515_715) // U/h based + apsResult.usePercent(false) + + // open loop + closedLoopEnabled.set(aapsLogger, false) + // request 100% when no temp is running + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(null) + apsResult.tempBasalRequested(true).rate(1.0).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request equal temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(2.0).duration(30)) + apsResult.tempBasalRequested(true).rate(2.0).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(200).duration(30)) + apsResult.tempBasalRequested(true).rate(2.0).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request zero temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(0.1).duration(30)) + apsResult.tempBasalRequested(true).rate(0.0).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // request high temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(34.9).duration(30)) + apsResult.tempBasalRequested(true).rate(35.0).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // request slightly different temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.1).duration(30)) + apsResult.tempBasalRequested(true).rate(1.2).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + + // request different temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.1).duration(30)) + apsResult.tempBasalRequested(true).rate(1.5).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + + // it should work with percent temps too + // request different temp + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(110).duration(30)) + apsResult.tempBasalRequested(true).rate(1.1).duration(30) + Assert.assertEquals(false, apsResult.isChangeRequested) + `when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(200).duration(30)) + apsResult.tempBasalRequested(true).rate(0.5).duration(30) + Assert.assertEquals(true, apsResult.isChangeRequested) + } + + @Test fun cloneTest() { + val apsResult = APSResult(HasAndroidInjector { AndroidInjector { Unit } }) + .also { + it.aapsLogger = aapsLogger + it.constraintChecker = constraintChecker + it.sp = sp + it.activePluginProvider = activePluginProvider + it.treatmentsPlugin = treatmentsPlugin + it.profileFunction = profileFunction + it.resourceHelper = resourceHelper + } + apsResult.rate(10.0) + val apsResult2 = apsResult.newAndClone(HasAndroidInjector { AndroidInjector { Unit } }) + Assert.assertEquals(apsResult.rate, apsResult2.rate, 0.0) + } + + @Test fun jsonTest() { + closedLoopEnabled.set(aapsLogger, true) + val apsResult = APSResult(HasAndroidInjector { AndroidInjector { Unit } }) + .also { + it.aapsLogger = aapsLogger + it.constraintChecker = constraintChecker + it.sp = sp + it.activePluginProvider = activePluginProvider + it.treatmentsPlugin = treatmentsPlugin + it.profileFunction = profileFunction + it.resourceHelper = resourceHelper + } + apsResult.rate(20.0).tempBasalRequested(true) + Assert.assertEquals(20.0, safeGetDouble(apsResult.json(), "rate"), 0.0) + apsResult.rate(20.0).tempBasalRequested(false) + Assert.assertEquals(false, apsResult.json().has("rate")) + } + + @Before + fun prepareMock() { + `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(closedLoopEnabled) + `when`(activePluginProvider.activePump).thenReturn(virtualPumpPlugin) + `when`(sp.getDouble(ArgumentMatchers.anyInt(), ArgumentMatchers.anyDouble())).thenReturn(30.0) + `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) + `when`(profileFunction.getProfile()).thenReturn(validProfile) + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt index 9bc37ae383..6dc589d145 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.sensitivity +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector import info.TestBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.logging.AAPSLogger @@ -21,7 +23,7 @@ class AbstractSensitivityPluginTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var sp: SP - private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, sp: SP) : AbstractSensitivityPlugin(pluginDescription, aapsLogger, resourceHelper, sp) { + private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, sp: SP) : AbstractSensitivityPlugin(pluginDescription, HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, resourceHelper, sp) { override fun detectSensitivity(plugin: IobCobCalculatorPlugin, fromTime: Long, toTime: Long): AutosensResult { return AutosensResult() From 7d9c1f8af9b60c40e4713fd439d6fdc5eeb00d89 Mon Sep 17 00:00:00 2001 From: TebbeUbben Date: Mon, 9 Mar 2020 23:07:55 +0100 Subject: [PATCH 046/100] Use "Display time-sensitive notifications" for Insight alerts --- app/src/main/AndroidManifest.xml | 3 + .../pump/insight/InsightAlertService.java | 187 ++++++++++++------ .../pump/insight/LocalInsightPlugin.java | 15 ++ .../activities/InsightAlertActivity.java | 175 ++-------------- .../pump/insight/descriptors/Alert.java | 20 ++ .../plugins/pump/insight/utils/AlertUtils.kt | 107 ++++++++++ app/src/main/res/values/strings.xml | 1 + app/src/main/res/values/styles.xml | 4 +- 8 files changed, 286 insertions(+), 226 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b571e247c2..6318d88e46 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -23,6 +23,7 @@ + @@ -264,6 +265,8 @@ alertLiveData = new MutableLiveData<>(); private Thread thread; - private InsightAlertActivity alertActivity; - private Ringtone ringtone; private Vibrator vibrator; private boolean vibrating; private InsightConnectionService connectionService; @@ -65,27 +68,6 @@ public class InsightAlertService extends Service implements InsightConnectionSer } }; - private void retrieveRingtone() { - Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); - ringtone = RingtoneManager.getRingtone(this, uri); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - ringtone.setAudioAttributes(new AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) - .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) - .setLegacyStreamType(AudioManager.STREAM_RING).build()); - } else ringtone.setStreamType(AudioManager.STREAM_RING); - } - - public Alert getAlert() { - synchronized ($alertLock) { - return alert; - } - } - - public void setAlertActivity(InsightAlertActivity alertActivity) { - this.alertActivity = alertActivity; - } - public void ignore(AlertType alertType) { synchronized ($alertLock) { if (alertType == null) { @@ -98,6 +80,10 @@ public class InsightAlertService extends Service implements InsightConnectionSer } } + public MutableLiveData getAlertLiveData() { + return alertLiveData; + } + @Nullable @Override public IBinder onBind(Intent intent) { @@ -108,6 +94,7 @@ public class InsightAlertService extends Service implements InsightConnectionSer public void onCreate() { vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); bindService(new Intent(this, InsightConnectionService.class), serviceConnection, BIND_AUTO_CREATE); + alertLiveData.setValue(null); } @Override @@ -118,6 +105,12 @@ public class InsightAlertService extends Service implements InsightConnectionSer @Override public int onStartCommand(Intent intent, int flags, int startId) { + if ("mute".equals(intent.getStringExtra("command"))) { + mute(); + } else if ("confirm".equals(intent.getStringExtra("command"))) { + dismissNotification(); + confirm(); + } return START_STICKY; } @@ -127,25 +120,47 @@ public class InsightAlertService extends Service implements InsightConnectionSer thread = new Thread(this::queryActiveAlert); thread.start(); - } else if (thread != null) thread.interrupt(); + } else { + dismissNotification(); + if (thread != null) thread.interrupt(); + } } private void queryActiveAlert() { while (!Thread.currentThread().isInterrupted()) { try { Alert alert = connectionService.requestMessage(new GetActiveAlertMessage()).await().getAlert(); - if (Thread.currentThread().isInterrupted()) { - connectionService.withdrawConnectionRequest(thread); - break; - } synchronized ($alertLock) { - if ((this.alert == null && alert != null) + if (alert == null || (alert.getAlertType() == ignoreType && System.currentTimeMillis() - ignoreTimestamp < 10000)) { + if (connectionRequested) { + connectionService.withdrawConnectionRequest(this); + connectionRequested = false; + } + this.alertLiveData.postValue(null); + this.alert = null; + dismissNotification(); + stopAlerting(); + } else if (!alert.equals(this.alert)) { + if (!connectionRequested) { + connectionService.requestConnection(this); + connectionRequested = true; + } + showNotification(alert); + this.alertLiveData.postValue(alert); + this.alert = alert; + if (alert.getAlertStatus() == AlertStatus.SNOOZED) stopAlerting(); + else alert(); + } + /*if ((this.alert == null && alert != null) || (this.alert != null && alert == null) || (this.alert != null && alert != null && !this.alert.equals(alert))) { if (this.alert != null && (alert == null || this.alert.getAlertId() != alert.getAlertId())) stopAlerting(); this.alert = alert; - if (alertActivity != null && alert != null) - new Handler(Looper.getMainLooper()).post(() -> alertActivity.update(alert)); + if (alert != null) + new Handler(Looper.getMainLooper()).post(() -> { + //showNotification(alert); + //alertActivity.update(alert); + }); } if (alert == null) { stopAlerting(); @@ -153,8 +168,10 @@ public class InsightAlertService extends Service implements InsightConnectionSer connectionService.withdrawConnectionRequest(this); connectionRequested = false; } - if (alertActivity != null) - new Handler(Looper.getMainLooper()).post(() -> alertActivity.finish()); + new Handler(Looper.getMainLooper()).post(() -> { + //dismissNotification(); + //alertActivity.finish(); + }); } else if (!(alert.getAlertType() == ignoreType && System.currentTimeMillis() - ignoreTimestamp < 10000)) { if (alert.getAlertStatus() == AlertStatus.ACTIVE) alert(); else stopAlerting(); @@ -162,12 +179,12 @@ public class InsightAlertService extends Service implements InsightConnectionSer connectionService.requestConnection(this); connectionRequested = true; } - if (alertActivity == null) { + /*if (alertActivity == null) { Intent intent = new Intent(InsightAlertService.this, InsightAlertActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); new Handler(Looper.getMainLooper()).post(() -> startActivity(intent)); - } - } + }*/ + //} } } catch (InterruptedException ignored) { connectionService.withdrawConnectionRequest(thread); @@ -189,21 +206,18 @@ public class InsightAlertService extends Service implements InsightConnectionSer connectionService.withdrawConnectionRequest(thread); connectionRequested = false; } - if (alertActivity != null) - new Handler(Looper.getMainLooper()).post(() -> alertActivity.finish()); stopAlerting(); + alertLiveData.postValue(null); + this.alert = null; + dismissNotification(); thread = null; } private void alert() { if (!vibrating) { - vibrator.vibrate(new long[] {0, 1000, 1000}, 0); + vibrator.vibrate(new long[]{0, 1000, 1000}, 0); vibrating = true; } - if (ringtone == null || !ringtone.isPlaying()) { - retrieveRingtone(); - ringtone.play(); - } } private void stopAlerting() { @@ -211,15 +225,21 @@ public class InsightAlertService extends Service implements InsightConnectionSer vibrator.cancel(); vibrating = false; } - if (ringtone != null && ringtone.isPlaying()) ringtone.stop(); } public void mute() { new Thread(() -> { try { - SnoozeAlertMessage snoozeAlertMessage = new SnoozeAlertMessage(); - snoozeAlertMessage.setAlertID(alert.getAlertId()); - connectionService.requestMessage(snoozeAlertMessage).await(); + synchronized ($alertLock) { + if (alert == null) return; + alert.setAlertStatus(AlertStatus.SNOOZED); + alertLiveData.postValue(alert); + stopAlerting(); + showNotification(alert); + SnoozeAlertMessage snoozeAlertMessage = new SnoozeAlertMessage(); + snoozeAlertMessage.setAlertID(alertLiveData.getValue().getAlertId()); + connectionService.requestMessage(snoozeAlertMessage).await(); + } } catch (AppLayerErrorException e) { log.info("Exception while muting alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); ExceptionTranslator.makeToast(InsightAlertService.this, e); @@ -236,9 +256,16 @@ public class InsightAlertService extends Service implements InsightConnectionSer public void confirm() { new Thread(() -> { try { - ConfirmAlertMessage confirmAlertMessage = new ConfirmAlertMessage(); - confirmAlertMessage.setAlertID(alert.getAlertId()); - connectionService.requestMessage(confirmAlertMessage).await(); + synchronized ($alertLock) { + if (alert == null) return; + stopAlerting(); + alertLiveData.postValue(null); + dismissNotification(); + ConfirmAlertMessage confirmAlertMessage = new ConfirmAlertMessage(); + confirmAlertMessage.setAlertID(alertLiveData.getValue().getAlertId()); + connectionService.requestMessage(confirmAlertMessage).await(); + this.alert = null; + } } catch (AppLayerErrorException e) { log.info("Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); ExceptionTranslator.makeToast(InsightAlertService.this, e); @@ -252,6 +279,48 @@ public class InsightAlertService extends Service implements InsightConnectionSer }).start(); } + private void showNotification(Alert alert) { + NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, LocalInsightPlugin.ALERT_CHANNEL_ID); + + notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX); + notificationBuilder.setCategory(NotificationCompat.CATEGORY_ALARM); + notificationBuilder.setVibrate(new long[0]); + notificationBuilder.setShowWhen(false); + notificationBuilder.setOngoing(true); + notificationBuilder.setOnlyAlertOnce(true); + notificationBuilder.setAutoCancel(false); + notificationBuilder.setSmallIcon(AlertUtilsKt.getAlertIcon(alert.getAlertCategory())); + + notificationBuilder.setContentTitle(AlertUtilsKt.getAlertCode(alert.getAlertType()) + " – " + AlertUtilsKt.getAlertTitle(alert.getAlertType())); + String description = AlertUtilsKt.getAlertDescription(alert); + if (description != null) + notificationBuilder.setContentText(Html.fromHtml(description).toString()); + + Intent fullScreenIntent = new Intent(this, InsightAlertActivity.class); + PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); + notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true); + + switch (alert.getAlertStatus()) { + case ACTIVE: + Intent muteIntent = new Intent(this, InsightAlertService.class).putExtra("command", "mute"); + PendingIntent mutePendingIntent = PendingIntent.getService(this, 1, muteIntent, PendingIntent.FLAG_UPDATE_CURRENT); + notificationBuilder.addAction(0, MainApp.gs(R.string.mute_alert), mutePendingIntent); + case SNOOZED: + Intent confirmIntent = new Intent(this, InsightAlertService.class).putExtra("command", "confirm"); + PendingIntent confirmPendingIntent = PendingIntent.getService(this, 2, confirmIntent, PendingIntent.FLAG_UPDATE_CURRENT); + notificationBuilder.addAction(0, MainApp.gs(R.string.confirm), confirmPendingIntent); + } + + Notification notification = notificationBuilder.build(); + NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification); + startForeground(NOTIFICATION_ID, notification); + } + + private void dismissNotification() { + NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID); + stopForeground(true); + } + public class LocalBinder extends Binder { public InsightAlertService getService() { return InsightAlertService.this; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 2197b48577..66ee0bed5a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -1,9 +1,12 @@ package info.nightscout.androidaps.plugins.pump.insight; +import android.app.NotificationChannel; +import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; +import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Looper; @@ -132,6 +135,8 @@ import info.nightscout.androidaps.utils.SP; public class LocalInsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface, InsightConnectionService.StateCallback { + public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; + private static LocalInsightPlugin instance = null; private Logger log = LoggerFactory.getLogger(L.PUMP); @@ -245,6 +250,15 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con super.onStart(); MainApp.instance().bindService(new Intent(MainApp.instance(), InsightConnectionService.class), serviceConnection, Context.BIND_AUTO_CREATE); MainApp.instance().bindService(new Intent(MainApp.instance(), InsightAlertService.class), serviceConnection, Context.BIND_AUTO_CREATE); + createNotificationChannel(); + } + + private void createNotificationChannel() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationManager notificationManager = (NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE); + NotificationChannel channel = new NotificationChannel(ALERT_CHANNEL_ID, MainApp.gs(R.string.insight_alert_notification_channel), NotificationManager.IMPORTANCE_HIGH); + notificationManager.createNotificationChannel(channel); + } } @Override @@ -647,6 +661,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con cancelBolusMessage.setBolusID(bolusID); connectionService.requestMessage(cancelBolusMessage).await(); bolusCancelled = true; + alertService.ignore(null); } confirmAlert(AlertType.WARNING_38); } catch (AppLayerErrorException e) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java index 77be3ab03a..8ebd05801b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java @@ -12,19 +12,18 @@ import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; +import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; -import java.text.DecimalFormat; - import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService; import info.nightscout.androidaps.plugins.pump.insight.descriptors.Alert; import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertStatus; +import info.nightscout.androidaps.plugins.pump.insight.utils.AlertUtilsKt; -public class InsightAlertActivity extends NoSplashAppCompatActivity { +public class InsightAlertActivity extends AppCompatActivity { - private Alert alert; private InsightAlertService alertService; private ImageView icon; @@ -38,10 +37,10 @@ public class InsightAlertActivity extends NoSplashAppCompatActivity { @Override public void onServiceConnected(ComponentName name, IBinder binder) { alertService = ((InsightAlertService.LocalBinder) binder).getService(); - alertService.setAlertActivity(InsightAlertActivity.this); - alert = alertService.getAlert(); - if (alert == null) finish(); - else update(alert); + alertService.getAlertLiveData().observe(InsightAlertActivity.this, alert -> { + if (alert == null) finish(); + else update(alert); + }); } @Override @@ -70,174 +69,22 @@ public class InsightAlertActivity extends NoSplashAppCompatActivity { | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); - WindowManager.LayoutParams layoutParams = getWindow().getAttributes(); - layoutParams.screenBrightness = 1.0F; - getWindow().setAttributes(layoutParams); } @Override protected void onDestroy() { - alertService.setAlertActivity(null); unbindService(serviceConnection); super.onDestroy(); } public void update(Alert alert) { - this.alert = alert; mute.setEnabled(true); mute.setVisibility(alert.getAlertStatus() == AlertStatus.SNOOZED ? View.GONE : View.VISIBLE); confirm.setEnabled(true); - int icon = 0; - int code = 0; - int title = 0; - String description = null; - switch (alert.getAlertCategory()) { - case ERROR: - icon = R.drawable.ic_error; - break; - case MAINTENANCE: - icon = R.drawable.ic_maintenance; - break; - case WARNING: - icon = R.drawable.ic_warning; - break; - case REMINDER: - icon = R.drawable.ic_reminder; - break; - } - DecimalFormat decimalFormat = new DecimalFormat("##0.00"); - int hours = alert.getTBRDuration() / 60; - int minutes = alert.getTBRDuration() - hours * 60; - switch (alert.getAlertType()) { - case REMINDER_01: - code = R.string.alert_r1_code; - title = R.string.alert_r1_title; - break; - case REMINDER_02: - code = R.string.alert_r2_code; - title = R.string.alert_r2_title; - break; - case REMINDER_03: - code = R.string.alert_r3_code; - title = R.string.alert_r3_title; - break; - case REMINDER_04: - code = R.string.alert_r4_code; - title = R.string.alert_r4_title; - break; - case REMINDER_07: - code = R.string.alert_r7_code; - title = R.string.alert_r7_title; - description = getString(R.string.alert_r7_description, alert.getTBRAmount(), new DecimalFormat("#0").format(hours) + ":" + new DecimalFormat("00").format(minutes)); - break; - case WARNING_31: - code = R.string.alert_w31_code; - title = R.string.alert_w31_title; - description = getString(R.string.alert_w31_description, decimalFormat.format(alert.getCartridgeAmount())); - break; - case WARNING_32: - code = R.string.alert_w32_code; - title = R.string.alert_w32_title; - description = getString(R.string.alert_w32_description); - break; - case WARNING_33: - code = R.string.alert_w33_code; - title = R.string.alert_w33_title; - description = getString(R.string.alert_w33_description); - break; - case WARNING_34: - code = R.string.alert_w34_code; - title = R.string.alert_w34_title; - description = getString(R.string.alert_w34_description); - break; - case WARNING_36: - code = R.string.alert_w36_code; - title = R.string.alert_w36_title; - description = getString(R.string.alert_w36_description, alert.getTBRAmount(), new DecimalFormat("#0").format(hours) + ":" + new DecimalFormat("00").format(minutes)); - break; - case WARNING_38: - code = R.string.alert_w38_code; - title = R.string.alert_w38_title; - description = getString(R.string.alert_w38_description, decimalFormat.format(alert.getProgrammedBolusAmount()), decimalFormat.format(alert.getDeliveredBolusAmount())); - break; - case WARNING_39: - code = R.string.alert_w39_code; - title = R.string.alert_w39_title; - break; - case MAINTENANCE_20: - code = R.string.alert_m20_code; - title = R.string.alert_m20_title; - description = getString(R.string.alert_m20_description); - break; - case MAINTENANCE_21: - code = R.string.alert_m21_code; - title = R.string.alert_m21_title; - description = getString(R.string.alert_m21_description); - break; - case MAINTENANCE_22: - code = R.string.alert_m22_code; - title = R.string.alert_m22_title; - description = getString(R.string.alert_m22_description); - break; - case MAINTENANCE_23: - code = R.string.alert_m23_code; - title = R.string.alert_m23_title; - description = getString(R.string.alert_m23_description); - break; - case MAINTENANCE_24: - code = R.string.alert_m24_code; - title = R.string.alert_m24_title; - description = getString(R.string.alert_m24_description); - break; - case MAINTENANCE_25: - code = R.string.alert_m25_code; - title = R.string.alert_m25_title; - description = getString(R.string.alert_m25_description); - break; - case MAINTENANCE_26: - code = R.string.alert_m26_code; - title = R.string.alert_m26_title; - description = getString(R.string.alert_m26_description); - break; - case MAINTENANCE_27: - code = R.string.alert_m27_code; - title = R.string.alert_m27_title; - description = getString(R.string.alert_m27_description); - break; - case MAINTENANCE_28: - code = R.string.alert_m28_code; - title = R.string.alert_m28_title; - description = getString(R.string.alert_m28_description); - break; - case MAINTENANCE_29: - code = R.string.alert_m29_code; - title = R.string.alert_m29_title; - description = getString(R.string.alert_m29_description); - break; - case MAINTENANCE_30: - code = R.string.alert_m30_code; - title = R.string.alert_m30_title; - description = getString(R.string.alert_m30_description); - break; - case ERROR_6: - code = R.string.alert_e6_code; - title = R.string.alert_e6_title; - description = getString(R.string.alert_e6_description); - break; - case ERROR_10: - code = R.string.alert_e10_code; - title = R.string.alert_e10_title; - description = getString(R.string.alert_e10_description); - break; - case ERROR_13: - code = R.string.alert_e13_code; - title = R.string.alert_e13_title; - description = getString(R.string.alert_e13_description); - break; - } - this.icon.setImageDrawable(ContextCompat.getDrawable(this, icon)); - this.errorCode.setText(code); - this.errorTitle.setText(title); + this.icon.setImageDrawable(ContextCompat.getDrawable(this, AlertUtilsKt.getAlertIcon(alert.getAlertCategory()))); + this.errorCode.setText(AlertUtilsKt.getAlertCode(alert.getAlertType())); + this.errorTitle.setText(AlertUtilsKt.getAlertTitle(alert.getAlertType())); + String description = AlertUtilsKt.getAlertDescription(alert); if (description == null) this.errorDescription.setVisibility(View.GONE); else { this.errorDescription.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/descriptors/Alert.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/descriptors/Alert.java index 8f6668c1ca..028fcb3b71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/descriptors/Alert.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/descriptors/Alert.java @@ -83,4 +83,24 @@ public class Alert { public double getCartridgeAmount() { return cartridgeAmount; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Alert alert = (Alert) o; + + if (alertId != alert.alertId) return false; + if (tbrAmount != alert.tbrAmount) return false; + if (tbrDuration != alert.tbrDuration) return false; + if (Double.compare(alert.programmedBolusAmount, programmedBolusAmount) != 0) + return false; + if (Double.compare(alert.deliveredBolusAmount, deliveredBolusAmount) != 0) + return false; + if (Double.compare(alert.cartridgeAmount, cartridgeAmount) != 0) return false; + if (alertCategory != alert.alertCategory) return false; + if (alertType != alert.alertType) return false; + return alertStatus == alert.alertStatus; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt new file mode 100644 index 0000000000..7cafb950cc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt @@ -0,0 +1,107 @@ +package info.nightscout.androidaps.plugins.pump.insight.utils + +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.plugins.pump.insight.descriptors.Alert +import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertCategory +import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertType +import java.text.DecimalFormat + +fun getAlertCode(alertType: AlertType) = MainApp.gs(when (alertType) { + AlertType.REMINDER_01 -> R.string.alert_r1_code + AlertType.REMINDER_02 -> R.string.alert_r2_code + AlertType.REMINDER_03 -> R.string.alert_r3_code + AlertType.REMINDER_04 -> R.string.alert_r4_code + AlertType.REMINDER_07 -> R.string.alert_r7_code + AlertType.WARNING_31 -> R.string.alert_w31_code + AlertType.WARNING_32 -> R.string.alert_w32_code + AlertType.WARNING_33 -> R.string.alert_w33_code + AlertType.WARNING_34 -> R.string.alert_w34_code + AlertType.WARNING_36 -> R.string.alert_w36_code + AlertType.WARNING_38 -> R.string.alert_w38_code + AlertType.WARNING_39 -> R.string.alert_w39_code + AlertType.MAINTENANCE_20 -> R.string.alert_m20_code + AlertType.MAINTENANCE_21 -> R.string.alert_m21_code + AlertType.MAINTENANCE_22 -> R.string.alert_m22_code + AlertType.MAINTENANCE_23 -> R.string.alert_m23_code + AlertType.MAINTENANCE_24 -> R.string.alert_m24_code + AlertType.MAINTENANCE_25 -> R.string.alert_m25_code + AlertType.MAINTENANCE_26 -> R.string.alert_m26_code + AlertType.MAINTENANCE_27 -> R.string.alert_m27_code + AlertType.MAINTENANCE_28 -> R.string.alert_m28_code + AlertType.MAINTENANCE_29 -> R.string.alert_m29_code + AlertType.MAINTENANCE_30 -> R.string.alert_m30_code + AlertType.ERROR_6 -> R.string.alert_e6_code + AlertType.ERROR_10 -> R.string.alert_e10_code + AlertType.ERROR_13 -> R.string.alert_e13_code +}) + +fun getAlertTitle(alertType: AlertType) = MainApp.gs(when (alertType) { + AlertType.REMINDER_01 -> R.string.alert_r1_title + AlertType.REMINDER_02 -> R.string.alert_r2_title + AlertType.REMINDER_03 -> R.string.alert_r3_title + AlertType.REMINDER_04 -> R.string.alert_r4_title + AlertType.REMINDER_07 -> R.string.alert_r7_title + AlertType.WARNING_31 -> R.string.alert_w31_title + AlertType.WARNING_32 -> R.string.alert_w32_title + AlertType.WARNING_33 -> R.string.alert_w33_title + AlertType.WARNING_34 -> R.string.alert_w34_title + AlertType.WARNING_36 -> R.string.alert_w36_title + AlertType.WARNING_38 -> R.string.alert_w38_title + AlertType.WARNING_39 -> R.string.alert_w39_title + AlertType.MAINTENANCE_20 -> R.string.alert_m20_title + AlertType.MAINTENANCE_21 -> R.string.alert_m21_title + AlertType.MAINTENANCE_22 -> R.string.alert_m22_title + AlertType.MAINTENANCE_23 -> R.string.alert_m23_title + AlertType.MAINTENANCE_24 -> R.string.alert_m24_title + AlertType.MAINTENANCE_25 -> R.string.alert_m25_title + AlertType.MAINTENANCE_26 -> R.string.alert_m26_title + AlertType.MAINTENANCE_27 -> R.string.alert_m27_title + AlertType.MAINTENANCE_28 -> R.string.alert_m28_title + AlertType.MAINTENANCE_29 -> R.string.alert_m29_title + AlertType.MAINTENANCE_30 -> R.string.alert_m30_title + AlertType.ERROR_6 -> R.string.alert_e6_title + AlertType.ERROR_10 -> R.string.alert_e10_title + AlertType.ERROR_13 -> R.string.alert_e13_title +}) + +fun getAlertDescription(alert: Alert): String? { + val decimalFormat = DecimalFormat("##0.00") + val hours = alert.tbrDuration / 60 + val minutes = alert.tbrDuration - hours * 60 + return when (alert.alertType!!) { + AlertType.REMINDER_01 -> null + AlertType.REMINDER_02 -> null + AlertType.REMINDER_03 -> null + AlertType.REMINDER_04 -> null + AlertType.REMINDER_07 -> MainApp.gs(R.string.alert_r7_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong())) + AlertType.WARNING_31 -> MainApp.gs(R.string.alert_w31_description, decimalFormat.format(alert.cartridgeAmount)) + AlertType.WARNING_32 -> MainApp.gs(R.string.alert_w32_description) + AlertType.WARNING_33 -> MainApp.gs(R.string.alert_w33_description) + AlertType.WARNING_34 -> MainApp.gs(R.string.alert_w34_description) + AlertType.WARNING_36 -> MainApp.gs(R.string.alert_w36_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong())) + AlertType.WARNING_38 -> MainApp.gs(R.string.alert_w38_description, decimalFormat.format(alert.programmedBolusAmount), decimalFormat.format(alert.deliveredBolusAmount)) + AlertType.WARNING_39 -> null + AlertType.MAINTENANCE_20 -> MainApp.gs(R.string.alert_m20_description) + AlertType.MAINTENANCE_21 -> MainApp.gs(R.string.alert_m21_description) + AlertType.MAINTENANCE_22 -> MainApp.gs(R.string.alert_m22_description) + AlertType.MAINTENANCE_23 -> MainApp.gs(R.string.alert_m23_description) + AlertType.MAINTENANCE_24 -> MainApp.gs(R.string.alert_m24_description) + AlertType.MAINTENANCE_25 -> MainApp.gs(R.string.alert_m25_description) + AlertType.MAINTENANCE_26 -> MainApp.gs(R.string.alert_m26_description) + AlertType.MAINTENANCE_27 -> MainApp.gs(R.string.alert_m27_description) + AlertType.MAINTENANCE_28 -> MainApp.gs(R.string.alert_m28_description) + AlertType.MAINTENANCE_29 -> MainApp.gs(R.string.alert_m29_description) + AlertType.MAINTENANCE_30 -> MainApp.gs(R.string.alert_m30_description) + AlertType.ERROR_6 -> MainApp.gs(R.string.alert_e6_description) + AlertType.ERROR_10 -> MainApp.gs(R.string.alert_e10_description) + AlertType.ERROR_13 -> MainApp.gs(R.string.alert_e13_description) + } +} + +fun getAlertIcon(alertCategory: AlertCategory) = when (alertCategory) { + AlertCategory.ERROR -> R.drawable.ic_error + AlertCategory.MAINTENANCE -> R.drawable.ic_maintenance + AlertCategory.WARNING -> R.drawable.ic_warning + AlertCategory.REMINDER -> R.drawable.ic_reminder +} \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2e06c2a027..a4c79cb63b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1698,5 +1698,6 @@ SMB execution time Temp basal request time Temp basal execution time + Insight Pump Alerts
diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index d2cacff3b7..d78df37ac4 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -27,12 +27,10 @@ @android:style/Animation -