Merge branch 'dagger3' into TOTP

This commit is contained in:
Milos Kozak 2020-03-20 15:58:17 +01:00
commit 5d32bfec95
851 changed files with 18292 additions and 22306 deletions

View file

@ -1,9 +1,6 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<option name="AUTODETECT_INDENTS" value="false" />
<AndroidXmlCodeStyleSettings>
<option name="ARRANGEMENT_SETTINGS_MIGRATED_TO_191" value="true" />
</AndroidXmlCodeStyleSettings>
<JetCodeStyleSettings>
<option name="ALIGN_IN_COLUMNS_CASE_BRANCH" value="true" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="6" />

View file

@ -109,7 +109,7 @@ android {
targetSdkVersion 28
multiDexEnabled true
versionCode 1500
version "2.6-dev-dagger3"
version "2.6.1-dagger3"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
@ -336,6 +336,7 @@ dependencies {
/* Dagger2 - default dependency */
kapt 'com.google.dagger:dagger-compiler:2.25.2'
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}
@ -362,7 +363,37 @@ 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
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

Binary file not shown.

View file

@ -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()
}

View file

@ -0,0 +1,132 @@
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.logging.L
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
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.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.extensions.isRunningTest
import info.nightscout.androidaps.utils.sharedPreferences.SP
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
import javax.inject.Inject
@LargeTest
@RunWith(AndroidJUnit4::class)
class RealPumpTest {
private val log = LoggerFactory.getLogger(L.CORE)
companion object {
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\"}"
@Inject lateinit var pump : DanaRv2Plugin
@Inject lateinit var randomBgPlugin :RandomBgPlugin
@Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var insulinOrefUltraRapidActingPlugin: InsulinOrefUltraRapidActingPlugin
@Inject lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var actionsPlugin: ActionsPlugin
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var objectivesPlugin: ObjectivesPlugin
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var sp: SP
@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
configBuilderPlugin.performPluginSwitch(randomBgPlugin,true, PluginType.BGSOURCE)
// Profile
configBuilderPlugin.performPluginSwitch(localProfilePlugin, 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(localProfilePlugin.rawProfile, profile, "TestProfile")
localProfilePlugin.addProfile(singleProfile)
val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, DateUtil.now())
treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch)
// Insulin
configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN)
// Pump
sp.putInt(R.string.key_danar_password, R_PASSWORD)
sp.putString(R.string.key_danar_bt_name, R_SERIAL)
configBuilderPlugin.performPluginSwitch((pump as PluginBase), true, PluginType.PUMP)
// Sensitivity
configBuilderPlugin.performPluginSwitch(sensitivityOref1Plugin, true, PluginType.SENSITIVITY)
// APS
configBuilderPlugin.performPluginSwitch(openAPSSMBPlugin, true, PluginType.APS)
configBuilderPlugin.performPluginSwitch(loopPlugin, true, PluginType.LOOP)
// Enable common
configBuilderPlugin.performPluginSwitch(actionsPlugin, 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)
}
}
}

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps
import android.os.SystemClock
import android.view.View
import android.view.ViewGroup
@ -9,7 +8,11 @@ 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
@ -38,7 +41,6 @@ import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class SetupWizardActivityTest {
@ -49,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() {
@ -73,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())
@ -85,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())
@ -98,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())
@ -124,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())
}
@ -203,7 +213,7 @@ adb shell settings put global animator_duration_scale 0 &
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
@ -214,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)
}
}
}

View file

@ -23,6 +23,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.dexcom.cgm.EXTERNAL_PERMISSION" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
@ -123,14 +124,6 @@
</intent-filter>
</receiver>
<!-- Network change local receiver -->
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
@ -264,6 +257,8 @@
<activity
android:name=".plugins.pump.insight.activities.InsightAlertActivity"
android:label="@string/pump_alert"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:theme="@style/InsightAlertDialog" />
<activity
android:name=".plugins.pump.insight.activities.InsightPairingInformationActivity"

View file

@ -37,7 +37,6 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.activities.SingleFragmentActivity;
@ -45,6 +44,8 @@ import info.nightscout.androidaps.activities.StatsActivity;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger;
@ -61,11 +62,14 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.PasswordProtection;
import info.nightscout.androidaps.utils.buildHelper.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import static info.nightscout.androidaps.utils.extensions.EspressoTestHelperKt.isRunningRealPumpTest;
public class MainActivity extends NoSplashAppCompatActivity {
private CompositeDisposable disposable = new CompositeDisposable();
@ -80,6 +84,8 @@ public class MainActivity extends NoSplashAppCompatActivity {
@Inject SmsCommunicatorPlugin smsCommunicatorPlugin;
@Inject LoopPlugin loopPlugin;
@Inject NSSettingsStatus nsSettingsStatus;
@Inject BuildHelper buildHelper;
@Inject ActivePluginProvider activePlugin;
@Override
@ -149,7 +155,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
.subscribe(this::processPreferenceChange, exception -> FabricPrivacy.getInstance().logException(exception))
);
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);
}
@ -201,14 +207,14 @@ public class MainActivity extends NoSplashAppCompatActivity {
navigationView.setNavigationItemSelectedListener(menuItem -> true);
Menu menu = navigationView.getMenu();
menu.clear();
for (PluginBase p : MainApp.getPluginsList()) {
for (PluginBase p : activePlugin.getPluginsList()) {
pageAdapter.registerNewFragment(p);
if (p.hasFragment() && !p.isFragmentVisible() && p.isEnabled(p.getPluginDescription().getType()) && !p.getPluginDescription().neverVisible) {
MenuItem menuItem = menu.add(p.getName());
menuItem.setCheckable(true);
menuItem.setOnMenuItemClickListener(item -> {
Intent intent = new Intent(this, SingleFragmentActivity.class);
intent.putExtra("plugin", MainApp.getPluginsList().indexOf(p));
intent.putExtra("plugin", activePlugin.getPluginsList().indexOf(p));
startActivity(intent);
((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawers();
return true;
@ -314,7 +320,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getNightscoutVersionName();
if (MainApp.engineeringMode)
if (buildHelper.isEngineeringMode())
message += "\n" + resourceHelper.gs(R.string.engineering_mode_enabled);
message += resourceHelper.gs(R.string.about_link_urls);
final SpannableString messageSpanned = new SpannableString(message);

View file

@ -7,9 +7,10 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import androidx.annotation.ColorRes;
import androidx.annotation.PluralsRes;
import androidx.annotation.StringRes;
import androidx.core.app.NotificationCompat;
import androidx.core.app.TaskStackBuilder;
@ -23,31 +24,24 @@ import com.j256.ormlite.android.apptools.OpenHelperManager;
import net.danlew.android.joda.JodaTimeAndroid;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
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.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
@ -60,7 +54,6 @@ import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin;
import info.nightscout.androidaps.plugins.general.food.FoodPlugin;
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils;
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@ -101,18 +94,17 @@ import info.nightscout.androidaps.plugins.source.XdripPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NetworkChangeReceiver;
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.ActivityMonitor;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OneTimePassword;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.fabric.sdk.android.Fabric;
public class MainApp extends DaggerApplication {
static Logger log = StacktraceLoggerWrapper.getLogger(L.CORE);
static MainApp sInstance;
private static Resources sResources;
@ -121,24 +113,22 @@ public class MainApp extends DaggerApplication {
static DatabaseHelper sDatabaseHelper = null;
static ArrayList<PluginBase> pluginsList = new ArrayList<>();
static DataReceiver dataReceiver = new DataReceiver();
DataReceiver dataReceiver = new DataReceiver();
TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver;
public static boolean devBranch;
public static boolean engineeringMode;
private String CHANNEL_ID = "AndroidAPS-Ongoing"; // TODO: move to OngoingNotificationProvider (and dagger)
private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger)
private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger)
@Inject PluginStore pluginStore;
@Inject public HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject ActivityMonitor activityMonitor;
@Inject FabricPrivacy fabricPrivacy;
@Inject ResourceHelper resourceHelper;
@Inject VersionCheckerUtils versionCheckersUtils;
@Inject OneTimePassword oneTimePassword;
@Inject SP sp;
@Inject ProfileFunction profileFunction;
@Inject ActionsPlugin actionsPlugin;
@Inject AutomationPlugin automationPlugin;
@ -199,7 +189,7 @@ public class MainApp extends DaggerApplication {
public void onCreate() {
super.onCreate();
log.debug("onCreate");
aapsLogger.debug("onCreate");
sInstance = this;
sResources = getResources();
LocaleHelper.INSTANCE.update(this);
@ -221,7 +211,7 @@ public class MainApp extends DaggerApplication {
Fabric.with(this, new Crashlytics());
}
} catch (Exception e) {
log.error("Error with Fabric init! " + e);
aapsLogger.error("Error with Fabric init! " + e);
}
registerActivityLifecycleCallbacks(activityMonitor);
@ -231,15 +221,9 @@ public class MainApp extends DaggerApplication {
JodaTimeAndroid.init(this);
log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
log.info("Remote: " + BuildConfig.REMOTE);
String extFilesDir = LoggerUtils.getLogDirectory();
File engineeringModeSemaphore = new File(extFilesDir, "engineering_mode");
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(".*[a-zA-Z]+.*");
aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME);
aapsLogger.debug("BuildVersion: " + BuildConfig.BUILDVERSION);
aapsLogger.debug("Remote: " + BuildConfig.REMOTE);
registerLocalBroadcastReceiver();
@ -247,61 +231,61 @@ public class MainApp extends DaggerApplication {
versionCheckersUtils.triggerCheckVersion();
// Register all tabs in app here
pluginsList.add(overviewPlugin);
pluginsList.add(iobCobCalculatorPlugin);
if (!Config.NSCLIENT) pluginsList.add(actionsPlugin);
pluginsList.add(insulinOrefRapidActingPlugin);
pluginsList.add(insulinOrefUltraRapidActingPlugin);
pluginsList.add(insulinOrefFreePeakPlugin);
pluginsList.add(sensitivityOref0Plugin);
pluginsList.add(sensitivityAAPSPlugin);
pluginsList.add(sensitivityWeightedAveragePlugin);
pluginsList.add(sensitivityOref1Plugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRKoreanPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRv2Plugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRSPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(localInsightPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(comboPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(medtronicPumpPlugin);
if (!Config.NSCLIENT) pluginsList.add(mdiPlugin);
if (!Config.NSCLIENT) pluginsList.add(virtualPumpPlugin);
if (Config.NSCLIENT) pluginsList.add(careportalPlugin);
if (Config.APS) pluginsList.add(loopPlugin);
if (Config.APS) pluginsList.add(openAPSMAPlugin);
if (Config.APS) pluginsList.add(openAPSAMAPlugin);
if (Config.APS) pluginsList.add(openAPSSMBPlugin);
pluginsList.add(nsProfilePlugin);
if (!Config.NSCLIENT) pluginsList.add(localProfilePlugin);
pluginsList.add(treatmentsPlugin);
if (!Config.NSCLIENT) pluginsList.add(safetyPlugin);
if (!Config.NSCLIENT) pluginsList.add(versionCheckerPlugin);
if (Config.APS) pluginsList.add(storageConstraintPlugin);
if (Config.APS) pluginsList.add(signatureVerifierPlugin);
if (Config.APS) pluginsList.add(objectivesPlugin);
pluginsList.add(xdripPlugin);
pluginsList.add(nSClientSourcePlugin);
pluginsList.add(mM640GPlugin);
pluginsList.add(glimpPlugin);
pluginsList.add(dexcomPlugin);
pluginsList.add(poctechPlugin);
pluginsList.add(tomatoPlugin);
pluginsList.add(eversensePlugin);
pluginsList.add(randomBgPlugin);
if (!Config.NSCLIENT) pluginsList.add(smsCommunicatorPlugin);
pluginsList.add(foodPlugin);
pluginStore.add(overviewPlugin);
pluginStore.add(iobCobCalculatorPlugin);
if (!Config.NSCLIENT) pluginStore.add(actionsPlugin);
pluginStore.add(insulinOrefRapidActingPlugin);
pluginStore.add(insulinOrefUltraRapidActingPlugin);
pluginStore.add(insulinOrefFreePeakPlugin);
pluginStore.add(sensitivityOref0Plugin);
pluginStore.add(sensitivityAAPSPlugin);
pluginStore.add(sensitivityWeightedAveragePlugin);
pluginStore.add(sensitivityOref1Plugin);
if (Config.PUMPDRIVERS) pluginStore.add(danaRPlugin);
if (Config.PUMPDRIVERS) pluginStore.add(danaRKoreanPlugin);
if (Config.PUMPDRIVERS) pluginStore.add(danaRv2Plugin);
if (Config.PUMPDRIVERS) pluginStore.add(danaRSPlugin);
if (Config.PUMPDRIVERS) pluginStore.add(localInsightPlugin);
if (Config.PUMPDRIVERS) pluginStore.add(comboPlugin);
if (Config.PUMPDRIVERS) pluginStore.add(medtronicPumpPlugin);
if (!Config.NSCLIENT) pluginStore.add(mdiPlugin);
if (!Config.NSCLIENT) pluginStore.add(virtualPumpPlugin);
if (Config.NSCLIENT) pluginStore.add(careportalPlugin);
if (Config.APS) pluginStore.add(loopPlugin);
if (Config.APS) pluginStore.add(openAPSMAPlugin);
if (Config.APS) pluginStore.add(openAPSAMAPlugin);
if (Config.APS) pluginStore.add(openAPSSMBPlugin);
pluginStore.add(nsProfilePlugin);
if (!Config.NSCLIENT) pluginStore.add(localProfilePlugin);
pluginStore.add(treatmentsPlugin);
if (!Config.NSCLIENT) pluginStore.add(safetyPlugin);
if (!Config.NSCLIENT) pluginStore.add(versionCheckerPlugin);
if (Config.APS) pluginStore.add(storageConstraintPlugin);
if (Config.APS) pluginStore.add(signatureVerifierPlugin);
if (Config.APS) pluginStore.add(objectivesPlugin);
pluginStore.add(xdripPlugin);
pluginStore.add(nSClientSourcePlugin);
pluginStore.add(mM640GPlugin);
pluginStore.add(glimpPlugin);
pluginStore.add(dexcomPlugin);
pluginStore.add(poctechPlugin);
pluginStore.add(tomatoPlugin);
pluginStore.add(eversensePlugin);
pluginStore.add(randomBgPlugin);
if (!Config.NSCLIENT) pluginStore.add(smsCommunicatorPlugin);
pluginStore.add(foodPlugin);
pluginsList.add(wearPlugin);
pluginsList.add(statusLinePlugin);
pluginsList.add(persistentNotificationPlugin);
pluginsList.add(nsClientPlugin);
pluginStore.add(wearPlugin);
pluginStore.add(statusLinePlugin);
pluginStore.add(persistentNotificationPlugin);
pluginStore.add(nsClientPlugin);
// if (engineeringMode) pluginsList.add(tidepoolPlugin);
pluginsList.add(maintenancePlugin);
pluginsList.add(automationPlugin);
pluginsList.add(dstHelperPlugin);
pluginsList.add(dataBroadcastPlugin);
pluginStore.add(maintenancePlugin);
pluginStore.add(automationPlugin);
pluginStore.add(dstHelperPlugin);
pluginStore.add(dataBroadcastPlugin);
pluginsList.add(configBuilderPlugin);
pluginStore.add(configBuilderPlugin);
configBuilderPlugin.initialize();
@ -316,23 +300,23 @@ public class MainApp extends DaggerApplication {
// guarantee that the unreachable threshold is at least 30 and of type String
// Added in 1.57 at 21.01.2018
int unreachable_threshold = SP.getInt(R.string.key_pump_unreachable_threshold, 30);
SP.remove(R.string.key_pump_unreachable_threshold);
int unreachable_threshold = sp.getInt(R.string.key_pump_unreachable_threshold, 30);
sp.remove(R.string.key_pump_unreachable_threshold);
if (unreachable_threshold < 30) unreachable_threshold = 30;
SP.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold));
sp.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold));
// 2.5 -> 2.6
if (!SP.contains(R.string.key_units)) {
if (!sp.contains(R.string.key_units)) {
String newUnits = Constants.MGDL;
Profile p = ProfileFunctions.getInstance().getProfile();
Profile p = profileFunction.getProfile();
if (p != null && p.getData() != null && p.getData().has("units")) {
try {
newUnits = p.getData().getString("units");
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
SP.putString(R.string.key_units, newUnits);
sp.putString(R.string.key_units, newUnits);
}
}
@ -357,6 +341,11 @@ public class MainApp extends DaggerApplication {
this.timeDateOrTZChangeReceiver = new TimeDateOrTZChangeReceiver();
this.timeDateOrTZChangeReceiver.registerBroadcasts(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(new NetworkChangeReceiver(), intentFilter);
}
@Deprecated
@ -369,11 +358,6 @@ public class MainApp extends DaggerApplication {
return sResources.getString(id, args);
}
@Deprecated
public static String gq(@PluralsRes int id, int quantity, Object... args) {
return sResources.getQuantityString(id, quantity, args);
}
@Deprecated
public static int gc(@ColorRes int id) {
return ContextCompat.getColor(instance(), id);
@ -397,78 +381,6 @@ public class MainApp extends DaggerApplication {
return firebaseAnalytics;
}
public static ArrayList<PluginBase> getPluginsList() {
return pluginsList;
}
public static ArrayList<PluginBase> getSpecificPluginsList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
if (p.showInList(type))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
if (p.showInList(type))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static boolean isEngineeringModeOrRelease() {
if (!Config.APS)
return true;
return engineeringMode || !devBranch;
}
public static boolean isDev() {
return devBranch;
}
// global Notification has been moved to MainApp because PersistentNotificationPlugin is initialized too late
private void generateEmptyNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
@ -516,16 +428,4 @@ public class MainApp extends DaggerApplication {
keepAliveManager.cancelAlarm(this);
super.onTerminate();
}
@Deprecated
public static int dpToPx(int dp) {
float scale = sResources.getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
@Deprecated
public ResourceHelper getResourceHelper() {
return resourceHelper;
}
}

View file

@ -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))
}

View file

@ -11,7 +11,6 @@ import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.events.EventPreferenceChange
@ -22,6 +21,8 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin
@ -60,6 +61,8 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var pluginStore: PluginStore
@Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var danaRPlugin: DanaRPlugin
@ -112,6 +115,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)
}
@ -174,7 +184,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey)
}
initSummary(preferenceScreen)
for (plugin in MainApp.getPluginsList()) {
for (plugin in pluginStore.plugins) {
plugin.preprocessPreferences(this)
}
}
@ -228,7 +238,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
)
if (listOf(*unitDependent).contains(pref.key)) {
val editTextPref = pref as EditTextPreference
val converted = Profile.toCurrentUnitsString(SafeParse.stringToDouble(editTextPref.text))
val converted = Profile.toCurrentUnitsString(profileFunction, SafeParse.stringToDouble(editTextPref.text))
editTextPref.summary = converted
editTextPref.text = converted
}
@ -245,7 +255,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
pref.dialogMessage = pref.dialogMessage
pref.setSummary(pref.text)
} else {
for (plugin in MainApp.getPluginsList()) {
for (plugin in pluginStore.plugins) {
plugin.updatePreferenceSummary(pref)
}
}

View file

@ -5,19 +5,23 @@ import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import info.nightscout.androidaps.MainApp
import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.utils.LocaleHelper
import info.nightscout.androidaps.utils.PasswordProtection
import javax.inject.Inject
class SingleFragmentActivity : DaggerAppCompatActivity() {
@Inject lateinit var pluginStore: PluginStore
class SingleFragmentActivity : AppCompatActivity() {
private var plugin: PluginBase? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_fragment)
plugin = MainApp.getPluginsList()[intent.getIntExtra("plugin", -1)]
plugin = pluginStore.plugins[intent.getIntExtra("plugin", -1)]
title = plugin?.name
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)

View file

@ -30,6 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
@Inject lateinit var tirCalculator: TirCalculator
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activityMonitor: ActivityMonitor
@Inject lateinit var defaultProfile: DefaultProfile
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@ -61,7 +62,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
val profile = DefaultProfile().profile(age, tdd, weight, profileFunction.getUnits())
val profile = defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
val args = Bundle()
args.putLong("time", DateUtil.now())
args.putInt("mode", ProfileViewerDialog.Mode.CUSTOM_PROFILE.ordinal)

View file

@ -5,31 +5,39 @@ import androidx.collection.LongSparseArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.TimeZone;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.MidnightTime;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
public class Profile {
private static Logger log = StacktraceLoggerWrapper.getLogger(Profile.class);
@Inject public AAPSLogger aapsLogger;
@Inject public ActivePluginProvider activePlugin;
@Inject public ResourceHelper resourceHelper;
@Inject public RxBusWrapper rxBus;
@Inject public FabricPrivacy fabricPrivacy;
private HasAndroidInjector injector;
private JSONObject json;
private String units;
@ -52,8 +60,14 @@ public class Profile {
protected boolean isValid;
protected boolean isValidated;
// Default constructor for tests
protected Profile() {
// Default constructor for DB
public Profile() {
MainApp.instance().injector.androidInjector().inject(this);
}
protected Profile(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
this.injector = injector;
}
@Override
@ -65,24 +79,27 @@ public class Profile {
}
// Constructor from profileStore JSON
public Profile(JSONObject json, String units) {
public Profile(HasAndroidInjector injector, JSONObject json, String units) {
this(injector);
init(json, 100, 0);
if (this.units == null) {
if (units != null)
this.units = units;
else {
FabricPrivacy.getInstance().log("Profile failover failed too");
fabricPrivacy.log("Profile failover failed too");
this.units = Constants.MGDL;
}
}
}
// Constructor from profileStore JSON
public Profile(JSONObject json) {
public Profile(HasAndroidInjector injector, JSONObject json) {
this(injector);
init(json, 100, 0);
}
public Profile(JSONObject json, int percentage, int timeshift) {
public Profile(HasAndroidInjector injector, JSONObject json, int percentage, int timeshift) {
this(injector);
init(json, percentage, timeshift);
}
@ -115,7 +132,7 @@ public class Profile {
targetLow = json.getJSONArray("target_low");
targetHigh = json.getJSONArray("target_high");
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
isValid = false;
isValidated = true;
}
@ -136,7 +153,7 @@ public class Profile {
try {
json.put("units", units);
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return json;
}
@ -181,9 +198,9 @@ public class Profile {
double value = o.getDouble("value") * multiplier;
sparse.put(tas, value);
} catch (Exception e) {
log.error("Unhandled exception", e);
log.error(json.toString());
FabricPrivacy.getInstance().logException(e);
aapsLogger.error("Unhandled exception", e);
aapsLogger.error(json.toString());
fabricPrivacy.logException(e);
}
}
@ -229,38 +246,31 @@ public class Profile {
if (isValid) {
// Check for hours alignment
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePumpPlugin();
if (pump != null && !pump.getPumpDescription().is30minBasalRatesCapable) {
PumpInterface pump = activePlugin.getActivePump();
if (!pump.getPumpDescription().is30minBasalRatesCapable) {
for (int index = 0; index < basal_v.size(); index++) {
long secondsFromMidnight = basal_v.keyAt(index);
if (notify && secondsFromMidnight % 3600 != 0) {
if (Config.APS) {
Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, String.format(MainApp.gs(R.string.basalprofilenotaligned), from), Notification.NORMAL);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, resourceHelper.gs(R.string.basalprofilenotaligned, from), Notification.NORMAL);
rxBus.send(new EventNewNotification(notification));
}
}
}
}
// Check for minimal basal value
if (pump != null) {
PumpDescription description = pump.getPumpDescription();
for (int i = 0; i < basal_v.size(); i++) {
if (basal_v.valueAt(i) < description.basalMinimumRate) {
basal_v.setValueAt(i, description.basalMinimumRate);
if (notify)
sendBelowMinimumNotification(from);
} else if (basal_v.valueAt(i) > description.basalMaximumRate) {
basal_v.setValueAt(i, description.basalMaximumRate);
if (notify)
sendAboveMaximumNotification(from);
}
PumpDescription description = pump.getPumpDescription();
for (int i = 0; i < basal_v.size(); i++) {
if (basal_v.valueAt(i) < description.basalMinimumRate) {
basal_v.setValueAt(i, description.basalMinimumRate);
if (notify)
sendBelowMinimumNotification(from);
} else if (basal_v.valueAt(i) > description.basalMaximumRate) {
basal_v.setValueAt(i, description.basalMaximumRate);
if (notify)
sendAboveMaximumNotification(from);
}
} else {
// if pump not available (at start)
// do not store converted array
basal_v = null;
isValidated = false;
}
}
@ -268,11 +278,11 @@ public class Profile {
}
protected void sendBelowMinimumNotification(String from) {
RxBus.Companion.getINSTANCE().send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
rxBus.send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, resourceHelper.gs(R.string.minimalbasalvaluereplaced, from), Notification.NORMAL)));
}
protected void sendAboveMaximumNotification(String from) {
RxBus.Companion.getINSTANCE().send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
rxBus.send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, resourceHelper.gs(R.string.maximumbasalvaluereplaced, from), Notification.NORMAL)));
}
private void validate(LongSparseArray array) {
@ -326,7 +336,7 @@ public class Profile {
else if (array == basal_v)
multiplier = percentage / 100d;
else
log.error("Unknown array type");
aapsLogger.error("Unknown array type");
return multiplier;
}
@ -344,7 +354,7 @@ public class Profile {
else if (array == targetHigh)
multiplier = 1d;
else
log.error("Unknown array type");
aapsLogger.error("Unknown array type");
return multiplier;
}
@ -407,7 +417,7 @@ public class Profile {
public String getIsfList() {
if (isf_v == null)
isf_v = convertToSparseArray(isf);
return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + MainApp.gs(R.string.profile_per_unit));
return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + resourceHelper.gs(R.string.profile_per_unit));
}
public ProfileValue[] getIsfsMgdl() {
@ -440,7 +450,7 @@ public class Profile {
public String getIcList() {
if (ic_v == null)
ic_v = convertToSparseArray(ic);
return getValuesList(ic_v, null, new DecimalFormat("0.0"), MainApp.gs(R.string.profile_carbs_per_unit));
return getValuesList(ic_v, null, new DecimalFormat("0.0"), resourceHelper.gs(R.string.profile_carbs_per_unit));
}
public ProfileValue[] getIcs() {
@ -474,7 +484,7 @@ public class Profile {
public String getBasalList() {
if (basal_v == null)
basal_v = convertToSparseArray(basal);
return getValuesList(basal_v, null, new DecimalFormat("0.00"), MainApp.gs(R.string.profile_ins_units_per_hour));
return getValuesList(basal_v, null, new DecimalFormat("0.00"), resourceHelper.gs(R.string.profile_ins_units_per_hour));
}
public class ProfileValue {
@ -643,16 +653,21 @@ public class Profile {
else return (valueInMmol > 0 ? "+" : "") + DecimalFormatter.to1Decimal(valueInMmol);
}
public static double toCurrentUnits(double anyBg) {
if (anyBg < 32) return fromMmolToUnits(anyBg, ProfileFunctions.getSystemUnits());
else return fromMgdlToUnits(anyBg, ProfileFunctions.getSystemUnits());
public static double toCurrentUnits(ProfileFunction profileFunction, double anyBg) {
if (anyBg < 32) return fromMmolToUnits(anyBg, profileFunction.getUnits());
else return fromMgdlToUnits(anyBg, profileFunction.getUnits());
}
public static String toCurrentUnitsString(double anyBg) {
public static double toCurrentUnits(String units, double anyBg) {
if (anyBg < 32) return fromMmolToUnits(anyBg, units);
else return fromMgdlToUnits(anyBg, units);
}
public static String toCurrentUnitsString(ProfileFunction profileFunction, double anyBg) {
if (anyBg < 32)
return toUnitsString(anyBg * Constants.MMOLL_TO_MGDL, anyBg, ProfileFunctions.getSystemUnits());
return toUnitsString(anyBg * Constants.MMOLL_TO_MGDL, anyBg, profileFunction.getUnits());
else
return toUnitsString(anyBg, anyBg * Constants.MGDL_TO_MMOLL, ProfileFunctions.getSystemUnits());
return toUnitsString(anyBg, anyBg * Constants.MGDL_TO_MMOLL, profileFunction.getUnits());
}
// targets are stored in mg/dl but profile vary
@ -796,8 +811,8 @@ public class Profile {
o.put("target_high", target_high);
} catch (JSONException e) {
log.error("Unhandled exception" + e);
aapsLogger.error("Unhandled exception" + e);
}
return new Profile(o);
return new Profile(injector, o);
}
}

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.data
import androidx.collection.ArrayMap
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONException
@ -8,9 +9,13 @@ import org.json.JSONObject
import java.util.*
import javax.inject.Inject
class ProfileStore(val data: JSONObject) {
class ProfileStore(val injector: HasAndroidInjector, val data: JSONObject) {
@Inject lateinit var aapsLogger: AAPSLogger
init {
injector.androidInjector().inject(this)
}
private val cachedObjects = ArrayMap<String, Profile>()
private fun getStore(): JSONObject? {
@ -49,7 +54,7 @@ class ProfileStore(val data: JSONObject) {
JsonHelper.safeGetJSONObject(store, profileName, null)?.let { profileObject ->
// take units from profile and if N/A from store
JsonHelper.safeGetStringAllowNull(profileObject, "units", JsonHelper.safeGetString(data, "units"))?.let { units ->
profile = Profile(profileObject, units)
profile = Profile(injector, profileObject, units)
cachedObjects[profileName] = profile
}
}

View file

@ -2,18 +2,19 @@ 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 dagger.android.HasAndroidInjector;
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 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;
@ -47,7 +52,7 @@ public class PumpEnactResult {
}
public PumpEnactResult comment(int comment) {
this.comment = MainApp.gs(comment);
this.comment = resourceHelper.gs(comment);
return this;
}
@ -106,66 +111,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 = "<b>" + MainApp.gs(R.string.success) + "</b>: " + success;
String ret = "<b>" + resourceHelper.gs(R.string.success) + "</b>: " + success;
if (queued) {
ret = MainApp.gs(R.string.waitingforpumpresult);
ret = resourceHelper.gs(R.string.waitingforpumpresult);
} else if (enacted) {
if (bolusDelivered > 0) {
ret += "<br><b>" + MainApp.gs(R.string.enacted) + "</b>: " + enacted;
ret += "<br><b>" + resourceHelper.gs(R.string.enacted) + "</b>: " + enacted;
if (!comment.isEmpty())
ret += "<br><b>" + MainApp.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + MainApp.gs(R.string.smb_shortname) + "</b>: " + bolusDelivered + " " + MainApp.gs(R.string.insulin_unit_shortname);
ret += "<br><b>" + resourceHelper.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + resourceHelper.gs(R.string.smb_shortname) + "</b>: " + bolusDelivered + " " + resourceHelper.gs(R.string.insulin_unit_shortname);
} else if (isTempCancel) {
ret += "<br><b>" + MainApp.gs(R.string.enacted) + "</b>: " + enacted;
ret += "<br><b>" + MainApp.gs(R.string.comment) + "</b>: " + comment +
"<br>" + MainApp.gs(R.string.canceltemp);
ret += "<br><b>" + resourceHelper.gs(R.string.enacted) + "</b>: " + enacted;
ret += "<br><b>" + resourceHelper.gs(R.string.comment) + "</b>: " + comment +
"<br>" + resourceHelper.gs(R.string.canceltemp);
} else if (isPercent && percent != -1) {
ret += "<br><b>" + MainApp.gs(R.string.enacted) + "</b>: " + enacted;
ret += "<br><b>" + resourceHelper.gs(R.string.enacted) + "</b>: " + enacted;
if (!comment.isEmpty())
ret += "<br><b>" + MainApp.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + MainApp.gs(R.string.duration) + "</b>: " + duration + " min";
ret += "<br><b>" + MainApp.gs(R.string.percent) + "</b>: " + percent + "%";
ret += "<br><b>" + resourceHelper.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + resourceHelper.gs(R.string.duration) + "</b>: " + duration + " min";
ret += "<br><b>" + resourceHelper.gs(R.string.percent) + "</b>: " + percent + "%";
} else if (absolute != -1) {
ret += "<br><b>" + MainApp.gs(R.string.enacted) + "</b>: " + enacted;
ret += "<br><b>" + resourceHelper.gs(R.string.enacted) + "</b>: " + enacted;
if (!comment.isEmpty())
ret += "<br><b>" + MainApp.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + MainApp.gs(R.string.duration) + "</b>: " + duration + " min";
ret += "<br><b>" + MainApp.gs(R.string.absolute) + "</b>: " + DecimalFormatter.to2Decimal(absolute) + " U/h";
ret += "<br><b>" + resourceHelper.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + resourceHelper.gs(R.string.duration) + "</b>: " + duration + " min";
ret += "<br><b>" + resourceHelper.gs(R.string.absolute) + "</b>: " + DecimalFormatter.to2Decimal(absolute) + " U/h";
}
} else {
ret += "<br><b>" + MainApp.gs(R.string.comment) + "</b>: " + comment;
ret += "<br><b>" + resourceHelper.gs(R.string.comment) + "</b>: " + comment;
}
return ret;
}
@ -188,12 +193,8 @@ public class PumpEnactResult {
result.put("duration", duration);
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return result;
}
public static PumpEnactResult error(String message) {
return new PumpEnactResult().enacted(false).success(false).comment(message);
}
}

View file

@ -1,13 +1,17 @@
package info.nightscout.androidaps.data.defaultProfile
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.utils.Round
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DefaultProfile @Inject constructor(val injector: HasAndroidInjector) {
class DefaultProfile {
var oneToFive: TreeMap<Double, Array<Double>> = TreeMap()
var sixToEleven: TreeMap<Double, Array<Double>> = TreeMap()
var twelveToSeventeen: TreeMap<Double, Array<Double>> = TreeMap()
@ -18,24 +22,24 @@ class DefaultProfile {
if (age >= 1 && age < 6) {
val _tdd = if (tdd == 0.0) 0.6 * weight else tdd
closest(oneToFive, _tdd * 0.3)?.let { array -> profile.put("basal", arrayToJson(array)) }
val ic = Round.roundTo(250.0 / _tdd, 1.0)
profile.put("carbratio", singleValueArray(ic, arrayOf( 0.0, -4.0, -1.0, -2.0, -4.0, 0.0, -4.0)))
val ic = Round.roundTo(250.0 / _tdd, 1.0)
profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -4.0, -1.0, -2.0, -4.0, 0.0, -4.0)))
val isf = Round.roundTo(200.0 / _tdd, 0.1)
profile.put("sens", singleValueArray(isf, arrayOf( 0.0, -2.0, -0.0, -0.0, -2.0, 0.0, -2.0)))
profile.put("sens", singleValueArray(isf, arrayOf(0.0, -2.0, -0.0, -0.0, -2.0, 0.0, -2.0)))
} else if (age >= 6 && age < 12) {
val _tdd = if (tdd == 0.0) 0.8 * weight else tdd
closest(sixToEleven, _tdd * 0.4)?.let { array -> profile.put("basal", arrayToJson(array)) }
val ic = Round.roundTo(375.0 / _tdd, 1.0)
profile.put("carbratio", singleValueArray(ic, arrayOf( 0.0, -3.0, 0.0, -1.0, -3.0, 0.0, -2.0)))
val ic = Round.roundTo(375.0 / _tdd, 1.0)
profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -3.0, 0.0, -1.0, -3.0, 0.0, -2.0)))
val isf = Round.roundTo(170.0 / _tdd, 0.1)
profile.put("sens", singleValueArray(isf, arrayOf( 0.0, -1.0, -0.0, -0.0, -1.0, 0.0, -1.0)))
profile.put("sens", singleValueArray(isf, arrayOf(0.0, -1.0, -0.0, -0.0, -1.0, 0.0, -1.0)))
} else if (age >= 12 && age < 17) {
val _tdd = if (tdd == 0.0) 1.0 * weight else tdd
closest(twelveToSeventeen, _tdd * 0.5)?.let { array -> profile.put("basal", arrayToJson(array)) }
val ic = Round.roundTo(500.0 / _tdd, 1.0)
profile.put("carbratio", singleValueArray(ic, arrayOf( 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, -1.0)))
val ic = Round.roundTo(500.0 / _tdd, 1.0)
profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -1.0, 0.0, 0.0, -1.0, 0.0, -1.0)))
val isf = Round.roundTo(100.0 / _tdd, 0.1)
profile.put("sens", singleValueArray(isf, arrayOf( 0.2, 0.0, 0.2, 0.2, 0.0, 0.2, 0.2)))
profile.put("sens", singleValueArray(isf, arrayOf(0.2, 0.0, 0.2, 0.2, 0.0, 0.2, 0.2)))
} else if (age >= 18) {
}
@ -45,7 +49,7 @@ class DefaultProfile {
profile.put("timezone", TimeZone.getDefault().getID())
profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units))))
profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units))))
return Profile(profile, units)
return Profile(injector, profile, units)
}
init {

View file

@ -11,6 +11,7 @@ import java.util.Objects;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -28,10 +29,10 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)
public class BgReading implements DataPointWithLabelInterface {
@Inject AAPSLogger aapsLogger;
@Inject DefaultValueHelper defaultValueHelper;
@Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper;
@Inject public AAPSLogger aapsLogger;
@Inject public DefaultValueHelper defaultValueHelper;
@Inject public ProfileFunction profileFunction;
@Inject public ResourceHelper resourceHelper;
@DatabaseField(id = true)
public long date;
@ -58,7 +59,11 @@ public class BgReading implements DataPointWithLabelInterface {
public boolean isZTPrediction = false; // true when drawing predictions as bg points (ZT)
public BgReading() {
MainApp.instance().androidInjector().inject(this); // TODO it will be removed by new database
MainApp.instance().androidInjector().inject(this);
}
public BgReading(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
}
public BgReading(NSSgv sgv) {

View file

@ -9,7 +9,6 @@ import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
@ -26,7 +25,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
@ -168,7 +167,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@Override
public double getY() {
String units = ProfileFunctions.getSystemUnits();
String units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits();
if (eventType.equals(MBG)) {
double mbg = 0d;
try {

View file

@ -18,7 +18,6 @@ import com.j256.ormlite.table.TableUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
@ -32,8 +31,6 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.data.NonOverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
@ -52,9 +49,9 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset;
@ -519,7 +516,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// ------------- DbRequests handling -------------------
public void create(DbRequest dbr) throws SQLException {
getDaoDbRequest().create(dbr);
getDaoDbRequest().create(dbr);
}
public int delete(DbRequest dbr) {
@ -800,31 +797,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return historyList;
}
public void updateDanaRHistoryRecordId(JSONObject trJson) {
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
Where where = queryBuilder.where();
where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
List<DanaRHistoryRecord> list = getDaoDanaRHistory().query(preparedQuery);
if (list.size() == 0) {
// Record does not exists. Ignore
} else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (L.isEnabled(L.DATABASE))
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record);
} else {
// already set
}
}
} catch (SQLException | JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
// ------------ TemporaryBasal handling ---------------
//return true if new record was created
@ -1738,7 +1710,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
try {
ProfileSwitch profileSwitch = new ProfileSwitch();
ProfileSwitch profileSwitch = new ProfileSwitch(MainApp.instance().injector);
profileSwitch.date = trJson.getLong("mills");
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
@ -1753,30 +1725,24 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson");
else {
ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
if (profileInterface != null) {
ProfileStore store = profileInterface.getProfile();
if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
if (L.isEnabled(L.DATABASE))
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
} else {
if (L.isEnabled(L.DATABASE))
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
ProfileInterface profileInterface = PluginStore.Companion.getInstance().getActiveProfileInterface();
ProfileStore store = profileInterface.getProfile();
if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
if (L.isEnabled(L.DATABASE))
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
} else {
if (L.isEnabled(L.DATABASE))
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("No active profile interface. Ignoring: " + trJson.toString());
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
}

View file

@ -11,7 +11,6 @@ import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
@ -23,7 +22,7 @@ import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
@ -220,7 +219,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
public IobTotal iobCalc(long time) {
IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin();
double realDuration = getDurationToTime(time);
@ -252,7 +251,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
public IobTotal iobCalc(long time, Profile profile, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) {
IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin();
double realDuration = getDurationToTime(time);
double netBasalAmount = 0d;

View file

@ -9,19 +9,20 @@ import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
@ -31,10 +32,10 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;
@ -68,6 +69,22 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private Profile profile = null;
HasAndroidInjector injector;
@Inject public TreatmentsPlugin treatmentsPlugin;
@Inject public AAPSLogger aapsLogger;
@Inject public RxBusWrapper rxBus;
@Inject public ResourceHelper resourceHelper;
public ProfileSwitch() {
this.injector = MainApp.instance().injector;
injector.androidInjector().inject(this);
}
public ProfileSwitch(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
this.injector = injector;
}
public ProfileSwitch date(long date) {
this.date = date;
return this;
@ -97,10 +114,10 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
public Profile getProfileObject() {
if (profile == null)
try {
profile = new Profile(new JSONObject(profileJson), percentage, timeshift);
profile = new Profile(injector, new JSONObject(profileJson), percentage, timeshift);
} catch (Exception e) {
log.error("Unhandled exception", e);
log.error("Unhandled exception", profileJson);
aapsLogger.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception: " + profileJson);
}
return profile;
}
@ -218,7 +235,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@Override
public boolean isValid() {
boolean isValid = getProfileObject() != null && getProfileObject().isValid(DateUtil.dateAndTimeString(date));
ProfileSwitch active = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now());
ProfileSwitch active = treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now());
long activeProfileSwitchDate = active != null ? active.date : -1L;
if (!isValid && date == activeProfileSwitchDate)
createNotificationInvalidProfile(DateUtil.dateAndTimeString(date));
@ -226,23 +243,23 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
}
private void createNotificationInvalidProfile(String detail) {
Notification notification = new Notification(Notification.ZERO_VALUE_IN_PROFILE, String.format(MainApp.gs(R.string.zerovalueinprofile), detail), Notification.LOW, 5);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
Notification notification = new Notification(Notification.ZERO_VALUE_IN_PROFILE, resourceHelper.gs(R.string.zerovalueinprofile, detail), Notification.LOW, 5);
rxBus.send(new EventNewNotification(notification));
}
public static boolean isEvent5minBack(List<ProfileSwitch> list, long time, boolean zeroDurationOnly) {
public static boolean isEvent5minBack(AAPSLogger aapsLogger, List<ProfileSwitch> list, long time, boolean zeroDurationOnly) {
for (int i = 0; i < list.size(); i++) {
ProfileSwitch event = list.get(i);
if (event.date <= time && event.date > (time - T.mins(5).msecs())) {
if (zeroDurationOnly) {
if (event.durationInMinutes == 0) {
if (L.isEnabled(L.DATABASE))
log.debug("Found ProfileSwitch event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
aapsLogger.debug("Found ProfileSwitch event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
return true;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("Found ProfileSwitch event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
aapsLogger.debug("Found ProfileSwitch event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
return true;
}
}

View file

@ -4,7 +4,6 @@ import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
@ -17,7 +16,7 @@ import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.utils.DateUtil;
@ -96,7 +95,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = ProfileFunctions.getInstance().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
double basal = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source;
@ -237,7 +236,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin();
int realDuration = getDurationToTime(time);
double netBasalAmount = 0d;
@ -292,7 +291,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin();
double realDuration = getDurationToTime(time);
double netBasalAmount = 0d;
@ -405,7 +404,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
public String toStringFull() {
if (isFakeExtended) {
Profile profile = ProfileFunctions.getInstance().getProfile();
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null)
return "null";
Double currentBasalRate = profile.getBasal();
@ -429,7 +428,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
double rate;
if (isFakeExtended) {
Profile profile = ProfileFunctions.getInstance().getProfile();
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null)
return "null";
double currentBasalRate = profile.getBasal();
@ -439,7 +438,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
Profile profile = ProfileFunctions.getInstance().getProfile();
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile != null) {
double basal = profile.getBasal();
if (basal != 0) {
@ -454,7 +453,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
private String getCalcuatedPercentageIfNeeded() {
Profile profile = ProfileFunctions.getInstance().getProfile();
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null)
return "null";
@ -480,7 +479,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public String toStringVeryShort() {
Profile profile = ProfileFunctions.getInstance().getProfile();
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null)
return "null";

View file

@ -42,6 +42,7 @@ abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesRileyLinkStatusActivity(): RileyLinkStatusActivity
@ContributesAndroidInjector abstract fun contributesRileyLinkBLEScanActivity(): RileyLinkBLEScanActivity
@ContributesAndroidInjector abstract fun contributesSetupWizardActivity(): SetupWizardActivity
@ContributesAndroidInjector abstract fun contributesSingleFragmentActivity(): SingleFragmentActivity
@ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity
@ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity
@ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity

View file

@ -5,16 +5,26 @@ import dagger.Component
import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.ProfileSwitch
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.*
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.plugins.general.automation.triggers.*
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
import info.nightscout.androidaps.plugins.treatments.Treatment
@ -38,6 +48,12 @@ import javax.inject.Singleton
interface AppComponent : AndroidInjector<MainApp> {
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)
@ -57,12 +73,17 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectCommandTempBasalPercent(commandTempBasalPercent: CommandTempBasalPercent)
fun injectCommandSetUserSettings(commandSetUserSettings: CommandSetUserSettings)
fun injectObjective(objective: Objective)
fun injectObjective0(objective0: Objective0)
fun injectObjective1(objective1: Objective1)
fun injectObjective2(objective2: Objective2)
fun injectObjective3(objective3: Objective3)
fun injectObjective3(objective4: Objective4)
fun injectObjective5(objective5: Objective5)
fun injectObjective6(objective6: Objective6)
fun injectObjective6(objective7: Objective7)
fun injectObjective6(objective8: Objective8)
fun injectObjective6(objective9: Objective9)
fun injectAutomationEvent(automationEvent: AutomationEvent)
@ -124,6 +145,7 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectTreatment(treatment: Treatment)
fun injectBgReading(bgReading: BgReading)
fun injectProfileSwitch(profileSwitch: ProfileSwitch)
fun injectNotification(notificationWithAction: NotificationWithAction)
@ -131,6 +153,11 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectBolusWizard(bolusWizard: BolusWizard)
fun injectQuickWizardEntry(quickWizardEntry: QuickWizardEntry)
fun injectAuthRequest(authRequest: AuthRequest)
fun injectProfile(profile: Profile)
fun injectGlucoseStatus(glucoseStatus: GlucoseStatus)
@Component.Builder
interface Builder {

View file

@ -7,17 +7,24 @@ 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.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.ProfileSwitch
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.PluginStore
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
@ -26,7 +33,9 @@ import info.nightscout.androidaps.plugins.general.automation.actions.*
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.plugins.general.automation.triggers.*
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
import info.nightscout.androidaps.plugins.treatments.Treatment
@ -51,8 +60,8 @@ open class AppModule {
@Provides
@Singleton
fun provideProfileFunction(sp: SP): ProfileFunction {
return ProfileFunctionImplementation(sp)
fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider): ProfileFunction {
return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin)
}
@Provides
@ -78,13 +87,25 @@ open class AppModule {
@ContributesAndroidInjector fun profileStoreInjector(): ProfileStore
@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
@ -100,12 +121,17 @@ open class AppModule {
@ContributesAndroidInjector fun commandTempBasalPercentInjector(): CommandTempBasalPercent
@ContributesAndroidInjector fun commandSetUserSettingsInjector(): CommandSetUserSettings
@ContributesAndroidInjector fun objectiveInjector(): Objective
@ContributesAndroidInjector fun objective0Injector(): Objective0
@ContributesAndroidInjector fun objective1Injector(): Objective1
@ContributesAndroidInjector fun objective2Injector(): Objective2
@ContributesAndroidInjector fun objective3Injector(): Objective3
@ContributesAndroidInjector fun objective4Injector(): Objective4
@ContributesAndroidInjector fun objective5Injector(): Objective5
@ContributesAndroidInjector fun objective6Injector(): Objective6
@ContributesAndroidInjector fun objective7Injector(): Objective7
@ContributesAndroidInjector fun objective8Injector(): Objective8
@ContributesAndroidInjector fun objective9Injector(): Objective9
@ContributesAndroidInjector fun automationEventInjector(): AutomationEvent
@ -120,6 +146,7 @@ open class AppModule {
@ContributesAndroidInjector fun triggerIobInjector(): TriggerIob
@ContributesAndroidInjector fun triggerLocationInjector(): TriggerLocation
@ContributesAndroidInjector fun triggerProfilePercentInjector(): TriggerProfilePercent
@ContributesAndroidInjector
fun triggerPumpLastConnectionInjector(): TriggerPumpLastConnection
@ -136,6 +163,7 @@ open class AppModule {
@ContributesAndroidInjector fun actionLoopSuspendInjector(): ActionLoopSuspend
@ContributesAndroidInjector fun actionNotificationInjector(): ActionNotification
@ContributesAndroidInjector fun actionProfileSwitchInjector(): ActionProfileSwitch
@ContributesAndroidInjector
fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent
@ -171,6 +199,7 @@ open class AppModule {
@ContributesAndroidInjector fun bgReadingInjector(): BgReading
@ContributesAndroidInjector fun treatmentInjector(): Treatment
@ContributesAndroidInjector fun profileSwitchInjector(): ProfileSwitch
@ContributesAndroidInjector fun notificationWithActionInjector(): NotificationWithAction
@ -178,11 +207,16 @@ open class AppModule {
@ContributesAndroidInjector fun loggerBolusWizard(): BolusWizard
@ContributesAndroidInjector fun loggerQuickWizardEntry(): QuickWizardEntry
@ContributesAndroidInjector fun authRequestInjector(): AuthRequest
@ContributesAndroidInjector fun profileInjector(): Profile
@ContributesAndroidInjector fun glucoseStatusInjector(): GlucoseStatus
@Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds
fun bindActivePluginProvider(configBuilderPlugin: ConfigBuilderPlugin): ActivePluginProvider
fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider
@Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider

View file

@ -30,6 +30,7 @@ import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicato
import info.nightscout.androidaps.plugins.general.smsCommunicator.fragments.SmsCommunicatorLogFragment
import info.nightscout.androidaps.plugins.general.smsCommunicator.fragments.SmsCommunicatorOtpFragment
import info.nightscout.androidaps.plugins.general.tidepool.TidepoolFragment
import info.nightscout.androidaps.plugins.insulin.InsulinFragment
import info.nightscout.androidaps.plugins.profile.local.LocalProfileFragment
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import info.nightscout.androidaps.plugins.pump.combo.ComboFragment
@ -41,7 +42,9 @@ import info.nightscout.androidaps.plugins.source.BGSourceFragment
import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment
@Module
@Suppress("unused")
@ -54,11 +57,13 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment
@ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment
@ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment
@ContributesAndroidInjector
abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment
@ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment
@ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment
@ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment
@ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment
@ContributesAndroidInjector abstract fun contributesObjectivesFragment(): ObjectivesFragment
@ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment
@ -77,14 +82,11 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesTidepoolFragment(): TidepoolFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment
@ContributesAndroidInjector
abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment
@ContributesAndroidInjector
abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment
@ContributesAndroidInjector
abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsTempTargetFragment(): TreatmentsTempTargetFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsExtendedBolusesFragment(): TreatmentsExtendedBolusesFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment
@ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment
@ -95,6 +97,7 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesEditActionDialog(): EditActionDialog
@ContributesAndroidInjector abstract fun contributesEditEventDialog(): EditEventDialog
@ContributesAndroidInjector abstract fun contributesEditTriggerDialog(): EditTriggerDialog
@ContributesAndroidInjector
abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog

View file

@ -2,11 +2,15 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver
import info.nightscout.androidaps.receivers.KeepAliveReceiver
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver
@Module
@Suppress("unused")
abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
}

View file

@ -4,6 +4,8 @@ import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService
import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService
import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService
import info.nightscout.androidaps.plugins.pump.danaR.services.AbstractDanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService
import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService
@ -16,6 +18,7 @@ import info.nightscout.androidaps.services.LocationService
@Suppress("unused")
abstract class ServicesModule {
@ContributesAndroidInjector abstract fun contributesAbstractDanaRExecutionService(): AbstractDanaRExecutionService
@ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService
@ContributesAndroidInjector abstract fun contributesDataService(): DataService
@ContributesAndroidInjector abstract fun contributesDummyService(): DummyService
@ -25,4 +28,5 @@ abstract class ServicesModule {
@ContributesAndroidInjector abstract fun contributesDanaRv2ExecutionService(): DanaRv2ExecutionService
@ContributesAndroidInjector abstract fun contributesDanaRExecutionService(): DanaRExecutionService
@ContributesAndroidInjector abstract fun contributesDanaRKoreanExecutionService(): DanaRKoreanExecutionService
@ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService
}

View file

@ -37,6 +37,7 @@ class BolusProgressDialog : DaggerDialogFragment() {
companion object {
@JvmField
var bolusEnded = false
@JvmField
var stopPressed = false
}
@ -67,6 +68,9 @@ class BolusProgressDialog : DaggerDialogFragment() {
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
savedInstanceState?.let {
amount = it.getDouble("amount")
}
overview_bolusprogress_title.text = resourceHelper.gs(R.string.overview_bolusprogress_goingtodeliver, amount)
overview_bolusprogress_stop.setOnClickListener {
aapsLogger.debug(LTag.UI, "Stop bolus delivery button pressed")
@ -145,6 +149,7 @@ class BolusProgressDialog : DaggerDialogFragment() {
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("state", state)
outState.putDouble("amount", amount)
}
private fun scheduleDismiss() {

View file

@ -5,6 +5,7 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.common.base.Joiner
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
@ -22,6 +23,7 @@ import javax.inject.Inject
class CalibrationDialog : DialogFragmentWithDate() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@ -40,7 +42,7 @@ class CalibrationDialog : DialogFragmentWithDate() {
super.onViewCreated(view, savedInstanceState)
val units = profileFunction.getUnits()
val bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData()?.glucose
val bg = Profile.fromMgdlToUnits(GlucoseStatus(injector).glucoseStatusData?.glucose
?: 0.0, units)
if (units == Constants.MMOL)
overview_calibration_bg.setParams(savedInstanceState?.getDouble("overview_calibration_bg")
@ -56,7 +58,7 @@ class CalibrationDialog : DialogFragmentWithDate() {
val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl)
val actions: LinkedList<String?> = LinkedList()
val bg = overview_calibration_bg.value
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(bg) + " " + unitLabel)
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel)
if (bg > 0) {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {

View file

@ -38,7 +38,8 @@ class CarbsDialog : DialogFragmentWithDate() {
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin;
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Inject lateinit var carbsGenerator: CarbsGenerator
companion object {
private const val FAV1_DEFAULT = 5
@ -227,10 +228,10 @@ class CarbsDialog : DialogFragmentWithDate() {
if (carbsAfterConstraints > 0) {
if (duration == 0) {
aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time")
CarbsGenerator.createCarb(carbsAfterConstraints, time, CareportalEvent.CARBCORRECTION, notes)
carbsGenerator.createCarb(carbsAfterConstraints, time, CareportalEvent.CARBCORRECTION, notes)
} else {
aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration")
CarbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes)
carbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes)
NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset))
}
}

View file

@ -8,6 +8,7 @@ import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import com.google.common.base.Joiner
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
@ -31,6 +32,7 @@ import java.util.*
import javax.inject.Inject
class CareDialog : DialogFragmentWithDate() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@ -57,6 +59,8 @@ class CareDialog : DialogFragmentWithDate() {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("actions_care_bg", actions_care_bg.value)
savedInstanceState.putDouble("actions_care_duration", actions_care_duration.value)
savedInstanceState.putInt("event", event)
savedInstanceState.putInt("options", options.ordinal)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
@ -68,6 +72,11 @@ class CareDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
savedInstanceState?.let {
event = savedInstanceState.getInt("event", R.string.error)
options = EventType.values()[savedInstanceState.getInt("options", 0)]
}
actions_care_icon.setImageResource(when (options) {
EventType.BGCHECK -> R.drawable.icon_cp_bgcheck
EventType.SENSOR_INSERT -> R.drawable.icon_cp_cgm_insert
@ -102,7 +111,7 @@ class CareDialog : DialogFragmentWithDate() {
}
}
val bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData()?.glucose
val bg = Profile.fromMgdlToUnits(GlucoseStatus(injector).getGlucoseStatusData()?.glucose
?: 0.0, profileFunction.getUnits())
val bgTextWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
@ -141,7 +150,7 @@ class CareDialog : DialogFragmentWithDate() {
else -> "Manual"
}
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type))
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(actions_care_bg.value) + " " + resourceHelper.gs(unitResId))
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, actions_care_bg.value) + " " + resourceHelper.gs(unitResId))
json.put("glucose", actions_care_bg.value)
json.put("glucoseType", type)
}

View file

@ -58,11 +58,11 @@ class FillDialog : DialogFragmentWithDate() {
val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
val bolusStep = activePlugin.activePump.pumpDescription.bolusStep
fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulin_amount")
?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), true, ok)
?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), true, ok)
val amount1 = sp.getDouble("fill_button1", 0.3)
if (amount1 > 0) {
fill_preset_button1.visibility = View.VISIBLE
fill_preset_button1.text = DecimalFormatter.toPumpSupportedBolus(amount1) // + "U");
fill_preset_button1.text = DecimalFormatter.toPumpSupportedBolus(amount1, activePlugin.activePump) // + "U");
fill_preset_button1.setOnClickListener { fill_insulinamount.value = amount1 }
} else {
fill_preset_button1.visibility = View.GONE
@ -70,7 +70,7 @@ class FillDialog : DialogFragmentWithDate() {
val amount2 = sp.getDouble("fill_button2", 0.0)
if (amount2 > 0) {
fill_preset_button2.visibility = View.VISIBLE
fill_preset_button2.text = DecimalFormatter.toPumpSupportedBolus(amount2) // + "U");
fill_preset_button2.text = DecimalFormatter.toPumpSupportedBolus(amount2, activePlugin.activePump) // + "U");
fill_preset_button2.setOnClickListener { fill_insulinamount.value = amount2 }
} else {
fill_preset_button2.visibility = View.GONE
@ -78,7 +78,7 @@ class FillDialog : DialogFragmentWithDate() {
val amount3 = sp.getDouble("fill_button3", 0.0)
if (amount3 > 0) {
fill_preset_button3.visibility = View.VISIBLE
fill_preset_button3.text = DecimalFormatter.toPumpSupportedBolus(amount3) // + "U");
fill_preset_button3.text = DecimalFormatter.toPumpSupportedBolus(amount3, activePlugin.activePump) // + "U");
fill_preset_button3.setOnClickListener { fill_insulinamount.value = amount3 }
} else {
fill_preset_button3.visibility = View.GONE
@ -94,7 +94,7 @@ class FillDialog : DialogFragmentWithDate() {
if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.fillwarning))
actions.add("")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.colorInsulinButton) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.colorInsulinButton) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
if (abs(insulinAfterConstraints - insulin) > 0.01)
actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints))
}

View file

@ -91,21 +91,21 @@ class InsulinDialog : DialogFragmentWithDate() {
overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time")
?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher)
overview_insulin_amount.setParams(savedInstanceState?.getDouble("overview_insulin_amount")
?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher)
overview_insulin_plus05.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString()
overview_insulin_plus05.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString(activePlugin.activePump)
overview_insulin_plus05.setOnClickListener {
overview_insulin_amount.value = max(0.0, overview_insulin_amount.value
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT))
validateInputs()
}
overview_insulin_plus10.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT).toSignedString()
overview_insulin_plus10.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT).toSignedString(activePlugin.activePump)
overview_insulin_plus10.setOnClickListener {
overview_insulin_amount.value = max(0.0, overview_insulin_amount.value
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT))
validateInputs()
}
overview_insulin_plus20.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString()
overview_insulin_plus20.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString(activePlugin.activePump)
overview_insulin_plus20.setOnClickListener {
overview_insulin_amount.value = max(0.0, overview_insulin_amount.value
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT))
@ -119,8 +119,7 @@ class InsulinDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription
?: return false
val pumpDescription = activePlugin.activePump.pumpDescription
val insulin = SafeParse.stringToDouble(overview_insulin_amount.text)
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
val actions: LinkedList<String?> = LinkedList()
@ -130,7 +129,7 @@ class InsulinDialog : DialogFragmentWithDate() {
val eatingSoonChecked = overview_insulin_start_eating_soon_tt.isChecked
if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
if (recordOnlyChecked)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.bolusrecordedonly) + "</font>")
if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints))

View file

@ -8,7 +8,7 @@ import android.widget.ArrayAdapter
import com.google.common.base.Joiner
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
@ -26,7 +26,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var activePlugin: ActivePluginProvider
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
@ -53,7 +53,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
// profile
context?.let { context ->
val profileStore = configBuilderPlugin.activeProfileInterface.profile
val profileStore = activePlugin.activeProfileInterface.profile
?: return
val profileList = profileStore.getProfileList()
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
@ -79,13 +79,13 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val profileStore = configBuilderPlugin.activeProfileInterface.profile
val profileStore = activePlugin.activeProfileInterface.profile
?: return false
val actions: LinkedList<String> = LinkedList()
val duration = overview_profileswitch_duration.value
val duration = overview_profileswitch_duration.value.toInt()
if (duration > 0)
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_hours, duration))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration))
val profile = overview_profileswitch_profile.selectedItem.toString()
actions.add(resourceHelper.gs(R.string.profile) + ": " + profile)
val percent = overview_profileswitch_percentage.value.toInt()
@ -103,7 +103,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
aapsLogger.debug("USER ENTRY: PROFILE SWITCH $profile percent: $percent timeshift: $timeShift duration: $duration")
treatmentsPlugin.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime)
treatmentsPlugin.doProfileSwitch(profileStore, profile, duration, percent, timeShift, eventTime)
})
}
return true

View file

@ -6,6 +6,7 @@ import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import dagger.android.HasAndroidInjector
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
@ -19,6 +20,7 @@ import org.json.JSONObject
import javax.inject.Inject
class ProfileViewerDialog : DaggerDialogFragment() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@ -71,7 +73,7 @@ class ProfileViewerDialog : DaggerDialogFragment() {
}
Mode.CUSTOM_PROFILE -> {
profile = Profile(JSONObject(customProfileJson), customProfileUnits)
profile = Profile(injector, JSONObject(customProfileJson), customProfileUnits)
profileName = customProfileName
date = ""
profileview_datelayout.visibility = View.GONE

View file

@ -53,7 +53,7 @@ class TempBasalDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return
val pumpDescription = activePlugin.activePump.pumpDescription
val profile = profileFunction.getProfile() ?: return
val maxTempPercent = pumpDescription.maxTempPercent.toDouble()

View file

@ -120,11 +120,11 @@ class TempTargetDialog : DialogFragmentWithDate() {
val reason = overview_temptarget_reason.selectedItem.toString()
val unitResId = if (profileFunction.getUnits() == 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(resourceHelper.gs(R.string.reason) + ": " + reason)
actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + resourceHelper.gs(unitResId))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_hours, duration))
actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration))
} else {
actions.add(resourceHelper.gs(R.string.stoptemptarget))
}
@ -134,7 +134,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
aapsLogger.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)
@ -144,14 +144,14 @@ class TempTargetDialog : DialogFragmentWithDate() {
} else {
val tempTarget = TempTarget()
.date(eventTime)
.duration(duration.toInt())
.duration(duration)
.reason(reason)
.source(Source.USER)
.low(Profile.toMgdl(target, profileFunction.getUnits()))
.high(Profile.toMgdl(target, profileFunction.getUnits()))
treatmentsPlugin.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

View file

@ -77,16 +77,15 @@ class TreatmentDialog : DialogFragmentWithDate() {
val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble()
val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return
val pumpDescription = activePlugin.activePump.pumpDescription
overview_treatment_carbs.setParams(savedInstanceState?.getDouble("overview_treatment_carbs")
?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher)
overview_treatment_insulin.setParams(savedInstanceState?.getDouble("overview_treatment_insulin")
?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher)
}
override fun submit(): Boolean {
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription
?: return false
val pumpDescription = activePlugin.activePump.pumpDescription
val insulin = SafeParse.stringToDouble(overview_treatment_insulin.text)
val carbs = SafeParse.stringToInt(overview_treatment_carbs.text)
val recordOnlyChecked = overview_treatment_record_only.isChecked
@ -95,7 +94,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
if (recordOnlyChecked)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.bolusrecordedonly) + "</font>")
if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints))

View file

@ -18,11 +18,11 @@ import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.logging.AAPSLogger
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
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
@ -55,7 +55,7 @@ class WizardDialog : DaggerDialogFragment() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
private var wizard: BolusWizard? = null
@ -109,9 +109,9 @@ class WizardDialog : DaggerDialogFragment() {
?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher)
treatments_wizard_carbs_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carbs_input")
?: 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false, ok, textWatcher)
val bolusStep = configBuilderPlugin.activePump.pumpDescription.bolusStep
val bolusStep = activePlugin.activePump.pumpDescription.bolusStep
treatments_wizard_correction_input.setParams(savedInstanceState?.getDouble("treatments_wizard_correction_input")
?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher)
treatments_wizard_carb_time_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carb_time_input")
?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher)
initDialog()
@ -212,7 +212,7 @@ class WizardDialog : DaggerDialogFragment() {
private fun initDialog() {
val profile = profileFunction.getProfile()
val profileStore = configBuilderPlugin.activeProfileInterface.profile
val profileStore = activePlugin.activeProfileInterface.profile
if (profile == null || profileStore == null) {
ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofile))
@ -260,7 +260,7 @@ class WizardDialog : DaggerDialogFragment() {
}
private fun calculateInsulin() {
val profileStore = configBuilderPlugin.activeProfileInterface.profile
val profileStore = activePlugin.activeProfileInterface.profile
if (treatments_wizard_profile.selectedItem == null || profileStore == null)
return // not initialized yet
var profileName = treatments_wizard_profile.selectedItem.toString()

View file

@ -23,16 +23,15 @@ import java.util.Date;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
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.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
@ -42,6 +41,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.buildHelper.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.android.schedulers.AndroidSchedulers;
@ -55,7 +55,8 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
@Inject ProfileFunction profileFunction;
@Inject DefaultValueHelper defaultValueHelper;
@Inject IobCobStaticCalculatorPlugin iobCobStaticCalculatorPlugin;
@Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject ActivePluginProvider activePlugin;
@Inject BuildHelper buildHelper;
private CompositeDisposable disposable = new CompositeDisposable();
@ -226,7 +227,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null)
return;
final PumpInterface pump = configBuilderPlugin.getActivePump();
final PumpInterface pump = activePlugin.getActivePump();
final Profile profile = profileFunction.getProfile();
if (profile == null) {
@ -441,7 +442,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
item.setChecked(showActSec);
if (MainApp.devBranch) {
if (buildHelper.isDev()) {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
if (titleMaxChars < title.length()) titleMaxChars = title.length();

View file

@ -1,9 +1,9 @@
package info.nightscout.androidaps.historyBrowser
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
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.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
@ -21,13 +21,13 @@ class IobCobStaticCalculatorPlugin @Inject constructor(
sp: SP,
resourceHelper: ResourceHelper,
profileFunction: ProfileFunction,
configBuilderPlugin: ConfigBuilderPlugin,
activePlugin: ActivePluginProvider,
treatmentsPlugin: TreatmentsPlugin,
sensitivityOref1Plugin: SensitivityOref1Plugin,
sensitivityAAPSPlugin: SensitivityAAPSPlugin,
sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin
) : IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction,
configBuilderPlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin) {
activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin) {
override fun onStart() { // do not attach to rxbus
}

View file

@ -1,25 +1,34 @@
package info.nightscout.androidaps.interfaces;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public interface ActivePluginProvider {
@Nullable BgSourceInterface getActiveBgSource();
@NotNull BgSourceInterface getActiveBgSource(); // Forced to Dexcom
@NotNull ProfileInterface getActiveProfileInterface(); // Forced to LocalProfile if not changed
@NonNull InsulinInterface getActiveInsulin(); // Forced to RapidActing if not changed
@NotNull InsulinInterface getActiveInsulin(); // Forced to RapidActing if not changed
@Nullable APSInterface getActiveAPS();
@Nullable PumpInterface getActivePumpPlugin(); // Use in UI to disable buttons or check if pump is selected
@NotNull APSInterface getActiveAPS(); // Forced to SMB
@NotNull PumpInterface getActivePump(); // Use in places not reachable without active pump. Otherwise IllegalStateException is thrown
@NotNull SensitivityInterface getActiveSensitivity(); // Forced to oref1 if not changed
@NotNull TreatmentsInterface getActiveTreatments();
@NotNull TreatmentsInterface getActiveTreatments(); // Forced to treatments
@NotNull ArrayList<PluginBase> getPluginsList();
@NotNull ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type);
@NotNull ArrayList<PluginBase> getSpecificPluginsVisibleInList(PluginType type);
@NotNull ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass);
// @NotNull ArrayList<PluginBase> getSpecificPluginsVisibleInList(Class interfaceClass);
void verifySelectionInCategories();
}

View file

@ -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<T extends Comparable> {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.CONSTRAINTS);
private T value;
private T originalValue;
T value;
T originalValue;
List<String> reasons = new ArrayList<>();
List<String> mostLimiting = new ArrayList<>();
private List<String> reasons = new ArrayList<>();
private List<String> mostLimiting = new ArrayList<>();
public Constraint(T value) {
this.value = value;
@ -35,27 +30,24 @@ public class Constraint<T extends Comparable> {
return originalValue;
}
public Constraint<T> set(T value) {
public Constraint<T> 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<T> set(T value, String reason, Object from) {
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]");
public Constraint<T> 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<T> setIfDifferent(T value, String reason, Object from) {
public Constraint<T> 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<T extends Comparable> {
return this;
}
public Constraint<T> setIfSmaller(T value, String reason, Object from) {
public Constraint<T> 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<T extends Comparable> {
return this;
}
public Constraint<T> setIfGreater(T value, String reason, Object from) {
public Constraint<T> 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,15 +95,14 @@ public class Constraint<T extends Comparable> {
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();
}
@ -121,15 +110,14 @@ public class Constraint<T extends Comparable> {
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();
}

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.interfaces;
import dagger.android.HasAndroidInjector;
/**
* Created by mike on 21.05.2017.
*/

View file

@ -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 {
@ -58,6 +60,8 @@ abstract class PluginBase(
return pluginDescription.fragmentClass != null
}
fun isDefault() = pluginDescription.defaultPlugin
/**
* So far plugin can have it's main type + ConstraintInterface + ProfileInterface
* ConstraintInterface is enabled if main plugin is enabled

View file

@ -13,6 +13,7 @@ public class PluginDescription {
int preferencesId = -1;
public boolean enableByDefault = false;
public boolean visibleByDefault = false;
boolean defaultPlugin = false;
public PluginDescription mainType(PluginType mainType) {
this.mainType = mainType;
@ -74,6 +75,11 @@ public class PluginDescription {
return this;
}
public PluginDescription setDefault() {
defaultPlugin = true;
return this;
}
public String getFragmentClass() {
return fragmentClass;
}

View file

@ -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()

View file

@ -6,35 +6,48 @@ 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 HasAndroidInjector injector;
@Inject public AAPSLogger aapsLogger;
@Inject ConstraintChecker constraintChecker;
@Inject SP sp;
@Inject ActivePluginProvider activePlugin;
@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 +101,65 @@ public class APSResult {
@Override
public String toString() {
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
final PumpInterface pump = activePlugin.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");
ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " 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 = activePlugin.getActivePump();
if (isChangeRequested()) {
String ret;
// rate
if (rate == 0 && duration == 0)
ret = MainApp.gs(R.string.canceltemp) + "<br>";
ret = resourceHelper.gs(R.string.canceltemp) + "<br>";
else if (rate == -1)
ret = MainApp.gs(R.string.let_temp_basal_run) + "<br>";
ret = resourceHelper.gs(R.string.let_temp_basal_run) + "<br>";
else if (usePercent)
ret = "<b>" + MainApp.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(percent) + "% " +
ret = "<b>" + resourceHelper.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(percent) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)<br>" +
"<b>" + MainApp.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
"<b>" + resourceHelper.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
else
ret = "<b>" + MainApp.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
ret = "<b>" + resourceHelper.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100d) + "%) <br>" +
"<b>" + MainApp.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
"<b>" + resourceHelper.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
// smb
if (smb != 0)
ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U<br>");
ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U<br>");
// reason
ret += "<b>" + MainApp.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
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 +175,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 +196,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 +259,7 @@ public class APSResult {
}
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return array;
}
@ -282,66 +292,60 @@ public class APSResult {
}
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return latest;
}
public boolean isChangeRequested() {
Constraint<Boolean> closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed();
Constraint<Boolean> 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 = activePlugin.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 +354,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 +392,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;
}
}

View file

@ -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
}

View file

@ -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;
@ -38,6 +39,7 @@ import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
@ -52,7 +54,6 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui
import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
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.nsclient.NSUpload;
@ -73,14 +74,15 @@ 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;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
private final MainApp mainApp;
private final Context context;
private final CommandQueueProvider commandQueue;
private final ConfigBuilderPlugin configBuilderPlugin;
private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin;
private final VirtualPumpPlugin virtualPumpPlugin;
private final Lazy<ActionStringHandler> actionStringHandler;
@ -114,15 +116,16 @@ public class LoopPlugin extends PluginBase {
@Inject
public LoopPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
SP sp,
ConstraintChecker constraintChecker,
ResourceHelper resourceHelper,
ProfileFunction profileFunction,
MainApp mainApp,
Context context,
CommandQueueProvider commandQueue,
ConfigBuilderPlugin configBuilderPlugin,
ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin,
VirtualPumpPlugin virtualPumpPlugin,
Lazy<ActionStringHandler> actionStringHandler, // TODO Adrian use RxBus instead of Lazy
@ -135,15 +138,16 @@ 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;
this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction;
this.mainApp = mainApp;
this.configBuilderPlugin = configBuilderPlugin;
this.context = context;
this.activePlugin = activePlugin;
this.commandQueue = commandQueue;
this.treatmentsPlugin = treatmentsPlugin;
this.virtualPumpPlugin = virtualPumpPlugin;
@ -194,7 +198,7 @@ public class LoopPlugin extends PluginBase {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager =
(NotificationManager) mainApp.getSystemService(Context.NOTIFICATION_SERVICE);
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
@SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH);
@ -210,8 +214,13 @@ public class LoopPlugin extends PluginBase {
@Override
public boolean specialEnableCondition() {
PumpInterface pump = configBuilderPlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
try {
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
} catch (Exception ignored) {
// may fail during initialization
return true;
}
}
public long suspendedTo() {
@ -311,14 +320,12 @@ public class LoopPlugin extends PluginBase {
Constraint<Boolean> 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;
}
final PumpInterface pump = configBuilderPlugin.getActivePumpPlugin();
if (pump == null)
return;
final PumpInterface pump = activePlugin.getActivePump();
APSResult result = null;
if (!isEnabled(PluginType.LOOP))
@ -336,8 +343,8 @@ public class LoopPlugin extends PluginBase {
// Check if pump info is loaded
if (pump.getBaseBasalRate() < 0.01d) return;
APSInterface usedAPS = configBuilderPlugin.getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
APSInterface usedAPS = activePlugin.getActiveAPS();
if (((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
usedAPS.invoke(initiator, tempBasalFallback);
result = usedAPS.getLastAPSResult();
}
@ -355,7 +362,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();
@ -404,7 +411,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;
@ -448,7 +455,7 @@ public class LoopPlugin extends PluginBase {
} else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mainApp, CHANNEL_ID);
new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString())
@ -461,13 +468,13 @@ public class LoopPlugin extends PluginBase {
}
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(mainApp, MainActivity.class);
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mainApp);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
@ -476,7 +483,7 @@ public class LoopPlugin extends PluginBase {
builder.setContentIntent(resultPendingIntent);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) mainApp.getSystemService(Context.NOTIFICATION_SERVICE);
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
rxBus.send(new EventNewOpenLoopNotification());
@ -486,7 +493,7 @@ public class LoopPlugin extends PluginBase {
} else if (allowNotification) {
// dismiss notifications
NotificationManager notificationManager =
(NotificationManager) mainApp.getSystemService(Context.NOTIFICATION_SERVICE);
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
actionStringHandler.get().handleInitiate("cancelChangeRequest");
}
@ -528,22 +535,17 @@ 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;
}
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();
return;
}
PumpInterface pump = activePlugin.getActivePump();
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;
}
@ -551,7 +553,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;
}
@ -568,7 +570,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();
}
}
@ -578,7 +580,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();
}
@ -594,7 +596,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();
}
}
@ -604,7 +606,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();
}
@ -620,18 +622,13 @@ public class LoopPlugin extends PluginBase {
return;
}
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();
return;
}
PumpInterface pump = activePlugin.getActivePump();
long lastBolusTime = treatmentsPlugin.getLastBolusTime();
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();
}
@ -641,7 +638,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;
}
@ -649,7 +646,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;
}
@ -669,9 +666,7 @@ public class LoopPlugin extends PluginBase {
}
public void disconnectPump(int durationInMinutes, Profile profile) {
PumpInterface pump = configBuilderPlugin.getActivePumpPlugin();
if (pump == null)
return;
PumpInterface pump = activePlugin.getActivePump();
disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
@ -680,12 +675,12 @@ public class LoopPlugin extends PluginBase {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(mainApp, ErrorHelperActivity.class);
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainApp.startActivity(i);
context.startActivity(i);
}
}
});
@ -694,12 +689,12 @@ public class LoopPlugin extends PluginBase {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(mainApp, ErrorHelperActivity.class);
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainApp.startActivity(i);
context.startActivity(i);
}
}
});
@ -710,12 +705,12 @@ public class LoopPlugin extends PluginBase {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(mainApp, ErrorHelperActivity.class);
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", resourceHelper.gs(R.string.extendedbolusdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainApp.startActivity(i);
context.startActivity(i);
}
}
});
@ -729,12 +724,12 @@ public class LoopPlugin extends PluginBase {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(mainApp, ErrorHelperActivity.class);
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainApp.startActivity(i);
context.startActivity(i);
}
}
});

View file

@ -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;
@ -30,17 +32,21 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
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.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;
@Inject ProfileFunction profileFunction;
@Inject TreatmentsPlugin treatmentsPlugin;
private ScriptReader mScriptReader = null;
private ScriptReader mScriptReader;
private JSONObject mProfile;
private JSONObject mGlucoseStatus;
@ -58,9 +64,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 +132,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,25 +211,25 @@ 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)) {
if (profileFunction.getUnits().equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L");
}
long now = System.currentTimeMillis();
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject();
mCurrentTemp.put("temp", "absolute");
@ -230,7 +237,7 @@ public class DetermineBasalAdapterAMAJS {
mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
// as we have non default temps longer than 30 mintues
TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
TemporaryBasal tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (tempBasal != null) {
mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration());
}
@ -240,7 +247,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 +260,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 {

View file

@ -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;

View file

@ -1,11 +1,13 @@
package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import android.content.Context;
import org.json.JSONException;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
@ -45,10 +47,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
private final MainApp mainApp;
private final Context context;
private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final HardLimits hardLimits;
// last values
DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null;
@ -58,15 +61,17 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
@Inject
public OpenAPSAMAPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
ConstraintChecker constraintChecker,
ResourceHelper resourceHelper,
ProfileFunction profileFunction,
MainApp mainApp,
Context context,
ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin,
IobCobCalculatorPlugin iobCobCalculatorPlugin
IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits
) {
super(new PluginDescription()
.mainType(PluginType.APS)
@ -75,33 +80,35 @@ 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;
this.constraintChecker = constraintChecker;
this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction;
this.mainApp = mainApp;
this.context = context;
this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.hardLimits = hardLimits;
}
@Override
public boolean specialEnableCondition() {
// main fail during init
if (activePlugin != null) {
PumpInterface pump = activePlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
try {
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
} catch (Exception ignored) {
// may fail during initialization
return true;
}
return true;
}
@Override
public boolean specialShowInListCondition() {
PumpInterface pump = activePlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
}
@Override
@ -119,9 +126,9 @@ 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(context), getInjector());
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePump();
@ -131,12 +138,6 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
return;
}
if (pump == null) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected)));
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.nopumpselected));
return;
}
if (!isEnabled(PluginType.APS)) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));
@ -168,29 +169,29 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
double maxIob = constraintChecker.getMaxIOBAllowed().value();
minBg = HardLimits.verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = HardLimits.verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
targetBg = HardLimits.verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]);
minBg = hardLimits.verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = hardLimits.verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false;
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) {
isTempTarget = true;
minBg = HardLimits.verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
maxBg = HardLimits.verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
targetBg = HardLimits.verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
minBg = hardLimits.verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[1]);
maxBg = hardLimits.verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[1]);
targetBg = hardLimits.verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[1]);
}
if (!HardLimits.checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
if (!hardLimits.checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return;
if (!HardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return;
if (!HardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF))
if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return;
if (!HardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
if (!hardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, hardLimits.maxBasal()))
return;
if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return;
startPart = System.currentTimeMillis();

View file

@ -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;
@ -26,14 +28,18 @@ import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.SP;
public class DetermineBasalAdapterMAJS {
private final AAPSLogger aapsLogger;
private HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject ProfileFunction profileFunction;
@Inject TreatmentsPlugin treatmentsPlugin;
private ScriptReader mScriptReader;
private JSONObject mProfile;
private JSONObject mGlucoseStatus;
@ -47,9 +53,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 +112,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);
}
@ -176,12 +183,12 @@ public class DetermineBasalAdapterMAJS {
mProfile.put("current_basal", basalRate);
if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) {
if (profileFunction.getUnits().equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L");
}
long now = System.currentTimeMillis();
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject();
mCurrentTemp.put("duration", tb != null ? tb.getPlannedRemainingMinutes() : 0);

View file

@ -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;

View file

@ -1,11 +1,13 @@
package info.nightscout.androidaps.plugins.aps.openAPSMA;
import android.content.Context;
import org.json.JSONException;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
@ -36,19 +38,17 @@ import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import static info.nightscout.androidaps.utils.HardLimits.checkOnlyHardLimits;
import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits;
@Singleton
public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
private final RxBusWrapper rxBus;
private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
private final MainApp mainApp;
private final Context context;
private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final HardLimits hardLimits;
// last values
DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null;
@ -57,15 +57,17 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
@Inject
public OpenAPSMAPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
ConstraintChecker constraintChecker,
ResourceHelper resourceHelper,
ProfileFunction profileFunction,
MainApp mainApp,
Context context,
ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin,
IobCobCalculatorPlugin iobCobCalculatorPlugin
IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits
) {
super(new PluginDescription()
.mainType(PluginType.APS)
@ -74,33 +76,35 @@ 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;
this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction;
this.mainApp = mainApp;
this.context = context;
this.rxBus = rxBus;
this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.hardLimits = hardLimits;
}
@Override
public boolean specialEnableCondition() {
// main fail during init
if (activePlugin != null) {
PumpInterface pump = activePlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
try {
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
} catch (Exception ignored) {
// may fail during initialization
return true;
}
return true;
}
@Override
public boolean specialShowInListCondition() {
PumpInterface pump = activePlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
}
@Override
@ -118,11 +122,11 @@ 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(context), getInjector());
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePumpPlugin();
PumpInterface pump = activePlugin.getActivePump();
if (profile == null) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected)));
@ -130,12 +134,6 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
return;
}
if (pump == null) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected)));
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.nopumpselected));
return;
}
if (!isEnabled(PluginType.APS)) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));
@ -170,26 +168,26 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
double maxIob = constraintChecker.getMaxIOBAllowed().value();
Profiler.log(getAapsLogger(), LTag.APS, "MA data gathering", start);
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
targetBg = verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]);
minBg = hardLimits.verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = hardLimits.verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) {
minBg = verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
maxBg = verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
targetBg = verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
minBg = hardLimits.verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[1]);
maxBg = hardLimits.verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[1]);
targetBg = hardLimits.verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[1]);
}
if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
if (!hardLimits.checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return;
if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF))
if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
if (!hardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, hardLimits.maxBasal()))
return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return;
start = System.currentTimeMillis();

View file

@ -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;
@ -30,16 +32,20 @@ import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
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.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;
@Inject ProfileFunction profileFunction;
@Inject TreatmentsPlugin treatmentsPlugin;
private ScriptReader mScriptReader;
private JSONObject mProfile;
@ -67,9 +73,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 +150,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 +238,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,26 +265,26 @@ 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)) {
if (profileFunction.getUnits().equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L");
}
long now = System.currentTimeMillis();
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
mCurrentTemp = new JSONObject();
mCurrentTemp.put("temp", "absolute");
@ -285,7 +292,7 @@ public class DetermineBasalAdapterSMBJS {
mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d);
// as we have non default temps longer than 30 mintues
TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
TemporaryBasal tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (tempBasal != null) {
mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration());
}
@ -295,7 +302,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 +321,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 {

View file

@ -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;

View file

@ -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) {

View file

@ -1,12 +1,14 @@
package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
@ -29,7 +31,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
@ -40,7 +41,6 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
@Singleton
@ -48,11 +48,12 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
private final MainApp mainApp;
private final Context context;
private final RxBusWrapper rxBus;
private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final HardLimits hardLimits;
// last values
DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null;
@ -62,15 +63,17 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
@Inject
public OpenAPSSMBPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
ConstraintChecker constraintChecker,
ResourceHelper resourceHelper,
ProfileFunction profileFunction,
MainApp mainApp,
Context context,
ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin,
IobCobCalculatorPlugin iobCobCalculatorPlugin
IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits
) {
super(new PluginDescription()
.mainType(PluginType.APS)
@ -79,33 +82,34 @@ 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.constraintChecker = constraintChecker;
this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction;
this.rxBus = rxBus;
this.mainApp = mainApp;
this.context = context;
this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.hardLimits = hardLimits;
}
@Override
public boolean specialEnableCondition() {
// main fail during init
if (activePlugin != null) {
PumpInterface pump = activePlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
try {
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
} catch (Exception ignored) {
// may fail during initialization
return true;
}
return true;
}
@Override
public boolean specialShowInListCondition() {
PumpInterface pump = activePlugin.getActivePumpPlugin();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
}
@Override
@ -123,9 +127,9 @@ 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(context), getInjector());
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePump();
@ -135,12 +139,6 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
return;
}
if (pump == null) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.nopumpselected)));
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.nopumpselected));
return;
}
if (!isEnabled(PluginType.APS)) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));
@ -175,29 +173,29 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
inputConstraints.copyReasons(maxIOBAllowedConstraint);
double maxIob = maxIOBAllowedConstraint.value();
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
targetBg = verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]);
minBg = hardLimits.verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = hardLimits.verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false;
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) {
isTempTarget = true;
minBg = verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
maxBg = verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
targetBg = verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
minBg = hardLimits.verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[1]);
maxBg = hardLimits.verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[1]);
targetBg = hardLimits.verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[1]);
}
if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
if (!hardLimits.checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return;
if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", HardLimits.MINISF, HardLimits.MAXISF))
if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
if (!hardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, hardLimits.maxBasal()))
return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return;
startPart = System.currentTimeMillis();
@ -280,30 +278,10 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
//deviceStatus.suggested = determineBasalResultAMA.json;
}
// safety checks
private boolean checkOnlyHardLimits(Double value, String valueName, double lowLimit, double highLimit) {
return value.equals(verifyHardLimits(value, valueName, lowLimit, highLimit));
}
private Double verifyHardLimits(Double value, String valueName, double lowLimit, double highLimit) {
Double newvalue = value;
if (newvalue < lowLimit || newvalue > highLimit) {
newvalue = Math.max(newvalue, lowLimit);
newvalue = Math.min(newvalue, highLimit);
String msg = String.format(resourceHelper.gs(R.string.valueoutofrange), valueName);
msg += ".\n";
msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newvalue);
getAapsLogger().error(LTag.APS, msg);
NSUpload.uploadError(msg);
ToastUtils.showToastInUiThread(mainApp, msg, R.raw.error);
}
return newvalue;
}
@NotNull
@Override
public Constraint<Boolean> isSuperBolusEnabled(Constraint<Boolean> value) {
value.set(false);
value.set(getAapsLogger(), false);
return value;
}

View file

@ -34,6 +34,7 @@ class ConfigBuilderFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider
private var disposable: CompositeDisposable = CompositeDisposable()
private val pluginViewHolders = ArrayList<PluginViewHolder>()
@ -80,16 +81,16 @@ class ConfigBuilderFragment : DaggerFragment() {
@Synchronized
private fun updateGUI() {
configbuilder_categories.removeAllViews()
createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE))
createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN))
createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE))
createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, MainApp.getSpecificPluginsVisibleInList(PluginType.PUMP))
createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY))
createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, MainApp.getSpecificPluginsVisibleInList(PluginType.APS))
createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, MainApp.getSpecificPluginsVisibleInList(PluginType.LOOP))
createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS))
createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, MainApp.getSpecificPluginsVisibleInList(PluginType.TREATMENT))
createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, MainApp.getSpecificPluginsVisibleInList(PluginType.GENERAL))
createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, activePlugin.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE))
createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, activePlugin.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN))
createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, activePlugin.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE))
createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, activePlugin.getSpecificPluginsVisibleInList(PluginType.PUMP))
createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, activePlugin.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY))
createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, activePlugin.getSpecificPluginsVisibleInList(PluginType.APS))
createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP))
createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS))
createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, activePlugin.getSpecificPluginsVisibleInList(PluginType.TREATMENT))
createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, activePlugin.getSpecificPluginsVisibleInList(PluginType.GENERAL))
}
private fun createViewsForPlugins(@StringRes title: Int, @StringRes description: Int, pluginType: PluginType, plugins: List<PluginBase>) {

View file

@ -4,15 +4,13 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Lazy;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppInitialized;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
@ -47,24 +45,25 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
* Created by mike on 05.08.2016.
*/
@Singleton
public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvider {
public class ConfigBuilderPlugin extends PluginBase {
private static ConfigBuilderPlugin configBuilderPlugin;
private final ActivePluginProvider activePlugin;
private final SP sp;
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper;
private final CommandQueueProvider commandQueue;
private final NSProfilePlugin nsProfilePlugin;
private final ProfileFunction profileFunction;
/**
* @deprecated Use dagger to get an instance
*/
@Deprecated
public CommandQueueProvider getCommandQueue() {
if (commandQueue == null)
throw new IllegalStateException("Accessing commandQueue before first instantiation");
return commandQueue;
public ProfileFunction getProfileFunction() {
if (profileFunction == null)
throw new IllegalStateException("Accessing profileFunction before first instantiation");
return profileFunction;
}
@Deprecated
@ -74,22 +73,6 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
return configBuilderPlugin;
}
private BgSourceInterface activeBgSource;
private PumpInterface activePump;
private ProfileInterface activeProfile;
private APSInterface activeAPS;
private InsulinInterface activeInsulin;
private SensitivityInterface activeSensitivity;
private Lazy<TreatmentsPlugin> treatmentsPlugin;
private Lazy<SensitivityOref0Plugin> sensitivityOref0Plugin;
private Lazy<SensitivityOref1Plugin> sensitivityOref1Plugin;
private ArrayList<PluginBase> pluginList;
private final Lazy<InsulinOrefRapidActingPlugin> insulinOrefRapidActingPlugin;
private final Lazy<LocalProfilePlugin> localProfilePlugin;
private final Lazy<VirtualPumpPlugin> virtualPumpPlugin;
/*
* Written by Adrian:
* The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app.
@ -99,18 +82,13 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
* */
@Inject
public ConfigBuilderPlugin(
Lazy<InsulinOrefRapidActingPlugin> insulinOrefRapidActingPlugin,
Lazy<LocalProfilePlugin> localProfilePlugin,
Lazy<VirtualPumpPlugin> virtualPumpPlugin,
Lazy<TreatmentsPlugin> treatmentsPlugin,
Lazy<SensitivityOref0Plugin> sensitivityOref0Plugin,
Lazy<SensitivityOref1Plugin> sensitivityOref1Plugin,
ActivePluginProvider activePlugin,
HasAndroidInjector injector,
SP sp,
RxBusWrapper rxBus,
AAPSLogger aapsLogger,
ResourceHelper resourceHelper,
CommandQueueProvider commandQueue,
NSProfilePlugin nsProfilePlugin
ProfileFunction profileFunction
) {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
@ -121,33 +99,27 @@ 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;
this.virtualPumpPlugin = virtualPumpPlugin;
this.treatmentsPlugin = treatmentsPlugin;
this.sensitivityOref0Plugin = sensitivityOref0Plugin;
this.sensitivityOref1Plugin = sensitivityOref1Plugin;
this.activePlugin = activePlugin;
this.sp = sp;
this.rxBus = rxBus;
this.aapsLogger = aapsLogger;
this.resourceHelper = resourceHelper;
this.commandQueue = commandQueue;
this.nsProfilePlugin = nsProfilePlugin;
this.profileFunction = profileFunction;
configBuilderPlugin = this; // TODO: only while transitioning to Dagger
}
public void initialize() {
pluginList = MainApp.getPluginsList();
upgradeSettings();
((PluginStore) activePlugin).loadDefaults();
loadSettings();
setAlwaysEnabledPluginsEnabled();
rxBus.send(new EventAppInitialized());
}
private void setAlwaysEnabledPluginsEnabled() {
for (PluginBase plugin : pluginList) {
for (PluginBase plugin : activePlugin.getPluginsList()) {
if (plugin.getPluginDescription().alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true);
}
@ -155,22 +127,21 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
}
public void storeSettings(String from) {
if (pluginList != null) {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from);
activePlugin.getPluginsList();
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from);
verifySelectionInCategories();
activePlugin.verifySelectionInCategories();
for (PluginBase p : pluginList) {
PluginType type = p.getType();
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible)
continue;
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().neverVisible)
continue;
savePref(p, type, true);
if (type == PluginType.PUMP) {
if (p instanceof ProfileInterface) { // Store state of optional Profile interface
savePref(p, PluginType.PROFILE, false);
}
for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible)
continue;
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().neverVisible)
continue;
savePref(p, type, true);
if (type == PluginType.PUMP) {
if (p instanceof ProfileInterface) { // Store state of optional Profile interface
savePref(p, PluginType.PROFILE, false);
}
}
}
@ -189,7 +160,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
private void loadSettings() {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loading stored settings");
for (PluginBase p : pluginList) {
for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
loadPref(p, type, true);
if (p.getType() == PluginType.PUMP) {
@ -198,7 +169,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
}
}
}
verifySelectionInCategories();
activePlugin.verifySelectionInCategories();
}
private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
@ -225,7 +196,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return;
getAapsLogger().debug(LTag.CONFIGBUILDER, "Upgrading stored settings");
for (PluginBase p : pluginList) {
for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Processing " + p.getName());
for (int type = 1; type < 11; type++) {
PluginType newType;
@ -274,69 +245,13 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
sp.remove(settingVisible);
if (newType == p.getType()) {
savePref(p, newType, true);
} else if (p.getType() == PluginType.PUMP && p instanceof ProfileInterface) {
savePref(p, PluginType.PROFILE, false);
}
}
}
}
@Override
@Nullable
public BgSourceInterface getActiveBgSource() {
return activeBgSource;
}
@Override
@NotNull
public ProfileInterface getActiveProfileInterface() {
if (activeProfile != null) return activeProfile;
else return localProfilePlugin.get();
}
@Override
@NotNull
public InsulinInterface getActiveInsulin() {
if (activeInsulin == null)
return insulinOrefRapidActingPlugin.get();
return activeInsulin;
}
@Override
@Nullable
public APSInterface getActiveAPS() {
return activeAPS;
}
@Override
@NotNull
public PumpInterface getActivePump() {
if (activePump == null)
throw new IllegalStateException("No pump selected");
return activePump;
}
@Override
@Nullable
public PumpInterface getActivePumpPlugin() {
return activePump;
}
@Override
@NotNull
public SensitivityInterface getActiveSensitivity() {
if (activeSensitivity == null)
return sensitivityOref1Plugin.get();
else
return activeSensitivity;
}
@NonNull @Override public TreatmentsInterface getActiveTreatments() {
return treatmentsPlugin.get();
}
public void logPluginStatus() {
for (PluginBase p : pluginList) {
for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
(p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
@ -352,120 +267,6 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
}
}
private void verifySelectionInCategories() {
ArrayList<PluginBase> pluginsInCategory;
// PluginType.APS
activeAPS = this.determineActivePlugin(APSInterface.class, PluginType.APS);
// PluginType.INSULIN
pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.INSULIN);
activeInsulin = (InsulinInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN);
if (activeInsulin == null) {
activeInsulin = insulinOrefRapidActingPlugin.get();
insulinOrefRapidActingPlugin.get().setPluginEnabled(PluginType.INSULIN, true);
getAapsLogger().debug(LTag.CONFIGBUILDER, "Defaulting InsulinOrefRapidActingPlugin");
}
this.setFragmentVisiblities(((PluginBase) activeInsulin).getName(), pluginsInCategory, PluginType.INSULIN);
// PluginType.SENSITIVITY
pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.SENSITIVITY);
activeSensitivity = (SensitivityInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY);
if (activeSensitivity == null) {
activeSensitivity = sensitivityOref0Plugin.get();
sensitivityOref0Plugin.get().setPluginEnabled(PluginType.SENSITIVITY, true);
getAapsLogger().debug(LTag.CONFIGBUILDER, "Defaulting SensitivityOref0Plugin");
}
this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY);
// PluginType.PROFILE
activeProfile = this.determineActivePlugin(ProfileInterface.class, PluginType.PROFILE);
// PluginType.BGSOURCE
activeBgSource = this.determineActivePlugin(BgSourceInterface.class, PluginType.BGSOURCE);
// PluginType.PUMP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP);
if (activePump == null) {
activePump = virtualPumpPlugin.get();
virtualPumpPlugin.get().setPluginEnabled(PluginType.PUMP, true);
getAapsLogger().debug(LTag.CONFIGBUILDER, "Defaulting VirtualPumpPlugin");
}
this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
// PluginType.TREATMENT
}
/**
* disables the visibility for all fragments of Plugins with the given PluginType
* which are not equally named to the Plugin implementing the given Plugin Interface.
*
* @param pluginInterface
* @param pluginType
* @param <T>
* @return
*/
private <T> T determineActivePlugin(Class<T> pluginInterface, PluginType pluginType) {
ArrayList<PluginBase> pluginsInCategory;
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(pluginInterface);
return this.determineActivePlugin(pluginsInCategory, pluginType);
}
/**
* disables the visibility for all fragments of Plugins in the given pluginsInCategory
* with the given PluginType which are not equally named to the Plugin implementing the
* given Plugin Interface.
* <p>
* TODO we are casting an interface to PluginBase, which seems to be rather odd, since
* TODO the interface is not implementing PluginBase (this is just avoiding errors through
* TODO conventions.
*
* @param pluginsInCategory
* @param pluginType
* @param <T>
* @return
*/
private <T> T determineActivePlugin(ArrayList<PluginBase> pluginsInCategory,
PluginType pluginType) {
T activePlugin = (T) getTheOneEnabledInArray(pluginsInCategory, pluginType);
if (activePlugin != null) {
this.setFragmentVisiblities(((PluginBase) activePlugin).getName(),
pluginsInCategory, pluginType);
}
return activePlugin;
}
private void setFragmentVisiblities(String activePluginName, ArrayList<PluginBase> pluginsInCategory,
PluginType pluginType) {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Selected interface: " + activePluginName);
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activePluginName)) {
p.setFragmentVisible(pluginType, false);
}
}
}
@Nullable
private PluginBase getTheOneEnabledInArray(ArrayList<PluginBase> pluginsInCategory, PluginType type) {
PluginBase found = null;
for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p;
} else if (p.isEnabled(type)) {
// set others disabled
p.setPluginEnabled(type, false);
}
}
// If none enabled, enable first one
//if (found == null && pluginsInCategory.size() > 0)
// found = pluginsInCategory.get(0);
return found;
}
// Ask when switching to physical pump plugin
public void switchAllowed(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
if (changedPlugin.getType() == PluginType.PUMP && !changedPlugin.getName().equals(resourceHelper.gs(R.string.virtualpump)))
@ -490,7 +291,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
}
}
private void performPluginSwitch(PluginBase changedPlugin, boolean enabled, @NonNull PluginType type) {
public void performPluginSwitch(PluginBase changedPlugin, boolean enabled, @NonNull PluginType type) {
changedPlugin.setPluginEnabled(type, enabled);
changedPlugin.setFragmentVisible(type, enabled);
processOnEnabledCategoryChanged(changedPlugin, type);
@ -511,23 +312,25 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
break;
// Single selection allowed
case INSULIN:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(InsulinInterface.class);
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface.class);
break;
case SENSITIVITY:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(SensitivityInterface.class);
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface.class);
break;
case APS:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(APSInterface.class);
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface.class);
break;
case PROFILE:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(ProfileInterface.class);
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case BGSOURCE:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(BgSourceInterface.class);
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case TREATMENT:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface.class);
break;
case PUMP:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(PumpInterface.class);
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface.class);
break;
}
if (pluginsInCategory != null) {
@ -542,16 +345,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
}
}
} else { // enable first plugin in list
if (type == PluginType.PUMP)
virtualPumpPlugin.get().setPluginEnabled(type, true);
else if (type == PluginType.INSULIN)
insulinOrefRapidActingPlugin.get().setPluginEnabled(type, true);
else if (type == PluginType.SENSITIVITY)
sensitivityOref0Plugin.get().setPluginEnabled(type, true);
else if (type == PluginType.PROFILE)
nsProfilePlugin.setPluginEnabled(type, true);
else
pluginsInCategory.get(0).setPluginEnabled(type, true);
pluginsInCategory.get(0).setPluginEnabled(type, true);
}
}
}

View file

@ -1,8 +1,8 @@
package info.nightscout.androidaps.plugins.configBuilder
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginType
@ -10,17 +10,7 @@ import javax.inject.Inject
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
}
class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface {
fun isLoopInvocationAllowed(): Constraint<Boolean> =
isLoopInvocationAllowed(Constraint(true))
@ -65,7 +55,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB))
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -75,7 +65,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -85,7 +75,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -95,7 +85,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isAMAModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -105,7 +95,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -115,7 +105,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isUAMEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -125,7 +115,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isAdvancedFilteringEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -135,7 +125,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun isSuperBolusEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -145,7 +135,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun applyBasalConstraints(absoluteRate: Constraint<Double>, profile: Profile): Constraint<Double> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -155,7 +145,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun applyBasalPercentConstraints(percentRate: Constraint<Int>, profile: Profile): Constraint<Int> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -165,7 +155,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun applyBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -175,7 +165,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun applyExtendedBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -185,7 +175,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun applyCarbsConstraints(carbs: Constraint<Int>): Constraint<Int> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -195,7 +185,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
}
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)
for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue

View file

@ -0,0 +1,233 @@
package info.nightscout.androidaps.plugins.configBuilder
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PluginStore @Inject constructor(
val aapsLogger: AAPSLogger
) : ActivePluginProvider {
// TODO remove
init {
pluginStore = this
}
companion object {
var pluginStore: PluginStore? = null
@Deprecated("Use dagger instead")
fun getInstance(): PluginStore {
checkNotNull(pluginStore) { "Accessing PluginStore before first instantiation" }
return pluginStore!!
}
}
var plugins = ArrayList<PluginBase>()
private var activeBgSource: BgSourceInterface? = null
private var activePump: PumpInterface? = null
private var activeProfile: ProfileInterface? = null
private var activeAPS: APSInterface? = null
private var activeInsulin: InsulinInterface? = null
private var activeSensitivity: SensitivityInterface? = null
private var activeTreatments: TreatmentsInterface? = null
fun loadDefaults() {
verifySelectionInCategories()
}
fun add(pluginBase: PluginBase): ActivePluginProvider {
plugins.add(pluginBase)
return this
}
fun getDefaultPlugin(type: PluginType): PluginBase {
for (p in plugins)
if (p.getType() == type && p.isDefault()) return p
throw IllegalStateException("Default plugin not found")
}
fun getSpecificPluginsList(type: PluginType): ArrayList<PluginBase> {
val newList = ArrayList<PluginBase>()
for (p in plugins) {
if (p.getType() == type) newList.add(p)
}
return newList
}
override fun getSpecificPluginsVisibleInList(type: PluginType): ArrayList<PluginBase> {
val newList = ArrayList<PluginBase>()
for (p in plugins) {
if (p.getType() == type) if (p.showInList(type)) newList.add(p)
}
return newList
}
override fun getSpecificPluginsListByInterface(interfaceClass: Class<*>): ArrayList<PluginBase> {
val newList = ArrayList<PluginBase>()
for (p in plugins) {
if (p.javaClass != ConfigBuilderPlugin::class.java && interfaceClass.isAssignableFrom(p.javaClass)) newList.add(p)
}
return newList
}
override fun getSpecificPluginsVisibleInListByInterface(interfaceClass: Class<*>, type: PluginType): ArrayList<PluginBase> {
val newList = ArrayList<PluginBase>()
for (p in plugins) {
if (p.javaClass != ConfigBuilderPlugin::class.java && interfaceClass.isAssignableFrom(p.javaClass)) if (p.showInList(type)) newList.add(p)
}
return newList
}
override fun verifySelectionInCategories() {
var pluginsInCategory: ArrayList<PluginBase>?
// PluginType.APS
activeAPS = determineActivePlugin(APSInterface::class.java, PluginType.APS)
// PluginType.INSULIN
pluginsInCategory = getSpecificPluginsList(PluginType.INSULIN)
activeInsulin = getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN) as InsulinInterface?
if (activeInsulin == null) {
activeInsulin = getDefaultPlugin(PluginType.INSULIN) as InsulinInterface
(activeInsulin as PluginBase).setPluginEnabled(PluginType.INSULIN, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting InsulinInterface")
}
setFragmentVisiblities((activeInsulin as PluginBase).name, pluginsInCategory, PluginType.INSULIN)
// PluginType.SENSITIVITY
pluginsInCategory = getSpecificPluginsList(PluginType.SENSITIVITY)
activeSensitivity = getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY) as SensitivityInterface?
if (activeSensitivity == null) {
activeSensitivity = getDefaultPlugin(PluginType.SENSITIVITY) as SensitivityInterface
(activeSensitivity as PluginBase).setPluginEnabled(PluginType.SENSITIVITY, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting SensitivityInterface")
}
setFragmentVisiblities((activeSensitivity as PluginBase).name, pluginsInCategory, PluginType.SENSITIVITY)
// PluginType.PROFILE
pluginsInCategory = getSpecificPluginsList(PluginType.PROFILE)
activeProfile = getTheOneEnabledInArray(pluginsInCategory, PluginType.PROFILE) as ProfileInterface?
if (activeProfile == null) {
activeProfile = getDefaultPlugin(PluginType.PROFILE) as ProfileInterface
(activeProfile as PluginBase).setPluginEnabled(PluginType.PROFILE, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting ProfileInterface")
}
setFragmentVisiblities((activeSensitivity as PluginBase).name, pluginsInCategory, PluginType.PROFILE)
// PluginType.BGSOURCE
activeBgSource = this.determineActivePlugin(BgSourceInterface::class.java, PluginType.BGSOURCE)
// PluginType.PUMP
pluginsInCategory = getSpecificPluginsList(PluginType.PUMP)
activePump = getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP) as PumpInterface?
if (activePump == null) {
activePump = getDefaultPlugin(PluginType.PUMP) as PumpInterface
(activePump as PluginBase).setPluginEnabled(PluginType.PUMP, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting PumpInterface")
}
setFragmentVisiblities((activePump as PluginBase).name, pluginsInCategory, PluginType.PUMP)
// PluginType.TREATMENT
pluginsInCategory = getSpecificPluginsList(PluginType.TREATMENT)
activeTreatments = getTheOneEnabledInArray(pluginsInCategory, PluginType.TREATMENT) as TreatmentsInterface?
if (activeTreatments == null) {
activeTreatments = getDefaultPlugin(PluginType.TREATMENT) as TreatmentsInterface
(activeTreatments as PluginBase).setPluginEnabled(PluginType.TREATMENT, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting PumpInterface")
}
setFragmentVisiblities((activeTreatments as PluginBase).name, pluginsInCategory, PluginType.TREATMENT)
}
/**
* disables the visibility for all fragments of Plugins with the given PluginType
* which are not equally named to the Plugin implementing the given Plugin Interface.
*
* @param pluginInterface
* @param pluginType
* @param <T>
* @return
</T> */
private fun <T> determineActivePlugin(pluginInterface: Class<T>, pluginType: PluginType): T? {
val pluginsInCategory: ArrayList<PluginBase>
pluginsInCategory = pluginStore!!.getSpecificPluginsListByInterface(pluginInterface)
return determineActivePlugin(pluginsInCategory, pluginType)
}
/**
* disables the visibility for all fragments of Plugins in the given pluginsInCategory
* with the given PluginType which are not equally named to the Plugin implementing the
* given Plugin Interface.
*
*
* TODO we are casting an interface to PluginBase, which seems to be rather odd, since
* TODO the interface is not implementing PluginBase (this is just avoiding errors through
* TODO conventions.
*
* @param pluginsInCategory
* @param pluginType
* @param <T>
* @return
</T> */
private fun <T> determineActivePlugin(pluginsInCategory: ArrayList<PluginBase>,
pluginType: PluginType): T? {
val activePlugin = getTheOneEnabledInArray(pluginsInCategory, pluginType) as T?
if (activePlugin != null) {
setFragmentVisiblities((activePlugin as PluginBase).name, pluginsInCategory, pluginType)
}
return activePlugin
}
private fun setFragmentVisiblities(activePluginName: String, pluginsInCategory: ArrayList<PluginBase>,
pluginType: PluginType) {
aapsLogger.debug(LTag.CONFIGBUILDER, "Selected interface: $activePluginName")
for (p in pluginsInCategory)
if (p.name != activePluginName)
p.setFragmentVisible(pluginType, false)
}
private fun getTheOneEnabledInArray(pluginsInCategory: ArrayList<PluginBase>, type: PluginType): PluginBase? {
var found: PluginBase? = null
for (p in pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p
} else if (p.isEnabled(type)) {
// set others disabled
p.setPluginEnabled(type, false)
}
}
return found
}
// ***** Interface *****
override fun getActiveBgSource(): BgSourceInterface {
return activeBgSource ?: checkNotNull(activeBgSource) { "No bg source selected" }
}
override fun getActiveProfileInterface(): ProfileInterface =
activeProfile ?: checkNotNull(activeProfile) { "No profile selected" }
override fun getActiveInsulin(): InsulinInterface =
activeInsulin ?: checkNotNull(activeInsulin) { "No insulin selected" }
override fun getActiveAPS(): APSInterface =
activeAPS ?: checkNotNull(activeAPS) { "No APS selected" }
override fun getActivePump(): PumpInterface =
activePump ?: checkNotNull(activePump) { "No pump selected" }
override fun getActiveSensitivity(): SensitivityInterface =
activeSensitivity ?: checkNotNull(activeSensitivity) { "No sensitivity selected" }
override fun getActiveTreatments(): TreatmentsInterface =
activeTreatments ?: checkNotNull(activeTreatments) { "No treatments selected" }
override fun getPluginsList(): ArrayList<PluginBase> = plugins
}

View file

@ -1,11 +1,20 @@
package info.nightscout.androidaps.plugins.configBuilder
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.security.spec.InvalidParameterSpecException
import javax.inject.Inject
@ -13,7 +22,11 @@ import javax.inject.Singleton
@Singleton
class ProfileFunctionImplementation @Inject constructor(
private val sp: SP
private val injector: HasAndroidInjector,
private val aapsLogger: AAPSLogger,
private val sp: SP,
private val resourceHelper: ResourceHelper,
private val activePlugin: ActivePluginProvider
) : ProfileFunction {
override fun getProfileName(): String =
@ -22,8 +35,30 @@ class ProfileFunctionImplementation @Inject constructor(
override fun getProfileName(customized: Boolean): String =
getProfileName(System.currentTimeMillis(), customized, showRemainingTime = false)
override fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String =
ProfileFunctions.getInstance().getProfileName(time, customized, showRemainingTime)
override fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String {
var profileName = resourceHelper.gs(R.string.noprofileselected)
val activeTreatments = activePlugin.activeTreatments
val activeProfile = activePlugin.activeProfileInterface
val profileSwitch = activeTreatments.getProfileSwitchFromHistory(time)
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
profileName = if (customized) profileSwitch.customizedName else profileSwitch.profileName
} else {
activeProfile.profile?.let { profileStore ->
val profile = profileStore.getSpecificProfile(profileSwitch.profileName)
if (profile != null)
profileName = profileSwitch.profileName
}
}
if (showRemainingTime && profileSwitch.durationInMinutes != 0) {
profileName += DateUtil.untilString(profileSwitch.originalEnd(), resourceHelper);
}
}
return profileName;
}
override fun getProfileNameWithDuration(): String =
getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true)
@ -31,12 +66,34 @@ class ProfileFunctionImplementation @Inject constructor(
override fun isProfileValid(from: String): Boolean =
getProfile()?.isValid(from) ?: false
override fun getProfile(): Profile? {
return ProfileFunctions.getInstance().getProfile()
}
override fun getProfile(): Profile? =
getProfile(System.currentTimeMillis())
override fun getProfile(time: Long): Profile? =
ProfileFunctions.getInstance().getProfile(System.currentTimeMillis())
override fun getProfile(time: Long): Profile? {
val activeTreatments = activePlugin.activeTreatments
val activeProfile = activePlugin.activeProfileInterface
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
val profileSwitch = activeTreatments.getProfileSwitchFromHistory(time)
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return profileSwitch.profileObject
} else if (activeProfile.profile != null) {
val profile = activeProfile.profile!!.getSpecificProfile(profileSwitch.profileName)
if (profile != null) return profile
}
}
if (activeTreatments.profileSwitchesFromHistory.size() > 0) {
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "CatchedError")
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, BuildConfig.BUILDVERSION)
bundle.putString(FirebaseAnalytics.Param.START_DATE, time.toString())
bundle.putString(FirebaseAnalytics.Param.VALUE, activeTreatments.profileSwitchesFromHistory.toString())
FabricPrivacy.getInstance().logCustom(bundle)
}
aapsLogger.error("getProfile at the end: returning null")
return null
}
override fun getUnits(): String =
sp.getString(R.string.key_units, Constants.MGDL)
@ -44,7 +101,7 @@ class ProfileFunctionImplementation @Inject constructor(
override fun prepareProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long): ProfileSwitch {
val profile = profileStore.getSpecificProfile(profileName)
?: throw InvalidParameterSpecException(profileName)
val profileSwitch = ProfileSwitch()
val profileSwitch = ProfileSwitch(injector)
profileSwitch.date = date
profileSwitch.source = Source.USER
profileSwitch.profileName = profileName

View file

@ -1,188 +0,0 @@
package info.nightscout.androidaps.plugins.configBuilder;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
public class ProfileFunctions implements ProfileFunction {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.PROFILE);
private CompositeDisposable disposable = new CompositeDisposable();
private static ProfileFunctions profileFunctions = null;
@Deprecated
public static ProfileFunctions getInstance() {
if (profileFunctions == null)
profileFunctions = new ProfileFunctions();
return profileFunctions;
}
static {
ProfileFunctions.getInstance(); // register to bus at start
}
private ProfileFunctions() {
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventProfileNeedsUpdate.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
if (L.isEnabled(L.PROFILE))
log.debug("onProfileSwitch");
ConfigBuilderPlugin.getPlugin().getCommandQueue().setProfile(getProfile(), new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
if (result.enacted)
RxBus.Companion.getINSTANCE().send(new EventNewBasalProfile());
}
});
}, exception -> FabricPrivacy.getInstance().logException(exception))
);
}
@NotNull
public String getProfileName() {
return getProfileName(System.currentTimeMillis(), true, false);
}
@NotNull
public String getProfileName(boolean customized) {
return getProfileName(System.currentTimeMillis(), customized, false);
}
@NotNull
public String getProfileNameWithDuration() {
return getProfileName(System.currentTimeMillis(), true, true);
}
@NotNull
public String getProfileName(long time, boolean customized, boolean showRemainingTime) {
String profileName = MainApp.gs(R.string.noprofileselected);
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
profileName = customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
profileName = profileSwitch.profileName;
}
}
if (showRemainingTime && profileSwitch.durationInMinutes != 0) {
profileName += DateUtil.untilString(profileSwitch.originalEnd());
}
return profileName;
}
return profileName;
}
public boolean isProfileValid(@NotNull String from) {
Profile profile = getProfile();
return profile != null && profile.isValid(from);
}
@Nullable
public Profile getProfile() {
return getProfile(System.currentTimeMillis());
}
@NotNull
public String getUnits() {
return getSystemUnits();
}
@NotNull
@Deprecated
public static String getSystemUnits() {
return SP.getString(R.string.key_units, Constants.MGDL);
}
@Nullable
public Profile getProfile(long time) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return profileSwitch.getProfileObject();
} else if (activeProfile.getProfile() != null) {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profile;
}
}
if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "CatchedError");
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, BuildConfig.BUILDVERSION);
bundle.putString(FirebaseAnalytics.Param.START_DATE, String.valueOf(time));
bundle.putString(FirebaseAnalytics.Param.VALUE, activeTreatments.getProfileSwitchesFromHistory().toString());
FabricPrivacy.getInstance().logCustom(bundle);
}
log.error("getProfile at the end: returning null");
return null;
}
@NotNull
public ProfileSwitch prepareProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, long date) {
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = date;
profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeShift != 0;
profileSwitch.timeshift = timeShift;
profileSwitch.percentage = percentage;
return profileSwitch;
}
}

View file

@ -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 {
@ -42,7 +42,7 @@ class DstHelperPlugin @Inject constructor(
//Return false if time to DST change happened in the last 3 hours.
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val pump = activePlugin.activePumpPlugin ?: return value
val pump = activePlugin.activePump
if (pump.canHandleDST()) {
aapsLogger.debug(LTag.CONSTRAINTS, "Pump can handle DST")
return value
@ -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
}

View file

@ -7,11 +7,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
@ -25,10 +21,10 @@ import javax.inject.Singleton
@Singleton
class ObjectivesPlugin @Inject constructor(
private val injector: HasAndroidInjector,
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
private val configBuilderPlugin: ConfigBuilderPlugin,
private val activePlugin: ActivePluginProvider,
private val sp: SP
) : PluginBase(PluginDescription()
@ -39,7 +35,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<Objective> = ArrayList()
@ -57,15 +53,14 @@ class ObjectivesPlugin @Inject constructor(
const val SMB_OBJECTIVE = 9
}
override fun onStart() {
public override fun onStart() {
super.onStart()
convertSP()
setupObjectives()
}
override fun specialEnableCondition(): Boolean {
val pump = configBuilderPlugin.activePumpPlugin
return pump == null || pump.pumpDescription.isTempBasalCapable
return activePlugin.activePump.pumpDescription.isTempBasalCapable
}
// convert 2.3 SP version
@ -90,16 +85,16 @@ class ObjectivesPlugin @Inject constructor(
private fun setupObjectives() {
objectives.clear()
objectives.add(Objective0())
objectives.add(Objective1())
objectives.add(Objective2())
objectives.add(Objective3())
objectives.add(Objective4())
objectives.add(Objective0(injector))
objectives.add(Objective1(injector))
objectives.add(Objective2(injector))
objectives.add(Objective3(injector))
objectives.add(Objective4(injector))
objectives.add(Objective5(injector))
objectives.add(Objective6())
objectives.add(Objective7())
objectives.add(Objective8())
objectives.add(Objective9())
objectives.add(Objective6(injector))
objectives.add(Objective7(injector))
objectives.add(Objective8(injector))
objectives.add(Objective9(injector))
}
fun reset() {
@ -151,37 +146,37 @@ class ObjectivesPlugin @Inject constructor(
*/
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[FIRST_OBJECTIVE].isStarted)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this)
value.set(aapsLogger, false, String.format(resourceHelper.gs(R.string.objectivenotstarted), FIRST_OBJECTIVE + 1), this)
return value
}
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
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, String.format(resourceHelper.gs(R.string.objectivenotstarted), MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
return value
}
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[AUTOSENS_OBJECTIVE].isStarted)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this)
value.set(aapsLogger, false, String.format(resourceHelper.gs(R.string.objectivenotstarted), AUTOSENS_OBJECTIVE + 1), this)
return value
}
override fun isAMAModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[AMA_OBJECTIVE].isStarted)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, AMA_OBJECTIVE + 1), this)
value.set(aapsLogger, false, String.format(resourceHelper.gs(R.string.objectivenotstarted), AMA_OBJECTIVE + 1), this)
return value
}
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[SMB_OBJECTIVE].isStarted)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this)
value.set(aapsLogger, false, String.format(resourceHelper.gs(R.string.objectivenotstarted), SMB_OBJECTIVE + 1), this)
return value
}
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
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, String.format(resourceHelper.gs(R.string.objectivenotfinished), MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
return maxIob
}
}

View file

@ -4,7 +4,6 @@ import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.util.Linkify;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
@ -13,30 +12,35 @@ import androidx.annotation.StringRes;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public abstract class Objective {
@Inject public SP sp;
@Inject public ResourceHelper resourceHelper;
private String spName;
@StringRes
private int objective;
@StringRes
private int gate;
@StringRes private int objective;
@StringRes private int gate;
private long startedOn;
private long accomplishedOn;
List<Task> tasks = new ArrayList<>();
public boolean hasSpecialInput = false;
public Objective(String spName, @StringRes int objective, @StringRes int gate) {
public Objective(HasAndroidInjector injector, String spName, @StringRes int objective, @StringRes int gate) {
injector.androidInjector().inject(this);
this.spName = spName;
this.objective = objective;
this.gate = gate;
startedOn = SP.getLong("Objectives_" + spName + "_started", 0L);
accomplishedOn = SP.getLong("Objectives_" + spName + "_accomplished", 0L);
startedOn = sp.getLong("Objectives_" + spName + "_started", 0L);
accomplishedOn = sp.getLong("Objectives_" + spName + "_accomplished", 0L);
if ((accomplishedOn - DateUtil.now()) > T.hours(3).msecs() || (startedOn - DateUtil.now()) > T.hours(3).msecs()) { // more than 3 hours in the future
startedOn = 0;
accomplishedOn = 0;
@ -83,12 +87,12 @@ public abstract class Objective {
public void setStartedOn(long startedOn) {
this.startedOn = startedOn;
SP.putLong("Objectives_" + spName + "_started", startedOn);
sp.putLong("Objectives_" + spName + "_started", startedOn);
}
public void setAccomplishedOn(long accomplishedOn) {
this.accomplishedOn = accomplishedOn;
SP.putLong("Objectives_" + spName + "_accomplished", accomplishedOn);
sp.putLong("Objectives_" + spName + "_accomplished", accomplishedOn);
}
public long getAccomplishedOn() {
@ -103,9 +107,12 @@ public abstract class Objective {
return tasks;
}
public boolean specialActionEnabled() { return true; }
public boolean specialActionEnabled() {
return true;
}
public void specialAction(Activity activity, String input) {}
public void specialAction(Activity activity, String input) {
}
public abstract class Task {
@StringRes
@ -126,7 +133,12 @@ public abstract class Objective {
}
public abstract boolean isCompleted();
public boolean isCompleted(long trueTime) { return isCompleted(); };
public boolean isCompleted(long trueTime) {
return isCompleted();
}
;
public String getProgress() {
return MainApp.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet);
@ -175,9 +187,9 @@ public abstract class Objective {
int days = (int) Math.floor((double) duration / T.days(1).msecs());
int hours = (int) Math.floor((double) duration / T.hours(1).msecs());
int minutes = (int) Math.floor((double) duration / T.mins(1).msecs());
if (days > 0) return MainApp.gq(R.plurals.objective_days, days, days);
else if (hours > 0) return MainApp.gq(R.plurals.objective_hours, hours, hours);
else return MainApp.gq(R.plurals.objective_minutes, minutes, minutes);
if (days > 0) return resourceHelper.gq(R.plurals.objective_days, days, days);
else if (hours > 0) return resourceHelper.gq(R.plurals.objective_hours, hours, hours);
else return resourceHelper.gq(R.plurals.objective_minutes, minutes, minutes);
}
}
@ -193,13 +205,13 @@ public abstract class Objective {
super(task);
this.question = question;
this.spIdentifier = spIdentifier;
answered = SP.getBoolean("ExamTask_" + spIdentifier, false);
disabledTo = SP.getLong("DisabledTo_" + spIdentifier, 0L);
answered = sp.getBoolean("ExamTask_" + spIdentifier, false);
disabledTo = sp.getLong("DisabledTo_" + spIdentifier, 0L);
}
public void setDisabledTo(long newState) {
disabledTo = newState;
SP.putLong("DisabledTo_" + spIdentifier, disabledTo);
sp.putLong("DisabledTo_" + spIdentifier, disabledTo);
}
public long getDisabledTo() {
@ -212,7 +224,7 @@ public abstract class Objective {
public void setAnswered(boolean newState) {
answered = newState;
SP.putBoolean("ExamTask_" + spIdentifier, answered);
sp.putBoolean("ExamTask_" + spIdentifier, answered);
}
public boolean getAnswered() {

View file

@ -4,13 +4,13 @@ import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
@ -20,16 +20,15 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class Objective0 extends Objective {
@Inject SP sp;
@Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject ActivePluginProvider activePlugin;
@Inject VirtualPumpPlugin virtualPumpPlugin;
@Inject TreatmentsPlugin treatmentsPlugin;
@Inject LoopPlugin loopPlugin;
@Inject NSClientPlugin nsClientPlugin;
@Inject IobCobCalculatorPlugin iobCobCalculatorPlugin;
public Objective0() {
super("config", R.string.objectives_0_objective, R.string.objectives_0_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
public Objective0(HasAndroidInjector injector) {
super(injector, "config", R.string.objectives_0_objective, R.string.objectives_0_gate);
}
@Override
@ -78,8 +77,8 @@ public class Objective0 extends Objective {
tasks.add(new Task(R.string.apsselected) {
@Override
public boolean isCompleted() {
APSInterface usedAPS = configBuilderPlugin.getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS))
APSInterface usedAPS = activePlugin.getActiveAPS();
if (((PluginBase) usedAPS).isEnabled(PluginType.APS))
return true;
return false;
}

View file

@ -4,7 +4,7 @@ import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
@ -15,9 +15,8 @@ public class Objective1 extends Objective {
@Inject ActionsPlugin actionsPlugin;
@Inject
public Objective1() {
super("usage", R.string.objectives_usage_objective, R.string.objectives_usage_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once ActionsPlugin is prepared for Dagger
public Objective1(HasAndroidInjector injector) {
super(injector, "usage", R.string.objectives_usage_objective, R.string.objectives_usage_gate);
}
@Override

View file

@ -3,15 +3,15 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.Collections;
import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
public class Objective2 extends Objective {
public Objective2() {
super("exam", R.string.objectives_exam_objective, R.string.objectives_exam_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
public Objective2(HasAndroidInjector injector) {
super(injector, "exam", R.string.objectives_exam_objective, R.string.objectives_exam_gate);
for (Task task : tasks) {
if (!task.isCompleted()) setAccomplishedOn(0);
}

View file

@ -6,7 +6,7 @@ import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
@ -23,9 +23,8 @@ public class Objective3 extends Objective {
private final int MANUAL_ENACTS_NEEDED = 20;
@Inject
public Objective3() {
super("openloop", R.string.objectives_openloop_objective, R.string.objectives_openloop_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
public Objective3(HasAndroidInjector injector) {
super(injector, "openloop", R.string.objectives_openloop_objective, R.string.objectives_openloop_gate);
hasSpecialInput = true;
}

View file

@ -1,10 +1,11 @@
package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
public class Objective4 extends Objective {
public Objective4() {
super("maxbasal", R.string.objectives_maxbasal_objective, R.string.objectives_maxbasal_gate);
public Objective4(HasAndroidInjector injector) {
super(injector, "maxbasal", R.string.objectives_maxbasal_objective, R.string.objectives_maxbasal_gate);
}
}

View file

@ -14,8 +14,7 @@ public class Objective5 extends Objective {
@Inject SafetyPlugin safetyPlugin;
public Objective5(HasAndroidInjector injector) {
super("maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate);
injector.androidInjector().inject(this);
super(injector, "maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate);
}
@Override

View file

@ -4,7 +4,7 @@ import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.utils.T;
@ -12,9 +12,8 @@ import info.nightscout.androidaps.utils.T;
public class Objective6 extends Objective {
@Inject ConstraintChecker constraintChecker;
public Objective6() {
super("maxiob", R.string.objectives_maxiob_objective, R.string.objectives_maxiob_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
public Objective6(HasAndroidInjector injector) {
super(injector, "maxiob", R.string.objectives_maxiob_objective, R.string.objectives_maxiob_gate);
}
@Override

View file

@ -2,14 +2,14 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.utils.T;
public class Objective7 extends Objective {
public Objective7() {
super("autosens", R.string.objectives_autosens_objective, R.string.objectives_autosens_gate);
public Objective7(HasAndroidInjector injector) {
super(injector, "autosens", R.string.objectives_autosens_objective, R.string.objectives_autosens_gate);
}
@Override

View file

@ -2,14 +2,14 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.utils.T;
public class Objective8 extends Objective {
public Objective8() {
super("ama", R.string.objectives_ama_objective, 0);
public Objective8(HasAndroidInjector injector) {
super(injector, "ama", R.string.objectives_ama_objective, 0);
}
@Override

View file

@ -2,13 +2,14 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.T;
public class Objective9 extends Objective {
public Objective9() {
super("smb", R.string.objectives_smb_objective, R.string.objectives_smb_gate);
public Objective9(HasAndroidInjector injector) {
super(injector, "smb", R.string.objectives_smb_objective, R.string.objectives_smb_gate);
}
@Override

View file

@ -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

View file

@ -5,8 +5,8 @@ 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;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
@ -31,33 +31,62 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.buildHelper.BuildHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton
public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
// TODO: dagger
@Inject SP sp;
@Inject RxBusWrapper rxBus;
@Inject ResourceHelper resourceHelper;
@Inject ConstraintChecker constraintChecker;
@Inject OpenAPSAMAPlugin openAPSAMAPlugin;
@Inject OpenAPSMAPlugin openAPSMAPlugin;
@Inject OpenAPSSMBPlugin openAPSSMBPlugin;
@Inject SensitivityOref1Plugin sensitivityOref1Plugin;
@Inject ActivePluginProvider activePlugin;
private SP sp;
private RxBusWrapper rxBus;
private ConstraintChecker constraintChecker;
private OpenAPSAMAPlugin openAPSAMAPlugin;
private OpenAPSMAPlugin openAPSMAPlugin;
private OpenAPSSMBPlugin openAPSSMBPlugin;
private SensitivityOref1Plugin sensitivityOref1Plugin;
private ActivePluginProvider activePlugin;
private HardLimits hardLimits;
private BuildHelper buildHelper;
private TreatmentsPlugin treatmentsPlugin;
@Inject
public SafetyPlugin(AAPSLogger aapsLogger, ResourceHelper resourceHelper) {
public SafetyPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
ResourceHelper resourceHelper,
SP sp,
RxBusWrapper rxBus,
ConstraintChecker constraintChecker,
OpenAPSAMAPlugin openAPSAMAPlugin,
OpenAPSMAPlugin openAPSMAPlugin,
OpenAPSSMBPlugin openAPSSMBPlugin,
SensitivityOref1Plugin sensitivityOref1Plugin,
ActivePluginProvider activePlugin,
HardLimits hardLimits,
BuildHelper buildHelper,
TreatmentsPlugin treatmentsPlugin
) {
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
);
this.sp = sp;
this.rxBus = rxBus;
this.constraintChecker = constraintChecker;
this.openAPSAMAPlugin = openAPSAMAPlugin;
this.openAPSMAPlugin = openAPSMAPlugin;
this.openAPSSMBPlugin = openAPSSMBPlugin;
this.sensitivityOref1Plugin = sensitivityOref1Plugin;
this.activePlugin = activePlugin;
this.hardLimits = hardLimits;
this.buildHelper = buildHelper;
this.treatmentsPlugin = treatmentsPlugin;
}
/**
@ -65,8 +94,8 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
**/
@NonNull @Override
public Constraint<Boolean> isLoopInvocationAllowed(@NonNull Constraint<Boolean> value) {
if (!activePlugin.getActivePumpPlugin().getPumpDescription().isTempBasalCapable)
value.set(false, resourceHelper.gs(R.string.pumpisnottempbasalcapable), this);
if (!activePlugin.getActivePump().getPumpDescription().isTempBasalCapable)
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.pumpisnottempbasalcapable), this);
return value;
}
@ -74,18 +103,18 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isClosedLoopAllowed(@NonNull Constraint<Boolean> 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, getResourceHelper().gs(R.string.closedmodedisabledinpreferences), this);
if (!MainApp.isEngineeringModeOrRelease()) {
if (!buildHelper.isEngineeringModeOrRelease()) {
if (value.value()) {
Notification n = new Notification(Notification.TOAST_ALARM, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL);
Notification n = new Notification(Notification.TOAST_ALARM, getResourceHelper().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, getResourceHelper().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);
PumpInterface pump = activePlugin.getActivePump();
if (!pump.isFakingTempsByExtendedBoluses() && treatmentsPlugin.isInHistoryExtendedBoluslInProgress()) {
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closed_loop_disabled_with_eb), this);
}
return value;
}
@ -94,7 +123,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isAutosensModeEnabled(@NonNull Constraint<Boolean> 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, getResourceHelper().gs(R.string.autosensdisabledinpreferences), this);
return value;
}
@ -102,10 +131,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isSMBModeEnabled(@NonNull Constraint<Boolean> 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, getResourceHelper().gs(R.string.smbdisabledinpreferences), this);
Constraint<Boolean> closedLoop = constraintChecker.isClosedLoopAllowed();
if (!closedLoop.value())
value.set(false, resourceHelper.gs(R.string.smbnotallowedinopenloopmode), this);
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbnotallowedinopenloopmode), this);
return value;
}
@ -113,10 +142,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isUAMEnabled(@NonNull Constraint<Boolean> 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, getResourceHelper().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, getResourceHelper().gs(R.string.uamdisabledoref1notselected), this);
return value;
}
@ -124,48 +153,46 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isAdvancedFilteringEnabled(@NonNull Constraint<Boolean> value) {
BgSourceInterface bgSource = activePlugin.getActiveBgSource();
if (bgSource != null) {
if (!bgSource.advancedFilteringSupported())
value.set(false, resourceHelper.gs(R.string.smbalwaysdisabled), this);
}
if (!bgSource.advancedFilteringSupported())
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbalwaysdisabled), this);
return value;
}
@NonNull @Override
public Constraint<Double> applyBasalConstraints(Constraint<Double> 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(getResourceHelper().gs(R.string.limitingbasalratio), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
if (Config.APS) {
double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d);
if (maxBasal < profile.getMaxDailyBasal()) {
maxBasal = profile.getMaxDailyBasal();
absoluteRate.addReason(resourceHelper.gs(R.string.increasingmaxbasal), this);
absoluteRate.addReason(getResourceHelper().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(getResourceHelper().gs(R.string.limitingbasalratio), maxBasal, getResourceHelper().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 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(getResourceHelper().gs(R.string.limitingbasalratio), maxFromBasalMult, getResourceHelper().gs(R.string.maxbasalmultiplier)), this);
Double maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3d);
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(getResourceHelper().gs(R.string.limitingbasalratio), maxFromDaily, getResourceHelper().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(getResourceHelper().gs(R.string.limitingbasalratio), hardLimits.maxBasal(), getResourceHelper().gs(R.string.hardlimit)), this);
PumpInterface pump = activePlugin.getActivePumpPlugin();
PumpInterface pump = activePlugin.getActivePump();
// check for pump max
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
if (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(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().gs(R.string.pumplimit)), this);
}
// do rounding
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
absoluteRate.set(Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep));
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
absoluteRate.set(getAapsLogger(), Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep));
}
return absoluteRate;
}
@ -174,7 +201,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) {
Double currentBasal = profile.getBasal();
Double absoluteRate = currentBasal * ((double) percentRate.originalValue() / 100);
double absoluteRate = currentBasal * ((double) percentRate.originalValue() / 100);
percentRate.addReason("Percent rate " + percentRate.originalValue() + "% recalculated to " + DecimalFormatter.to2Decimal(absoluteRate) + " U/h with current basal " + DecimalFormatter.to2Decimal(currentBasal) + " U/h", this);
@ -182,21 +209,19 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
applyBasalConstraints(absoluteConstraint, profile);
percentRate.copyReasons(absoluteConstraint);
PumpInterface pump = activePlugin.getActivePumpPlugin();
PumpInterface pump = activePlugin.getActivePump();
Integer percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue();
if (pump != null) {
if (percentRateAfterConst < 100)
percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
else
percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
}
int percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue();
if (percentRateAfterConst < 100)
percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
else
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(getResourceHelper().gs(R.string.limitingpercentrate), percentRateAfterConst, getResourceHelper().gs(R.string.pumplimit)), this);
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
if (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(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().gs(R.string.pumplimit)), this);
}
return percentRate;
@ -204,44 +229,40 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
@NonNull @Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) {
insulin.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this);
insulin.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingbolus), 0d, getResourceHelper().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(getResourceHelper().gs(R.string.limitingbolus), maxBolus, getResourceHelper().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(getResourceHelper().gs(R.string.limitingbolus), hardLimits.maxBolus(), getResourceHelper().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);
}
PumpInterface pump = activePlugin.getActivePump();
double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value());
insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this);
return insulin;
}
@NonNull @Override
public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
insulin.setIfGreater(0d, String.format(resourceHelper.gs(R.string.limitingextendedbolus), 0d, resourceHelper.gs(R.string.itmustbepositivevalue)), this);
insulin.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingextendedbolus), 0d, getResourceHelper().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(getResourceHelper().gs(R.string.limitingextendedbolus), maxBolus, getResourceHelper().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(getResourceHelper().gs(R.string.limitingextendedbolus), hardLimits.maxBolus(), getResourceHelper().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);
}
PumpInterface pump = activePlugin.getActivePump();
double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value());
insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this);
return insulin;
}
@NonNull @Override
public Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) {
carbs.setIfGreater(0, String.format(resourceHelper.gs(R.string.limitingcarbs), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this);
carbs.setIfGreater(getAapsLogger(), 0, String.format(getResourceHelper().gs(R.string.limitingcarbs), 0, getResourceHelper().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(getResourceHelper().gs(R.string.limitingcarbs), maxCarbs, getResourceHelper().gs(R.string.maxvalueinpreferences)), this);
return carbs;
}
@ -253,14 +274,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(getResourceHelper().gs(R.string.limitingiob), maxIobPref, getResourceHelper().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(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobAMA(), getResourceHelper().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(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobAMA(), getResourceHelper().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(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobSMB(), getResourceHelper().gs(R.string.hardlimit)), this);
return maxIob;
}

View file

@ -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<Any>(0)
private var revokedCertsFile: File? = null
private var revokedCerts: List<ByteArray>? = 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<Boolean>): Constraint<Boolean> {
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)
}
}

View file

@ -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<Boolean>): Constraint<Boolean> {
val diskFree = availableInternalMemorySize
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 {
@ -46,13 +48,12 @@ open class StorageConstraintPlugin @Inject constructor(
return value
}
val availableInternalMemorySize: Long
get() {
val path = Environment.getDataDirectory()
val stat = StatFs(path.path)
val blockSize = stat.blockSizeLong
val blocksAvailable = stat.availableBlocksLong
val size = 1048576 // block size of 1 Mb
return blocksAvailable * blockSize / size
}
open fun availableInternalMemorySize(): Long {
val path = Environment.getDataDirectory()
val stat = StatFs(path.path)
val blockSize = stat.blockSizeLong
val blocksAvailable = stat.availableBlocksLong
val size = 1048576 // block size of 1 Mb
return blocksAvailable * blockSize / size
}
}

View file

@ -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<Double>): Constraint<Double> =
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

View file

@ -19,17 +19,17 @@ import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class VersionCheckerUtils @Inject constructor() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
class VersionCheckerUtils @Inject constructor(
val aapsLogger: AAPSLogger,
val sp: SP,
val resourceHelper: ResourceHelper,
val rxBus: RxBusWrapper,
val context: Context
) {
// check network connection
fun isConnected(): Boolean {
val connMgr = mainApp.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connMgr.activeNetworkInfo?.isConnected ?: false
}
@ -113,8 +113,6 @@ class VersionCheckerUtils @Inject constructor() {
}
}
private fun String?.toNumberList() =
this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction
@ -27,6 +27,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SingleClickButton
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -35,11 +36,11 @@ import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.actions_fragment.*
import kotlinx.android.synthetic.main.careportal_stats_fragment.*
import org.slf4j.LoggerFactory
import java.util.*
import javax.inject.Inject
class ActionsFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction
@ -49,7 +50,7 @@ class ActionsFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var commandQueue: CommandQueueProvider
private val log = LoggerFactory.getLogger(L.CORE)
@Inject lateinit var buildHelper: BuildHelper
private var disposable: CompositeDisposable = CompositeDisposable()
@ -80,7 +81,7 @@ class ActionsFragment : DaggerFragment() {
}
actions_extendedbolus_cancel.setOnClickListener {
if (activePlugin.activeTreatments.isInHistoryExtendedBoluslInProgress) {
log.debug("USER ENTRY: CANCEL EXTENDED BOLUS")
aapsLogger.debug("USER ENTRY: CANCEL EXTENDED BOLUS")
commandQueue.cancelExtended(object : Callback() {
override fun run() {
if (!result.success) {
@ -100,7 +101,7 @@ class ActionsFragment : DaggerFragment() {
}
actions_canceltempbasal.setOnClickListener {
if (activePlugin.activeTreatments.isTempBasalInProgress) {
log.debug("USER ENTRY: CANCEL TEMP BASAL")
aapsLogger.debug("USER ENTRY: CANCEL TEMP BASAL")
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (!result.success) {
@ -180,19 +181,18 @@ class ActionsFragment : DaggerFragment() {
else View.GONE
val profile = profileFunction.getProfile()
val pump = activePlugin.activePumpPlugin
val pump = activePlugin.activePump
actions_temptarget?.visibility = (profile != null).toVisibility()
actions_canceltempbasal.visibility = (pump != null || profile == null).toVisibility()
actions_settempbasal.visibility = (pump != null || profile == null).toVisibility()
actions_fill.visibility = (pump != null || profile == null).toVisibility()
actions_extendedbolus.visibility = (pump != null || profile == null).toVisibility()
actions_extendedbolus_cancel.visibility = (pump != null || profile == null).toVisibility()
actions_historybrowser.visibility = (pump != null || profile == null).toVisibility()
actions_tddstats.visibility = (pump != null || profile == null).toVisibility()
if (pump == null) return
actions_canceltempbasal.visibility = (profile == null).toVisibility()
actions_settempbasal.visibility = (profile == null).toVisibility()
actions_fill.visibility = (profile == null).toVisibility()
actions_extendedbolus.visibility = (profile == null).toVisibility()
actions_extendedbolus_cancel.visibility = (profile == null).toVisibility()
actions_historybrowser.visibility = (profile == null).toVisibility()
actions_tddstats.visibility = (profile == null).toVisibility()
val basalProfileEnabled = MainApp.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE
@ -239,7 +239,7 @@ class ActionsFragment : DaggerFragment() {
}
private fun checkPumpCustomActions() {
val activePump = activePlugin.activePumpPlugin ?: return
val activePump = activePlugin.activePump
val customActions = activePump.customActions ?: return
removePumpCustomActions()

View file

@ -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
)

View file

@ -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()

View file

@ -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()
}
}
}

View file

@ -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()
}
}

View file

@ -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()
}
}
}

View file

@ -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()
}
}

View file

@ -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 {

View file

@ -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) {

View file

@ -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) {

View file

@ -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 {

View file

@ -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) {

View file

@ -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()
}
}

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