PluginStore

This commit is contained in:
Milos Kozak 2020-03-16 21:40:29 +01:00
parent 74a0890d34
commit 66bea16bdf
98 changed files with 1107 additions and 1247 deletions

View file

@ -37,7 +37,6 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.activities.PreferencesActivity; import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.activities.SingleFragmentActivity; 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.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRebuildTabs; 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.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
@ -84,6 +85,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
@Inject LoopPlugin loopPlugin; @Inject LoopPlugin loopPlugin;
@Inject NSSettingsStatus nsSettingsStatus; @Inject NSSettingsStatus nsSettingsStatus;
@Inject BuildHelper buildHelper; @Inject BuildHelper buildHelper;
@Inject ActivePluginProvider activePlugin;
@Override @Override
@ -205,14 +207,14 @@ public class MainActivity extends NoSplashAppCompatActivity {
navigationView.setNavigationItemSelectedListener(menuItem -> true); navigationView.setNavigationItemSelectedListener(menuItem -> true);
Menu menu = navigationView.getMenu(); Menu menu = navigationView.getMenu();
menu.clear(); menu.clear();
for (PluginBase p : MainApp.getPluginsList()) { for (PluginBase p : activePlugin.getPluginsList()) {
pageAdapter.registerNewFragment(p); pageAdapter.registerNewFragment(p);
if (p.hasFragment() && !p.isFragmentVisible() && p.isEnabled(p.getPluginDescription().getType()) && !p.getPluginDescription().neverVisible) { if (p.hasFragment() && !p.isFragmentVisible() && p.isEnabled(p.getPluginDescription().getType()) && !p.getPluginDescription().neverVisible) {
MenuItem menuItem = menu.add(p.getName()); MenuItem menuItem = menu.add(p.getName());
menuItem.setCheckable(true); menuItem.setCheckable(true);
menuItem.setOnMenuItemClickListener(item -> { menuItem.setOnMenuItemClickListener(item -> {
Intent intent = new Intent(this, SingleFragmentActivity.class); Intent intent = new Intent(this, SingleFragmentActivity.class);
intent.putExtra("plugin", MainApp.getPluginsList().indexOf(p)); intent.putExtra("plugin", activePlugin.getPluginsList().indexOf(p));
startActivity(intent); startActivity(intent);
((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawers(); ((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawers();
return true; return true;

View file

@ -39,6 +39,7 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
@ -50,6 +51,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin; import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
@ -124,8 +126,6 @@ public class MainApp extends DaggerApplication {
static DatabaseHelper sDatabaseHelper = null; static DatabaseHelper sDatabaseHelper = null;
static ArrayList<PluginBase> pluginsList = new ArrayList<>();
static DataReceiver dataReceiver = new DataReceiver(); static DataReceiver dataReceiver = new DataReceiver();
TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver; TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver;
@ -133,6 +133,7 @@ public class MainApp extends DaggerApplication {
private int ONGOING_NOTIFICATION_ID = 4711; // 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) private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger)
@Inject PluginStore pluginStore;
@Inject public HasAndroidInjector injector; @Inject public HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject ActivityMonitor activityMonitor; @Inject ActivityMonitor activityMonitor;
@ -241,61 +242,61 @@ public class MainApp extends DaggerApplication {
versionCheckersUtils.triggerCheckVersion(); versionCheckersUtils.triggerCheckVersion();
// Register all tabs in app here // Register all tabs in app here
pluginsList.add(overviewPlugin); pluginStore.add(overviewPlugin);
pluginsList.add(iobCobCalculatorPlugin); pluginStore.add(iobCobCalculatorPlugin);
if (!Config.NSCLIENT) pluginsList.add(actionsPlugin); if (!Config.NSCLIENT) pluginStore.add(actionsPlugin);
pluginsList.add(insulinOrefRapidActingPlugin); pluginStore.add(insulinOrefRapidActingPlugin);
pluginsList.add(insulinOrefUltraRapidActingPlugin); pluginStore.add(insulinOrefUltraRapidActingPlugin);
pluginsList.add(insulinOrefFreePeakPlugin); pluginStore.add(insulinOrefFreePeakPlugin);
pluginsList.add(sensitivityOref0Plugin); pluginStore.add(sensitivityOref0Plugin);
pluginsList.add(sensitivityAAPSPlugin); pluginStore.add(sensitivityAAPSPlugin);
pluginsList.add(sensitivityWeightedAveragePlugin); pluginStore.add(sensitivityWeightedAveragePlugin);
pluginsList.add(sensitivityOref1Plugin); pluginStore.add(sensitivityOref1Plugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRPlugin); if (Config.PUMPDRIVERS) pluginStore.add(danaRPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRKoreanPlugin); if (Config.PUMPDRIVERS) pluginStore.add(danaRKoreanPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRv2Plugin); if (Config.PUMPDRIVERS) pluginStore.add(danaRv2Plugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRSPlugin); if (Config.PUMPDRIVERS) pluginStore.add(danaRSPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(localInsightPlugin); if (Config.PUMPDRIVERS) pluginStore.add(localInsightPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(comboPlugin); if (Config.PUMPDRIVERS) pluginStore.add(comboPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(medtronicPumpPlugin); if (Config.PUMPDRIVERS) pluginStore.add(medtronicPumpPlugin);
if (!Config.NSCLIENT) pluginsList.add(mdiPlugin); if (!Config.NSCLIENT) pluginStore.add(mdiPlugin);
if (!Config.NSCLIENT) pluginsList.add(virtualPumpPlugin); if (!Config.NSCLIENT) pluginStore.add(virtualPumpPlugin);
if (Config.NSCLIENT) pluginsList.add(careportalPlugin); if (Config.NSCLIENT) pluginStore.add(careportalPlugin);
if (Config.APS) pluginsList.add(loopPlugin); if (Config.APS) pluginStore.add(loopPlugin);
if (Config.APS) pluginsList.add(openAPSMAPlugin); if (Config.APS) pluginStore.add(openAPSMAPlugin);
if (Config.APS) pluginsList.add(openAPSAMAPlugin); if (Config.APS) pluginStore.add(openAPSAMAPlugin);
if (Config.APS) pluginsList.add(openAPSSMBPlugin); if (Config.APS) pluginStore.add(openAPSSMBPlugin);
pluginsList.add(nsProfilePlugin); pluginStore.add(nsProfilePlugin);
if (!Config.NSCLIENT) pluginsList.add(localProfilePlugin); if (!Config.NSCLIENT) pluginStore.add(localProfilePlugin);
pluginsList.add(treatmentsPlugin); pluginStore.add(treatmentsPlugin);
if (!Config.NSCLIENT) pluginsList.add(safetyPlugin); if (!Config.NSCLIENT) pluginStore.add(safetyPlugin);
if (!Config.NSCLIENT) pluginsList.add(versionCheckerPlugin); if (!Config.NSCLIENT) pluginStore.add(versionCheckerPlugin);
if (Config.APS) pluginsList.add(storageConstraintPlugin); if (Config.APS) pluginStore.add(storageConstraintPlugin);
if (Config.APS) pluginsList.add(signatureVerifierPlugin); if (Config.APS) pluginStore.add(signatureVerifierPlugin);
if (Config.APS) pluginsList.add(objectivesPlugin); if (Config.APS) pluginStore.add(objectivesPlugin);
pluginsList.add(xdripPlugin); pluginStore.add(xdripPlugin);
pluginsList.add(nSClientSourcePlugin); pluginStore.add(nSClientSourcePlugin);
pluginsList.add(mM640GPlugin); pluginStore.add(mM640GPlugin);
pluginsList.add(glimpPlugin); pluginStore.add(glimpPlugin);
pluginsList.add(dexcomPlugin); pluginStore.add(dexcomPlugin);
pluginsList.add(poctechPlugin); pluginStore.add(poctechPlugin);
pluginsList.add(tomatoPlugin); pluginStore.add(tomatoPlugin);
pluginsList.add(eversensePlugin); pluginStore.add(eversensePlugin);
pluginsList.add(randomBgPlugin); pluginStore.add(randomBgPlugin);
if (!Config.NSCLIENT) pluginsList.add(smsCommunicatorPlugin); if (!Config.NSCLIENT) pluginStore.add(smsCommunicatorPlugin);
pluginsList.add(foodPlugin); pluginStore.add(foodPlugin);
pluginsList.add(wearPlugin); pluginStore.add(wearPlugin);
pluginsList.add(statusLinePlugin); pluginStore.add(statusLinePlugin);
pluginsList.add(persistentNotificationPlugin); pluginStore.add(persistentNotificationPlugin);
pluginsList.add(nsClientPlugin); pluginStore.add(nsClientPlugin);
// if (engineeringMode) pluginsList.add(tidepoolPlugin); // if (engineeringMode) pluginsList.add(tidepoolPlugin);
pluginsList.add(maintenancePlugin); pluginStore.add(maintenancePlugin);
pluginsList.add(automationPlugin); pluginStore.add(automationPlugin);
pluginsList.add(dstHelperPlugin); pluginStore.add(dstHelperPlugin);
pluginsList.add(dataBroadcastPlugin); pluginStore.add(dataBroadcastPlugin);
pluginsList.add(configBuilderPlugin); pluginStore.add(configBuilderPlugin);
configBuilderPlugin.initialize(); configBuilderPlugin.initialize();
@ -396,68 +397,6 @@ public class MainApp extends DaggerApplication {
return firebaseAnalytics; 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;
}
// global Notification has been moved to MainApp because PersistentNotificationPlugin is initialized too late // global Notification has been moved to MainApp because PersistentNotificationPlugin is initialized too late
private void generateEmptyNotification() { private void generateEmptyNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

View file

@ -11,7 +11,6 @@ import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection import dagger.android.support.AndroidSupportInjection
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
@ -22,6 +21,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
@ -62,6 +62,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var pluginStore: PluginStore
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var danaRPlugin: DanaRPlugin @Inject lateinit var danaRPlugin: DanaRPlugin
@ -183,7 +184,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey) addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey)
} }
initSummary(preferenceScreen) initSummary(preferenceScreen)
for (plugin in MainApp.getPluginsList()) { for (plugin in pluginStore.plugins) {
plugin.preprocessPreferences(this) plugin.preprocessPreferences(this)
} }
} }
@ -254,7 +255,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
pref.dialogMessage = pref.dialogMessage pref.dialogMessage = pref.dialogMessage
pref.setSummary(pref.text) pref.setSummary(pref.text)
} else { } else {
for (plugin in MainApp.getPluginsList()) { for (plugin in pluginStore.plugins) {
plugin.updatePreferenceSummary(pref) plugin.updatePreferenceSummary(pref)
} }
} }

View file

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

View file

@ -239,8 +239,8 @@ public class Profile {
if (isValid) { if (isValid) {
// Check for hours alignment // Check for hours alignment
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
if (pump != null && !pump.getPumpDescription().is30minBasalRatesCapable) { if (!pump.getPumpDescription().is30minBasalRatesCapable) {
for (int index = 0; index < basal_v.size(); index++) { for (int index = 0; index < basal_v.size(); index++) {
long secondsFromMidnight = basal_v.keyAt(index); long secondsFromMidnight = basal_v.keyAt(index);
if (notify && secondsFromMidnight % 3600 != 0) { if (notify && secondsFromMidnight % 3600 != 0) {
@ -253,7 +253,6 @@ public class Profile {
} }
// Check for minimal basal value // Check for minimal basal value
if (pump != null) {
PumpDescription description = pump.getPumpDescription(); PumpDescription description = pump.getPumpDescription();
for (int i = 0; i < basal_v.size(); i++) { for (int i = 0; i < basal_v.size(); i++) {
if (basal_v.valueAt(i) < description.basalMinimumRate) { if (basal_v.valueAt(i) < description.basalMinimumRate) {
@ -266,12 +265,6 @@ public class Profile {
sendAboveMaximumNotification(from); sendAboveMaximumNotification(from);
} }
} }
} else {
// if pump not available (at start)
// do not store converted array
basal_v = null;
isValidated = false;
}
} }
return isValid; return isValid;

View file

@ -49,6 +49,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; 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.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
@ -1724,8 +1725,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (trJson.has("profileJson")) if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson"); profileSwitch.profileJson = trJson.getString("profileJson");
else { else {
ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); ProfileInterface profileInterface = PluginStore.Companion.getInstance().getActiveProfileInterface();
if (profileInterface != null) {
ProfileStore store = profileInterface.getProfile(); ProfileStore store = profileInterface.getProfile();
if (store != null) { if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName); Profile profile = store.getSpecificProfile(profileSwitch.profileName);
@ -1745,11 +1745,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return; return;
} }
} else {
if (L.isEnabled(L.DATABASE))
log.debug("No active profile interface. Ignoring: " + trJson.toString());
return;
}
} }
if (trJson.has("profilePlugin")) if (trJson.has("profilePlugin"))
profileSwitch.profilePlugin = trJson.getString("profilePlugin"); profileSwitch.profilePlugin = trJson.getString("profilePlugin");

View file

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

View file

@ -4,7 +4,6 @@ import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects; import java.util.Objects;
@ -16,7 +15,7 @@ import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; 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.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
@ -237,7 +236,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
} }
IobTotal result = new IobTotal(time); IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin();
int realDuration = getDurationToTime(time); int realDuration = getDurationToTime(time);
double netBasalAmount = 0d; double netBasalAmount = 0d;
@ -292,7 +291,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
} }
IobTotal result = new IobTotal(time); IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin();
double realDuration = getDurationToTime(time); double realDuration = getDurationToTime(time);
double netBasalAmount = 0d; double netBasalAmount = 0d;

View file

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

View file

@ -23,6 +23,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin 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.ProfileFunction
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
@ -212,7 +213,7 @@ open class AppModule {
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds @Binds
fun bindActivePluginProvider(configBuilderPlugin: ConfigBuilderPlugin): ActivePluginProvider fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider
@Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider @Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider

View file

@ -28,6 +28,7 @@ import info.nightscout.androidaps.plugins.general.overview.OverviewFragment
import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment
import info.nightscout.androidaps.plugins.general.tidepool.TidepoolFragment 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.local.LocalProfileFragment
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import info.nightscout.androidaps.plugins.pump.combo.ComboFragment import info.nightscout.androidaps.plugins.pump.combo.ComboFragment
@ -57,6 +58,7 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment @ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment
@ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment @ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment
@ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment
@ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment @ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment
@ContributesAndroidInjector abstract fun contributesObjectivesFragment(): ObjectivesFragment @ContributesAndroidInjector abstract fun contributesObjectivesFragment(): ObjectivesFragment
@ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment

View file

@ -2,11 +2,15 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector 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.KeepAliveReceiver
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver
@Module @Module
@Suppress("unused") @Suppress("unused")
abstract class ReceiversModule { abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver @ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
} }

View file

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

View file

@ -119,8 +119,7 @@ class InsulinDialog : DialogFragmentWithDate() {
} }
override fun submit(): Boolean { override fun submit(): Boolean {
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription val pumpDescription = activePlugin.activePump.pumpDescription
?: return false
val insulin = SafeParse.stringToDouble(overview_insulin_amount.text) val insulin = SafeParse.stringToDouble(overview_insulin_amount.text)
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
val actions: LinkedList<String?> = LinkedList() val actions: LinkedList<String?> = LinkedList()

View file

@ -8,7 +8,7 @@ import android.widget.ArrayAdapter
import com.google.common.base.Joiner import com.google.common.base.Joiner
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R 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.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -26,7 +26,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var activePlugin: ActivePluginProvider
override fun onSaveInstanceState(savedInstanceState: Bundle) { override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState) super.onSaveInstanceState(savedInstanceState)
@ -53,7 +53,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
// profile // profile
context?.let { context -> context?.let { context ->
val profileStore = configBuilderPlugin.activeProfileInterface.profile val profileStore = activePlugin.activeProfileInterface.profile
?: return ?: return
val profileList = profileStore.getProfileList() val profileList = profileStore.getProfileList()
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
@ -79,7 +79,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
} }
override fun submit(): Boolean { override fun submit(): Boolean {
val profileStore = configBuilderPlugin.activeProfileInterface.profile val profileStore = activePlugin.activeProfileInterface.profile
?: return false ?: return false
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()

View file

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

View file

@ -77,7 +77,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble()
val maxInsulin = constraintChecker.getMaxBolusAllowed().value() 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") overview_treatment_carbs.setParams(savedInstanceState?.getDouble("overview_treatment_carbs")
?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher) ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher)
overview_treatment_insulin.setParams(savedInstanceState?.getDouble("overview_treatment_insulin") overview_treatment_insulin.setParams(savedInstanceState?.getDouble("overview_treatment_insulin")
@ -85,8 +85,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
} }
override fun submit(): Boolean { override fun submit(): Boolean {
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription val pumpDescription = activePlugin.activePump.pumpDescription
?: return false
val insulin = SafeParse.stringToDouble(overview_treatment_insulin.text) val insulin = SafeParse.stringToDouble(overview_treatment_insulin.text)
val carbs = SafeParse.stringToInt(overview_treatment_carbs.text) val carbs = SafeParse.stringToInt(overview_treatment_carbs.text)
val recordOnlyChecked = overview_treatment_record_only.isChecked val recordOnlyChecked = overview_treatment_record_only.isChecked

View file

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

View file

@ -27,11 +27,11 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished; import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData; import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
@ -55,7 +55,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject DefaultValueHelper defaultValueHelper; @Inject DefaultValueHelper defaultValueHelper;
@Inject IobCobStaticCalculatorPlugin iobCobStaticCalculatorPlugin; @Inject IobCobStaticCalculatorPlugin iobCobStaticCalculatorPlugin;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ActivePluginProvider activePlugin;
@Inject BuildHelper buildHelper; @Inject BuildHelper buildHelper;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -227,7 +227,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null) if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null)
return; return;
final PumpInterface pump = configBuilderPlugin.getActivePump(); final PumpInterface pump = activePlugin.getActivePump();
final Profile profile = profileFunction.getProfile(); final Profile profile = profileFunction.getProfile();
if (profile == null) { if (profile == null) {

View file

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

View file

@ -1,25 +1,34 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public interface ActivePluginProvider { public interface ActivePluginProvider {
@Nullable BgSourceInterface getActiveBgSource(); @NotNull BgSourceInterface getActiveBgSource(); // Forced to Dexcom
@NotNull ProfileInterface getActiveProfileInterface(); // Forced to LocalProfile if not changed @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(); @NotNull APSInterface getActiveAPS(); // Forced to SMB
@Nullable PumpInterface getActivePumpPlugin(); // Use in UI to disable buttons or check if pump is selected
@NotNull PumpInterface getActivePump(); // Use in places not reachable without active pump. Otherwise IllegalStateException is thrown @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 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

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

View file

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

View file

@ -39,6 +39,7 @@ import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -53,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.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@ -82,7 +82,7 @@ public class LoopPlugin extends PluginBase {
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final Context context; private final Context context;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
private final ConfigBuilderPlugin configBuilderPlugin; private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final VirtualPumpPlugin virtualPumpPlugin; private final VirtualPumpPlugin virtualPumpPlugin;
private final Lazy<ActionStringHandler> actionStringHandler; private final Lazy<ActionStringHandler> actionStringHandler;
@ -125,7 +125,7 @@ public class LoopPlugin extends PluginBase {
ProfileFunction profileFunction, ProfileFunction profileFunction,
Context context, Context context,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
ConfigBuilderPlugin configBuilderPlugin, ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
VirtualPumpPlugin virtualPumpPlugin, VirtualPumpPlugin virtualPumpPlugin,
Lazy<ActionStringHandler> actionStringHandler, // TODO Adrian use RxBus instead of Lazy Lazy<ActionStringHandler> actionStringHandler, // TODO Adrian use RxBus instead of Lazy
@ -147,7 +147,7 @@ public class LoopPlugin extends PluginBase {
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.context = context; this.context = context;
this.configBuilderPlugin = configBuilderPlugin; this.activePlugin = activePlugin;
this.commandQueue = commandQueue; this.commandQueue = commandQueue;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.virtualPumpPlugin = virtualPumpPlugin; this.virtualPumpPlugin = virtualPumpPlugin;
@ -214,8 +214,13 @@ public class LoopPlugin extends PluginBase {
@Override @Override
public boolean specialEnableCondition() { public boolean specialEnableCondition() {
PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); try {
return pump == null || pump.getPumpDescription().isTempBasalCapable; PumpInterface pump = activePlugin.getActivePump();
return pump.getPumpDescription().isTempBasalCapable;
} catch (Exception ignored) {
// may fail during initialization
return true;
}
} }
public long suspendedTo() { public long suspendedTo() {
@ -320,9 +325,7 @@ public class LoopPlugin extends PluginBase {
rxBus.send(new EventLoopSetLastRunGui(message)); rxBus.send(new EventLoopSetLastRunGui(message));
return; return;
} }
final PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); final PumpInterface pump = activePlugin.getActivePump();
if (pump == null)
return;
APSResult result = null; APSResult result = null;
if (!isEnabled(PluginType.LOOP)) if (!isEnabled(PluginType.LOOP))
@ -340,8 +343,8 @@ public class LoopPlugin extends PluginBase {
// Check if pump info is loaded // Check if pump info is loaded
if (pump.getBaseBasalRate() < 0.01d) return; if (pump.getBaseBasalRate() < 0.01d) return;
APSInterface usedAPS = configBuilderPlugin.getActiveAPS(); APSInterface usedAPS = activePlugin.getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) { if (((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
usedAPS.invoke(initiator, tempBasalFallback); usedAPS.invoke(initiator, tempBasalFallback);
result = usedAPS.getLastAPSResult(); result = usedAPS.getLastAPSResult();
} }
@ -537,12 +540,7 @@ public class LoopPlugin extends PluginBase {
return; return;
} }
PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
if (pump == null) {
if (callback != null)
callback.result(new PumpEnactResult(getInjector()).enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run();
return;
}
if (!pump.isInitialized()) { if (!pump.isInitialized()) {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpNotInitialized)); getAapsLogger().debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpNotInitialized));
@ -624,12 +622,7 @@ public class LoopPlugin extends PluginBase {
return; return;
} }
PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
if (pump == null) {
if (callback != null)
callback.result(new PumpEnactResult(getInjector()).enacted(false).success(false).comment(resourceHelper.gs(R.string.nopumpselected))).run();
return;
}
long lastBolusTime = treatmentsPlugin.getLastBolusTime(); long lastBolusTime = treatmentsPlugin.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
@ -673,9 +666,7 @@ public class LoopPlugin extends PluginBase {
} }
public void disconnectPump(int durationInMinutes, Profile profile) { public void disconnectPump(int durationInMinutes, Profile profile) {
PumpInterface pump = configBuilderPlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
if (pump == null)
return;
disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L); disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);

View file

@ -96,18 +96,19 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
@Override @Override
public boolean specialEnableCondition() { public boolean specialEnableCondition() {
// main fail during init try {
if (activePlugin != null) { PumpInterface pump = activePlugin.getActivePump();
PumpInterface pump = activePlugin.getActivePumpPlugin(); return pump.getPumpDescription().isTempBasalCapable;
return pump == null || pump.getPumpDescription().isTempBasalCapable; } catch (Exception ignored) {
} // may fail during initialization
return true; return true;
} }
}
@Override @Override
public boolean specialShowInListCondition() { public boolean specialShowInListCondition() {
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable; return pump.getPumpDescription().isTempBasalCapable;
} }
@Override @Override
@ -137,12 +138,6 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
return; 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)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)); aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));

View file

@ -92,18 +92,19 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
@Override @Override
public boolean specialEnableCondition() { public boolean specialEnableCondition() {
// main fail during init try {
if (activePlugin != null) { PumpInterface pump = activePlugin.getActivePump();
PumpInterface pump = activePlugin.getActivePumpPlugin(); return pump.getPumpDescription().isTempBasalCapable;
return pump == null || pump.getPumpDescription().isTempBasalCapable; } catch (Exception ignored) {
} // may fail during initialization
return true; return true;
} }
}
@Override @Override
public boolean specialShowInListCondition() { public boolean specialShowInListCondition() {
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable; return pump.getPumpDescription().isTempBasalCapable;
} }
@Override @Override
@ -125,7 +126,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
if (profile == null) { if (profile == null) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))); rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected)));
@ -133,12 +134,6 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
return; 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)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));

View file

@ -31,7 +31,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; 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.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
@ -42,7 +41,6 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
@Singleton @Singleton
@ -99,18 +97,19 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
@Override @Override
public boolean specialEnableCondition() { public boolean specialEnableCondition() {
// main fail during init try {
if (activePlugin != null) { PumpInterface pump = activePlugin.getActivePump();
PumpInterface pump = activePlugin.getActivePumpPlugin(); return pump.getPumpDescription().isTempBasalCapable;
return pump == null || pump.getPumpDescription().isTempBasalCapable; } catch (Exception ignored) {
} // may fail during initialization
return true; return true;
} }
}
@Override @Override
public boolean specialShowInListCondition() { public boolean specialShowInListCondition() {
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable; return pump.getPumpDescription().isTempBasalCapable;
} }
@Override @Override
@ -140,12 +139,6 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
return; 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)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))); rxBus.send(new EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled)));
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled));
@ -180,29 +173,29 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
inputConstraints.copyReasons(maxIOBAllowedConstraint); inputConstraints.copyReasons(maxIOBAllowedConstraint);
double maxIob = maxIOBAllowedConstraint.value(); double maxIob = maxIOBAllowedConstraint.value();
minBg = verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]); minBg = hardLimits.verifyHardLimits(minBg, "minBg", hardLimits.getVERY_HARD_LIMIT_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_MIN_BG()[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]); maxBg = hardLimits.verifyHardLimits(maxBg, "maxBg", hardLimits.getVERY_HARD_LIMIT_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_MAX_BG()[1]);
targetBg = verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]); targetBg = hardLimits.verifyHardLimits(targetBg, "targetBg", hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TARGET_BG()[1]);
boolean isTempTarget = false; boolean isTempTarget = false;
TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis()); TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) { if (tempTarget != null) {
isTempTarget = true; isTempTarget = true;
minBg = verifyHardLimits(tempTarget.low, "minBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MIN_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 = verifyHardLimits(tempTarget.high, "maxBg", hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_MAX_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 = verifyHardLimits(tempTarget.target(), "targetBg", hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_BG()[0], hardLimits.getVERY_HARD_LIMIT_TEMP_TARGET_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.getMINDIA(), hardLimits.getMAXDIA())) if (!hardLimits.checkOnlyHardLimits(profile.getDia(), "dia", hardLimits.getMINDIA(), hardLimits.getMAXDIA()))
return; return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC())) if (!hardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", hardLimits.getMINIC(), hardLimits.getMAXIC()))
return; return;
if (!checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF())) if (!hardLimits.checkOnlyHardLimits(profile.getIsfMgdl(), "sens", hardLimits.getMINISF(), hardLimits.getMAXISF()))
return; 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; return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal())) if (!hardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, hardLimits.maxBasal()))
return; return;
startPart = System.currentTimeMillis(); startPart = System.currentTimeMillis();
@ -285,26 +278,6 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
//deviceStatus.suggested = determineBasalResultAMA.json; //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(context, msg, R.raw.error);
}
return newvalue;
}
@NotNull @NotNull
@Override @Override
public Constraint<Boolean> isSuperBolusEnabled(Constraint<Boolean> value) { public Constraint<Boolean> isSuperBolusEnabled(Constraint<Boolean> value) {

View file

@ -34,6 +34,7 @@ class ConfigBuilderFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val pluginViewHolders = ArrayList<PluginViewHolder>() private val pluginViewHolders = ArrayList<PluginViewHolder>()
@ -80,16 +81,16 @@ class ConfigBuilderFragment : DaggerFragment() {
@Synchronized @Synchronized
private fun updateGUI() { private fun updateGUI() {
configbuilder_categories.removeAllViews() 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_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, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN)) 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, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE)) 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, MainApp.getSpecificPluginsVisibleInList(PluginType.PUMP)) 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, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY)) 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, MainApp.getSpecificPluginsVisibleInList(PluginType.APS)) 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, MainApp.getSpecificPluginsVisibleInList(PluginType.LOOP)) 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, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS)) 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, MainApp.getSpecificPluginsVisibleInList(PluginType.TREATMENT)) 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, MainApp.getSpecificPluginsVisibleInList(PluginType.GENERAL)) 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>) { private fun createViewsForPlugins(@StringRes title: Int, @StringRes description: Int, pluginType: PluginType, plugins: List<PluginBase>) {

View file

@ -4,8 +4,6 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import javax.inject.Inject; import javax.inject.Inject;
@ -13,7 +11,6 @@ import javax.inject.Singleton;
import dagger.Lazy; import dagger.Lazy;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventAppInitialized;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
@ -48,14 +45,15 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
@Singleton @Singleton
public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvider { public class ConfigBuilderPlugin extends PluginBase {
private static ConfigBuilderPlugin configBuilderPlugin; private static ConfigBuilderPlugin configBuilderPlugin;
private final ActivePluginProvider activePlugin;
private final SP sp; private final SP sp;
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
private final NSProfilePlugin nsProfilePlugin;
/** /**
* @deprecated Use dagger to get an instance * @deprecated Use dagger to get an instance
@ -75,22 +73,6 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
return configBuilderPlugin; 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: * Written by Adrian:
* The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app. * The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app.
@ -100,19 +82,13 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
* */ * */
@Inject @Inject
public ConfigBuilderPlugin( public ConfigBuilderPlugin(
Lazy<InsulinOrefRapidActingPlugin> insulinOrefRapidActingPlugin, ActivePluginProvider activePlugin,
Lazy<LocalProfilePlugin> localProfilePlugin,
Lazy<VirtualPumpPlugin> virtualPumpPlugin,
Lazy<TreatmentsPlugin> treatmentsPlugin,
Lazy<SensitivityOref0Plugin> sensitivityOref0Plugin,
Lazy<SensitivityOref1Plugin> sensitivityOref1Plugin,
HasAndroidInjector injector, HasAndroidInjector injector,
SP sp, SP sp,
RxBusWrapper rxBus, RxBusWrapper rxBus,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue
NSProfilePlugin nsProfilePlugin
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
@ -125,31 +101,25 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
.description(R.string.description_config_builder), .description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
); );
this.insulinOrefRapidActingPlugin = insulinOrefRapidActingPlugin; this.activePlugin = activePlugin;
this.localProfilePlugin = localProfilePlugin;
this.virtualPumpPlugin = virtualPumpPlugin;
this.treatmentsPlugin = treatmentsPlugin;
this.sensitivityOref0Plugin = sensitivityOref0Plugin;
this.sensitivityOref1Plugin = sensitivityOref1Plugin;
this.sp = sp; this.sp = sp;
this.rxBus = rxBus; this.rxBus = rxBus;
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.commandQueue = commandQueue; this.commandQueue = commandQueue;
this.nsProfilePlugin = nsProfilePlugin;
configBuilderPlugin = this; // TODO: only while transitioning to Dagger configBuilderPlugin = this; // TODO: only while transitioning to Dagger
} }
public void initialize() { public void initialize() {
pluginList = MainApp.getPluginsList();
upgradeSettings(); upgradeSettings();
((PluginStore) activePlugin).loadDefaults();
loadSettings(); loadSettings();
setAlwaysEnabledPluginsEnabled(); setAlwaysEnabledPluginsEnabled();
rxBus.send(new EventAppInitialized()); rxBus.send(new EventAppInitialized());
} }
private void setAlwaysEnabledPluginsEnabled() { private void setAlwaysEnabledPluginsEnabled() {
for (PluginBase plugin : pluginList) { for (PluginBase plugin : activePlugin.getPluginsList()) {
if (plugin.getPluginDescription().alwaysEnabled) if (plugin.getPluginDescription().alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true); plugin.setPluginEnabled(plugin.getType(), true);
} }
@ -157,12 +127,12 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
} }
public void storeSettings(String from) { public void storeSettings(String from) {
if (pluginList != null) { activePlugin.getPluginsList();
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from); getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from);
verifySelectionInCategories(); activePlugin.verifySelectionInCategories();
for (PluginBase p : pluginList) { for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType(); PluginType type = p.getType();
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible) if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible)
continue; continue;
@ -176,7 +146,6 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
} }
} }
} }
}
private void savePref(PluginBase p, PluginType type, boolean storeVisible) { private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled"; String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
@ -191,7 +160,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
private void loadSettings() { private void loadSettings() {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loading stored settings"); getAapsLogger().debug(LTag.CONFIGBUILDER, "Loading stored settings");
for (PluginBase p : pluginList) { for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType(); PluginType type = p.getType();
loadPref(p, type, true); loadPref(p, type, true);
if (p.getType() == PluginType.PUMP) { if (p.getType() == PluginType.PUMP) {
@ -200,7 +169,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
} }
} }
} }
verifySelectionInCategories(); activePlugin.verifySelectionInCategories();
} }
private void loadPref(PluginBase p, PluginType type, boolean loadVisible) { private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
@ -227,7 +196,7 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled")) if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return; return;
getAapsLogger().debug(LTag.CONFIGBUILDER, "Upgrading stored settings"); getAapsLogger().debug(LTag.CONFIGBUILDER, "Upgrading stored settings");
for (PluginBase p : pluginList) { for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Processing " + p.getName()); getAapsLogger().debug(LTag.CONFIGBUILDER, "Processing " + p.getName());
for (int type = 1; type < 11; type++) { for (int type = 1; type < 11; type++) {
PluginType newType; PluginType newType;
@ -276,69 +245,13 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
sp.remove(settingVisible); sp.remove(settingVisible);
if (newType == p.getType()) { if (newType == p.getType()) {
savePref(p, newType, true); 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() { public void logPluginStatus() {
for (PluginBase p : pluginList) { for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, p.getName() + ":" + getAapsLogger().debug(LTag.CONFIGBUILDER, p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") + (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
(p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") + (p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
@ -354,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 // Ask when switching to physical pump plugin
public void switchAllowed(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) { 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))) if (changedPlugin.getType() == PluginType.PUMP && !changedPlugin.getName().equals(resourceHelper.gs(R.string.virtualpump)))
@ -513,23 +312,25 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
break; break;
// Single selection allowed // Single selection allowed
case INSULIN: case INSULIN:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(InsulinInterface.class); pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface.class);
break; break;
case SENSITIVITY: case SENSITIVITY:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(SensitivityInterface.class); pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface.class);
break; break;
case APS: case APS:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(APSInterface.class); pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface.class);
break; break;
case PROFILE: case PROFILE:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(ProfileInterface.class); pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface.class);
break; break;
case BGSOURCE: case BGSOURCE:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(BgSourceInterface.class); pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface.class);
break; break;
case TREATMENT: case TREATMENT:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface.class);
break;
case PUMP: case PUMP:
pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(PumpInterface.class); pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface.class);
break; break;
} }
if (pluginsInCategory != null) { if (pluginsInCategory != null) {
@ -544,15 +345,6 @@ public class ConfigBuilderPlugin extends PluginBase implements ActivePluginProvi
} }
} }
} else { // enable first plugin in list } 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 package info.nightscout.androidaps.plugins.configBuilder
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -10,7 +10,7 @@ import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@Singleton @Singleton
class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : ConstraintsInterface { class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface {
fun isLoopInvocationAllowed(): Constraint<Boolean> = fun isLoopInvocationAllowed(): Constraint<Boolean> =
isLoopInvocationAllowed(Constraint(true)) isLoopInvocationAllowed(Constraint(true))
@ -55,7 +55,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB)) applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB))
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -65,7 +65,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -75,7 +75,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -85,7 +85,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isAMAModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -95,7 +95,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -105,7 +105,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isUAMEnabled(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -115,7 +115,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isAdvancedFilteringEnabled(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -125,7 +125,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun isSuperBolusEnabled(value: Constraint<Boolean>): Constraint<Boolean> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -135,7 +135,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun applyBasalConstraints(absoluteRate: Constraint<Double>, profile: Profile): Constraint<Double> { 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) { for (p in constraintsPlugins) {
val constraint = p as ConstraintsInterface val constraint = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -145,7 +145,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun applyBasalPercentConstraints(percentRate: Constraint<Int>, profile: Profile): Constraint<Int> { 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) { for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -155,7 +155,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun applyBolusConstraints(insulin: Constraint<Double>): Constraint<Double> { 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) { for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -165,7 +165,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun applyExtendedBolusConstraints(insulin: Constraint<Double>): Constraint<Double> { 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) { for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -175,7 +175,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun applyCarbsConstraints(carbs: Constraint<Int>): Constraint<Int> { 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) { for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue if (!p.isEnabled(PluginType.CONSTRAINTS)) continue
@ -185,7 +185,7 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons
} }
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> { 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) { for (p in constraintsPlugins) {
val constrain = p as ConstraintsInterface val constrain = p as ConstraintsInterface
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue 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,6 +1,5 @@
package info.nightscout.androidaps.plugins.configBuilder; package info.nightscout.androidaps.plugins.configBuilder;
import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
@ -9,35 +8,26 @@ import com.google.firebase.analytics.FirebaseAnalytics;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source; 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.ProfileInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
public class ProfileFunctions implements ProfileFunction { public class ProfileFunctions implements ProfileFunction {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.PROFILE); private static Logger log = StacktraceLoggerWrapper.getLogger(L.PROFILE);
private CompositeDisposable disposable = new CompositeDisposable();
private static ProfileFunctions profileFunctions = null; private static ProfileFunctions profileFunctions = null;
@ -48,36 +38,6 @@ public class ProfileFunctions implements ProfileFunction {
return 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 @NotNull
public String getProfileName() { public String getProfileName() {
return getProfileName(System.currentTimeMillis(), true, false); return getProfileName(System.currentTimeMillis(), true, false);
@ -98,7 +58,7 @@ public class ProfileFunctions implements ProfileFunction {
String profileName = MainApp.gs(R.string.noprofileselected); String profileName = MainApp.gs(R.string.noprofileselected);
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); ProfileInterface activeProfile = PluginStore.Companion.getInstance().getActiveProfileInterface();
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) { if (profileSwitch != null) {
@ -145,7 +105,7 @@ public class ProfileFunctions implements ProfileFunction {
@Nullable @Nullable
public Profile getProfile(long time) { public Profile getProfile(long time) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); ProfileInterface activeProfile = PluginStore.Companion.getInstance().getActiveProfileInterface();
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time)); //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
@ -177,7 +137,7 @@ public class ProfileFunctions implements ProfileFunction {
profileSwitch.source = Source.USER; profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName; profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); profileSwitch.profilePlugin = PluginStore.Companion.getInstance().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration; profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeShift != 0; profileSwitch.isCPP = percentage != 100 || timeShift != 0;
profileSwitch.timeshift = timeShift; profileSwitch.timeshift = timeShift;

View file

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

View file

@ -7,11 +7,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.*
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.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
@ -28,7 +24,7 @@ class ObjectivesPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
private val configBuilderPlugin: ConfigBuilderPlugin, private val activePlugin: ActivePluginProvider,
private val sp: SP private val sp: SP
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
@ -64,8 +60,7 @@ class ObjectivesPlugin @Inject constructor(
} }
override fun specialEnableCondition(): Boolean { override fun specialEnableCondition(): Boolean {
val pump = configBuilderPlugin.activePumpPlugin return activePlugin.activePump.pumpDescription.isTempBasalCapable
return pump == null || pump.pumpDescription.isTempBasalCapable
} }
// convert 2.3 SP version // convert 2.3 SP version

View file

@ -19,16 +19,16 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
public abstract class Objective { public abstract class Objective {
@Inject public SP sp; @Inject public SP sp;
@Inject ResourceHelper resourceHelper;
private String spName; private String spName;
@StringRes @StringRes private int objective;
private int objective; @StringRes private int gate;
@StringRes
private int gate;
private long startedOn; private long startedOn;
private long accomplishedOn; private long accomplishedOn;
List<Task> tasks = new ArrayList<>(); List<Task> tasks = new ArrayList<>();
@ -187,9 +187,9 @@ public abstract class Objective {
int days = (int) Math.floor((double) duration / T.days(1).msecs()); int days = (int) Math.floor((double) duration / T.days(1).msecs());
int hours = (int) Math.floor((double) duration / T.hours(1).msecs()); int hours = (int) Math.floor((double) duration / T.hours(1).msecs());
int minutes = (int) Math.floor((double) duration / T.mins(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); if (days > 0) return resourceHelper.gq(R.plurals.objective_days, days, days);
else if (hours > 0) return MainApp.gq(R.plurals.objective_hours, hours, hours); else if (hours > 0) return resourceHelper.gq(R.plurals.objective_hours, hours, hours);
else return MainApp.gq(R.plurals.objective_minutes, minutes, minutes); else return resourceHelper.gq(R.plurals.objective_minutes, minutes, minutes);
} }
} }

View file

@ -7,10 +7,10 @@ import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; 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.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
@ -20,7 +20,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class Objective0 extends Objective { public class Objective0 extends Objective {
@Inject SP sp; @Inject SP sp;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ActivePluginProvider activePlugin;
@Inject VirtualPumpPlugin virtualPumpPlugin; @Inject VirtualPumpPlugin virtualPumpPlugin;
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject LoopPlugin loopPlugin; @Inject LoopPlugin loopPlugin;
@ -77,8 +77,8 @@ public class Objective0 extends Objective {
tasks.add(new Task(R.string.apsselected) { tasks.add(new Task(R.string.apsselected) {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {
APSInterface usedAPS = configBuilderPlugin.getActiveAPS(); APSInterface usedAPS = activePlugin.getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) if (((PluginBase) usedAPS).isEnabled(PluginType.APS))
return true; return true;
return false; return false;
} }

View file

@ -94,7 +94,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
**/ **/
@NonNull @Override @NonNull @Override
public Constraint<Boolean> isLoopInvocationAllowed(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isLoopInvocationAllowed(@NonNull Constraint<Boolean> value) {
if (!activePlugin.getActivePumpPlugin().getPumpDescription().isTempBasalCapable) if (!activePlugin.getActivePump().getPumpDescription().isTempBasalCapable)
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.pumpisnottempbasalcapable), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.pumpisnottempbasalcapable), this);
return value; return value;
} }
@ -112,8 +112,8 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
} }
value.set(getAapsLogger(), false, getResourceHelper().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(); PumpInterface pump = activePlugin.getActivePump();
if (pump != null && !pump.isFakingTempsByExtendedBoluses() && treatmentsPlugin.isInHistoryExtendedBoluslInProgress()) { if (!pump.isFakingTempsByExtendedBoluses() && treatmentsPlugin.isInHistoryExtendedBoluslInProgress()) {
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closed_loop_disabled_with_eb), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closed_loop_disabled_with_eb), this);
} }
return value; return value;
@ -153,10 +153,8 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
public Constraint<Boolean> isAdvancedFilteringEnabled(@NonNull Constraint<Boolean> value) { public Constraint<Boolean> isAdvancedFilteringEnabled(@NonNull Constraint<Boolean> value) {
BgSourceInterface bgSource = activePlugin.getActiveBgSource(); BgSourceInterface bgSource = activePlugin.getActiveBgSource();
if (bgSource != null) {
if (!bgSource.advancedFilteringSupported()) if (!bgSource.advancedFilteringSupported())
value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbalwaysdisabled), this); value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.smbalwaysdisabled), this);
}
return value; return value;
} }
@ -185,15 +183,15 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
absoluteRate.setIfSmaller(getAapsLogger(), hardLimits.maxBasal(), String.format(getResourceHelper().gs(R.string.limitingbasalratio), hardLimits.maxBasal(), getResourceHelper().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 // 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(); double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
absoluteRate.setIfSmaller(getAapsLogger(), pumpLimit, String.format(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().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 // do rounding
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) { if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
absoluteRate.set(getAapsLogger(), Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep)); absoluteRate.set(getAapsLogger(), Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep));
} }
return absoluteRate; return absoluteRate;
@ -211,19 +209,17 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
applyBasalConstraints(absoluteConstraint, profile); applyBasalConstraints(absoluteConstraint, profile);
percentRate.copyReasons(absoluteConstraint); percentRate.copyReasons(absoluteConstraint);
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePump();
int percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue(); int percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue();
if (pump != null) {
if (percentRateAfterConst < 100) if (percentRateAfterConst < 100)
percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue(); percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
else else
percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue(); percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
}
percentRate.set(getAapsLogger(), percentRateAfterConst, String.format(getResourceHelper().gs(R.string.limitingpercentrate), percentRateAfterConst, getResourceHelper().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(); double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
percentRate.setIfSmaller(getAapsLogger(), (int) pumpLimit, String.format(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().gs(R.string.pumplimit)), this); percentRate.setIfSmaller(getAapsLogger(), (int) pumpLimit, String.format(getResourceHelper().gs(R.string.limitingbasalratio), pumpLimit, getResourceHelper().gs(R.string.pumplimit)), this);
} }
@ -240,11 +236,9 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
insulin.setIfSmaller(getAapsLogger(), hardLimits.maxBolus(), String.format(getResourceHelper().gs(R.string.limitingbolus), hardLimits.maxBolus(), getResourceHelper().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(); PumpInterface pump = activePlugin.getActivePump();
if (pump != null) {
double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value()); double rounded = pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value());
insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this); insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this);
}
return insulin; return insulin;
} }
@ -257,11 +251,9 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
insulin.setIfSmaller(getAapsLogger(), hardLimits.maxBolus(), String.format(getResourceHelper().gs(R.string.limitingextendedbolus), hardLimits.maxBolus(), getResourceHelper().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(); PumpInterface pump = activePlugin.getActivePump();
if (pump != null) {
double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value()); double rounded = pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value());
insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this); insulin.setIfDifferent(getAapsLogger(), rounded, getResourceHelper().gs(R.string.pumplimit), this);
}
return insulin; return insulin;
} }

View file

@ -181,17 +181,16 @@ class ActionsFragment : DaggerFragment() {
else View.GONE else View.GONE
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val pump = activePlugin.activePumpPlugin val pump = activePlugin.activePump
actions_temptarget?.visibility = (profile != null).toVisibility() actions_temptarget?.visibility = (profile != null).toVisibility()
actions_canceltempbasal.visibility = (pump != null || profile == null).toVisibility() actions_canceltempbasal.visibility = (profile == null).toVisibility()
actions_settempbasal.visibility = (pump != null || profile == null).toVisibility() actions_settempbasal.visibility = (profile == null).toVisibility()
actions_fill.visibility = (pump != null || profile == null).toVisibility() actions_fill.visibility = (profile == null).toVisibility()
actions_extendedbolus.visibility = (pump != null || profile == null).toVisibility() actions_extendedbolus.visibility = (profile == null).toVisibility()
actions_extendedbolus_cancel.visibility = (pump != null || profile == null).toVisibility() actions_extendedbolus_cancel.visibility = (profile == null).toVisibility()
actions_historybrowser.visibility = (pump != null || profile == null).toVisibility() actions_historybrowser.visibility = (profile == null).toVisibility()
actions_tddstats.visibility = (pump != null || profile == null).toVisibility() actions_tddstats.visibility = (profile == null).toVisibility()
if (pump == null) return
val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
@ -240,7 +239,7 @@ class ActionsFragment : DaggerFragment() {
} }
private fun checkPumpCustomActions() { private fun checkPumpCustomActions() {
val activePump = activePlugin.activePumpPlugin ?: return val activePump = activePlugin.activePump
val customActions = activePump.customActions ?: return val customActions = activePump.customActions ?: return
removePumpCustomActions() removePumpCustomActions()

View file

@ -40,7 +40,7 @@ class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val lastConnection = activePlugin.activePumpPlugin?.lastDataTime() ?: return false val lastConnection = activePlugin.activePump.lastDataTime()
if (lastConnection == 0L && comparator.value === Comparator.Compare.IS_NOT_AVAILABLE) { if (lastConnection == 0L && comparator.value === Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true return true

View file

@ -7,8 +7,8 @@ import android.view.ViewGroup
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventCareportalEventChange import info.nightscout.androidaps.events.EventCareportalEventChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler
@ -26,7 +26,7 @@ class CareportalFragment : DaggerFragment(), View.OnClickListener {
@Inject lateinit var nsSettingsStatus: NSSettingsStatus @Inject lateinit var nsSettingsStatus: NSSettingsStatus
@Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var statusLightHandler: StatusLightHandler
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var activePlugin: ActivePluginProvider
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -57,7 +57,7 @@ class CareportalFragment : DaggerFragment(), View.OnClickListener {
careportal_openapsoffline.setOnClickListener(this) careportal_openapsoffline.setOnClickListener(this)
careportal_temporarytarget.setOnClickListener(this) careportal_temporarytarget.setOnClickListener(this)
val profileStore = configBuilderPlugin.activeProfileInterface.profile val profileStore = activePlugin.activeProfileInterface.profile
if (profileStore == null) { if (profileStore == null) {
profileview_noprofile.visibility = View.VISIBLE profileview_noprofile.visibility = View.VISIBLE
careportal_buttons.visibility = View.GONE careportal_buttons.visibility = View.GONE

View file

@ -49,6 +49,7 @@ import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
@ -75,7 +76,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
@Inject SP sp; @Inject SP sp;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ActivePluginProvider activePlugin;
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject HardLimits hardLimits; @Inject HardLimits hardLimits;
@ -178,7 +179,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O
// profile // profile
profile = profileFunction.getProfile(); profile = profileFunction.getProfile();
profileStore = configBuilderPlugin.getActiveProfileInterface().getProfile(); profileStore = activePlugin.getActiveProfileInterface().getProfile();
if (profileStore == null) { if (profileStore == null) {
if (options.eventType == R.id.careportal_profileswitch) { if (options.eventType == R.id.careportal_profileswitch) {
log.error("Profile switch called but plugin doesn't contain valid profile"); log.error("Profile switch called but plugin doesn't contain valid profile");

View file

@ -42,6 +42,7 @@ import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.DeviceStatus; import info.nightscout.androidaps.plugins.aps.loop.DeviceStatus;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.utils.BatteryLevel; import info.nightscout.androidaps.utils.BatteryLevel;
@ -212,7 +213,7 @@ public class NSUpload {
} }
} }
deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL; deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL;
JSONObject pumpstatus = ConfigBuilderPlugin.getPlugin().getActivePump().getJSONStatus(profile, profileName); JSONObject pumpstatus = PluginStore.Companion.getInstance().getActivePump().getJSONStatus(profile, profileName);
if (pumpstatus != null) { if (pumpstatus != null) {
deviceStatus.pump = pumpstatus; deviceStatus.pump = pumpstatus;
} }

View file

@ -77,6 +77,7 @@ import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
@ -105,6 +106,7 @@ import info.nightscout.androidaps.plugins.source.DexcomPlugin;
import info.nightscout.androidaps.plugins.source.XdripPlugin; import info.nightscout.androidaps.plugins.source.XdripPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.DefaultValueHelper; import info.nightscout.androidaps.utils.DefaultValueHelper;
@ -140,6 +142,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
@Inject NSDeviceStatus nsDeviceStatus; @Inject NSDeviceStatus nsDeviceStatus;
@Inject LoopPlugin loopPlugin; @Inject LoopPlugin loopPlugin;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject ActivePluginProvider activePlugin;
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin;
@Inject DexcomPlugin dexcomPlugin; @Inject DexcomPlugin dexcomPlugin;
@ -148,6 +151,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
@Inject ActionStringHandler actionStringHandler; @Inject ActionStringHandler actionStringHandler;
@Inject QuickWizard quickWizard; @Inject QuickWizard quickWizard;
@Inject BuildHelper buildHelper; @Inject BuildHelper buildHelper;
@Inject CommandQueue commandQueue;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -625,7 +629,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
super.onCreateContextMenu(menu, v, menuInfo); super.onCreateContextMenu(menu, v, menuInfo);
if (v == apsModeView) { if (v == apsModeView) {
final PumpDescription pumpDescription = final PumpDescription pumpDescription =
configBuilderPlugin.getActivePump().getPumpDescription(); activePlugin.getActivePump().getPumpDescription();
if (!profileFunction.isProfileValid("ContexMenuCreation")) if (!profileFunction.isProfileValid("ContexMenuCreation"))
return; return;
menu.setHeaderTitle(resourceHelper.gs(R.string.loop)); menu.setHeaderTitle(resourceHelper.gs(R.string.loop));
@ -656,7 +660,8 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
} else if (v == activeProfileView) { } else if (v == activeProfileView) {
menu.setHeaderTitle(resourceHelper.gs(R.string.profile)); menu.setHeaderTitle(resourceHelper.gs(R.string.profile));
menu.add(resourceHelper.gs(R.string.danar_viewprofile)); menu.add(resourceHelper.gs(R.string.danar_viewprofile));
if (configBuilderPlugin.getActiveProfileInterface() != null && configBuilderPlugin.getActiveProfileInterface().getProfile() != null) { activePlugin.getActiveProfileInterface();
if (activePlugin.getActiveProfileInterface().getProfile() != null) {
menu.add(resourceHelper.gs(R.string.careportal_profileswitch)); menu.add(resourceHelper.gs(R.string.careportal_profileswitch));
} }
} else if (v == tempTargetView) { } else if (v == tempTargetView) {
@ -692,7 +697,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
loopPlugin.setFragmentVisible(PluginType.LOOP, false); loopPlugin.setFragmentVisible(PluginType.LOOP, false);
configBuilderPlugin.storeSettings("DisablingLoop"); configBuilderPlugin.storeSettings("DisablingLoop");
updateGUI("suspendmenu"); updateGUI("suspendmenu");
configBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() { commandQueue.cancelTempBasal(true, new Callback() {
@Override @Override
public void run() { public void run() {
if (!result.success) { if (!result.success) {
@ -715,7 +720,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
aapsLogger.debug("USER ENTRY: RESUME"); aapsLogger.debug("USER ENTRY: RESUME");
loopPlugin.suspendTo(0L); loopPlugin.suspendTo(0L);
updateGUI("suspendmenu"); updateGUI("suspendmenu");
configBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() { commandQueue.cancelTempBasal(true, new Callback() {
@Override @Override
public void run() { public void run() {
if (!result.success) { if (!result.success) {
@ -898,8 +903,8 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
new CarbsDialog().show(manager, "Overview"); new CarbsDialog().show(manager, "Overview");
break; break;
case R.id.overview_pumpstatus: case R.id.overview_pumpstatus:
if (configBuilderPlugin.getActivePump().isSuspended() || !configBuilderPlugin.getActivePump().isInitialized()) if (activePlugin.getActivePump().isSuspended() || !activePlugin.getActivePump().isInitialized())
configBuilderPlugin.getCommandQueue().readStatus("RefreshClicked", null); commandQueue.readStatus("RefreshClicked", null);
break; break;
} }
@ -953,7 +958,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
final BgReading actualBg = iobCobCalculatorPlugin.actualBg(); final BgReading actualBg = iobCobCalculatorPlugin.actualBg();
final Profile profile = profileFunction.getProfile(); final Profile profile = profileFunction.getProfile();
final String profileName = profileFunction.getProfileName(); final String profileName = profileFunction.getProfileName();
final PumpInterface pump = configBuilderPlugin.getActivePump(); final PumpInterface pump = activePlugin.getActivePump();
final QuickWizardEntry quickWizardEntry = quickWizard.getActive(); final QuickWizardEntry quickWizardEntry = quickWizard.getActive();
if (quickWizardEntry != null && actualBg != null && profile != null) { if (quickWizardEntry != null && actualBg != null && profile != null) {
@ -1050,7 +1055,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
BgReading actualBG = iobCobCalculatorPlugin.actualBg(); BgReading actualBG = iobCobCalculatorPlugin.actualBg();
BgReading lastBG = iobCobCalculatorPlugin.lastBg(); BgReading lastBG = iobCobCalculatorPlugin.lastBg();
final PumpInterface pump = configBuilderPlugin.getActivePump(); final PumpInterface pump = activePlugin.getActivePump();
final Profile profile = profileFunction.getProfile(); final Profile profile = profileFunction.getProfile();
if (profile == null) return; if (profile == null) return;
@ -1134,7 +1139,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
if (tempTarget != null) { if (tempTarget != null) {
tempTargetView.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)); tempTargetView.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning));
tempTargetView.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)); tempTargetView.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning));
tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end(), resourceHelper)); tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end()));
} else { } else {
tempTargetView.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)); tempTargetView.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault));
tempTargetView.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)); tempTargetView.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault));
@ -1193,11 +1198,11 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
} }
baseBasalView.setText(basalText); baseBasalView.setText(basalText);
baseBasalView.setOnClickListener(v -> { baseBasalView.setOnClickListener(v -> {
String fullText = MainApp.gs(R.string.pump_basebasalrate_label) + ": " + MainApp.gs(R.string.pump_basebasalrate, profile.getBasal()) + "\n"; String fullText = resourceHelper.gs(R.string.pump_basebasalrate_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal()) + "\n";
if (activeTemp != null) { if (activeTemp != null) {
fullText += MainApp.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull(); fullText += resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull();
} }
OKDialog.show(getActivity(), MainApp.gs(R.string.basal), fullText); OKDialog.show(getActivity(), resourceHelper.gs(R.string.basal), fullText);
}); });
if (activeTemp != null) { if (activeTemp != null) {
@ -1215,7 +1220,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
extendedBolusView.setText(extendedBolusText); extendedBolusView.setText(extendedBolusText);
extendedBolusView.setOnClickListener(v -> { extendedBolusView.setOnClickListener(v -> {
if (extendedBolus != null) if (extendedBolus != null)
OKDialog.show(getActivity(), MainApp.gs(R.string.extended_bolus), extendedBolus.toString()); OKDialog.show(getActivity(), resourceHelper.gs(R.string.extended_bolus), extendedBolus.toString());
}); });
} }
@ -1244,7 +1249,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
// **** Various treatment buttons **** // **** Various treatment buttons ****
if (carbsButton != null) { if (carbsButton != null) {
if (sp.getBoolean(R.string.key_show_carbs_button, true) if (sp.getBoolean(R.string.key_show_carbs_button, true)
&& (!configBuilderPlugin.getActivePump().getPumpDescription().storesCarbInfo || && (!activePlugin.getActivePump().getPumpDescription().storesCarbInfo ||
(pump.isInitialized() && !pump.isSuspended()))) { (pump.isInitialized() && !pump.isSuspended()))) {
carbsButton.setVisibility(View.VISIBLE); carbsButton.setVisibility(View.VISIBLE);
} else { } else {

View file

@ -7,7 +7,7 @@ import androidx.arch.core.util.Function
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
@ -22,7 +22,7 @@ class StatusLightHandler @Inject constructor(
private val nsSettingsStatus: NSSettingsStatus, private val nsSettingsStatus: NSSettingsStatus,
private val resourceHelper: ResourceHelper, private val resourceHelper: ResourceHelper,
private val sp: SP, private val sp: SP,
private val configBuilderPlugin: ConfigBuilderPlugin private val activePlugin: ActivePluginProvider
) { ) {
/** /**
@ -30,7 +30,7 @@ class StatusLightHandler @Inject constructor(
*/ */
fun statusLight(cageView: TextView?, iAgeView: TextView?, reservoirView: TextView?, fun statusLight(cageView: TextView?, iAgeView: TextView?, reservoirView: TextView?,
sageView: TextView?, batteryView: TextView?) { sageView: TextView?, batteryView: TextView?) {
val pump = configBuilderPlugin.activePumpPlugin ?: return val pump = activePlugin.activePump
applyStatusLight("cage", CareportalEvent.SITECHANGE, cageView, "CAN", 48, 72) applyStatusLight("cage", CareportalEvent.SITECHANGE, cageView, "CAN", 48, 72)
applyStatusLight("iage", CareportalEvent.INSULINCHANGE, iAgeView, "INS", 72, 96) applyStatusLight("iage", CareportalEvent.INSULINCHANGE, iAgeView, "INS", 72, 96)
val reservoirLevel = if (pump.isInitialized) pump.reservoirLevel else (-1).toDouble() val reservoirLevel = if (pump.isInitialized) pump.reservoirLevel else (-1).toDouble()
@ -92,7 +92,7 @@ class StatusLightHandler @Inject constructor(
fun extendedStatusLight(cageView: TextView, iAgeView: TextView, fun extendedStatusLight(cageView: TextView, iAgeView: TextView,
reservoirView: TextView, sageView: TextView, reservoirView: TextView, sageView: TextView,
batteryView: TextView) { batteryView: TextView) {
val pump = configBuilderPlugin.activePumpPlugin ?: return val pump = activePlugin.activePump
handleAge("cage", CareportalEvent.SITECHANGE, cageView, "CAN ", handleAge("cage", CareportalEvent.SITECHANGE, cageView, "CAN ",
48, 72) 48, 72)
handleAge("iage", CareportalEvent.INSULINCHANGE, iAgeView, "INS ", handleAge("iage", CareportalEvent.INSULINCHANGE, iAgeView, "INS ",

View file

@ -12,7 +12,6 @@ import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.Series; import com.jjoe64.graphview.series.Series;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -33,7 +32,7 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.AreaGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.AreaGraphSeries;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
@ -51,7 +50,6 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.SP;
/** /**
* Created by mike on 18.10.2017. * Created by mike on 18.10.2017.
@ -311,7 +309,7 @@ public class GraphData {
} }
// Extended bolus // Extended bolus
if (!ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { if (!PluginStore.Companion.getInstance().getActivePump().isFakingTempsByExtendedBoluses()) {
List<ExtendedBolus> extendedBoluses = TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory().getList(); List<ExtendedBolus> extendedBoluses = TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory().getList();
for (int tx = 0; tx < extendedBoluses.size(); tx++) { for (int tx = 0; tx < extendedBoluses.size(); tx++) {

View file

@ -129,7 +129,7 @@ class PersistentNotificationPlugin @Inject constructor(
} }
private fun updateNotification() { private fun updateNotification() {
val pump = activePlugins.activePumpPlugin ?: return val pump = activePlugins.activePump
var line1: String? var line1: String?
var line2: String? = null var line2: String? = null
var line3: String? = null var line3: String? = null

View file

@ -196,7 +196,7 @@ class SmsCommunicatorPlugin @Inject constructor(
rxBus.send(EventSmsCommunicatorUpdateGui()) rxBus.send(EventSmsCommunicatorUpdateGui())
return return
} }
val pump = activePlugin.activePumpPlugin ?: return val pump = activePlugin.activePump
messages.add(receivedSms) messages.add(receivedSms)
aapsLogger.debug(LTag.SMS, receivedSms.toString()) aapsLogger.debug(LTag.SMS, receivedSms.toString())
val splitted = receivedSms.text.split(Regex("\\s+")).toTypedArray() val splitted = receivedSms.text.split(Regex("\\s+")).toTypedArray()
@ -369,7 +369,7 @@ class SmsCommunicatorPlugin @Inject constructor(
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -418,12 +418,10 @@ class SmsCommunicatorPlugin @Inject constructor(
private fun processPUMP(receivedSms: Sms) { private fun processPUMP(receivedSms: Sms) {
commandQueue.readStatus("SMS", object : Callback() { commandQueue.readStatus("SMS", object : Callback() {
override fun run() { override fun run() {
val pump = activePlugin.activePumpPlugin val pump = activePlugin.activePump
if (result.success) { if (result.success) {
if (pump != null) {
val reply = pump.shortStatus(true) val reply = pump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, reply)) sendSMS(Sms(receivedSms.phoneNumber, reply))
}
} else { } else {
val reply = resourceHelper.gs(R.string.readstatusfailed) val reply = resourceHelper.gs(R.string.readstatusfailed)
sendSMS(Sms(receivedSms.phoneNumber, reply)) sendSMS(Sms(receivedSms.phoneNumber, reply))
@ -494,11 +492,11 @@ class SmsCommunicatorPlugin @Inject constructor(
override fun run() { override fun run() {
if (result.success) { if (result.success) {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled) var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -525,11 +523,11 @@ class SmsCommunicatorPlugin @Inject constructor(
if (result.success) { if (result.success) {
var replyText: String var replyText: String
replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -557,11 +555,11 @@ class SmsCommunicatorPlugin @Inject constructor(
if (result.success) { if (result.success) {
var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration)
else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -583,11 +581,11 @@ class SmsCommunicatorPlugin @Inject constructor(
override fun run() { override fun run() {
if (result.success) { if (result.success) {
var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcanceled) var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcanceled)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcancelfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcancelfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -612,11 +610,11 @@ class SmsCommunicatorPlugin @Inject constructor(
if (result.success) { if (result.success) {
var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration)
if (Config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) if (Config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -656,7 +654,7 @@ class SmsCommunicatorPlugin @Inject constructor(
String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered)
else else
String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
lastRemoteBolusTime = DateUtil.now() lastRemoteBolusTime = DateUtil.now()
if (isMeal) { if (isMeal) {
profileFunction.getProfile()?.let { currentProfile -> profileFunction.getProfile()?.let { currentProfile ->
@ -686,7 +684,7 @@ class SmsCommunicatorPlugin @Inject constructor(
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_bolusfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_bolusfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }
@ -725,11 +723,11 @@ class SmsCommunicatorPlugin @Inject constructor(
override fun run() { override fun run() {
if (result.success) { if (result.success) {
var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed)
replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
} }

View file

@ -6,10 +6,10 @@ import android.os.SystemClock
import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus
import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthReplyMessage import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthReplyMessage
import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthRequestMessage import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthRequestMessage
@ -17,7 +17,6 @@ import info.nightscout.androidaps.plugins.general.tidepool.messages.DatasetReply
import info.nightscout.androidaps.plugins.general.tidepool.messages.OpenDatasetRequestMessage import info.nightscout.androidaps.plugins.general.tidepool.messages.OpenDatasetRequestMessage
import info.nightscout.androidaps.plugins.general.tidepool.messages.UploadReplyMessage import info.nightscout.androidaps.plugins.general.tidepool.messages.UploadReplyMessage
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.InstanceId
import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -39,7 +38,7 @@ class TidepoolUploader @Inject constructor(
private val resourceHelper: ResourceHelper, private val resourceHelper: ResourceHelper,
private val sp: SP, private val sp: SP,
private val uploadChunk: UploadChunk, private val uploadChunk: UploadChunk,
private val configBuilderPlugin: ConfigBuilderPlugin private val activePlugin: ActivePluginProvider
) { ) {
private var wl: PowerManager.WakeLock? = null private var wl: PowerManager.WakeLock? = null
@ -151,8 +150,7 @@ class TidepoolUploader @Inject constructor(
if (session.datasetReply == null) { if (session.datasetReply == null) {
rxBus.send(EventTidepoolStatus(("Creating new dataset"))) rxBus.send(EventTidepoolStatus(("Creating new dataset")))
val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!, val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!,
OpenDatasetRequestMessage((configBuilderPlugin.activePumpPlugin?.serialNumber() OpenDatasetRequestMessage(activePlugin.activePump.serialNumber()).getBody())
?: InstanceId.instanceId())).getBody())
call.enqueue(TidepoolCallback<DatasetReplyMessage>(rxBus, session, "Open New Dataset", { call.enqueue(TidepoolCallback<DatasetReplyMessage>(rxBus, session, "Open New Dataset", {
connectionStatus = ConnectionStatus.CONNECTED connectionStatus = ConnectionStatus.CONNECTED
rxBus.send(EventTidepoolStatus(("New dataset OK"))) rxBus.send(EventTidepoolStatus(("New dataset OK")))

View file

@ -5,22 +5,18 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals import info.nightscout.androidaps.data.Intervals
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper
import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.general.tidepool.elements.* import info.nightscout.androidaps.plugins.general.tidepool.elements.*
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus
import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.InstanceId
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.slf4j.LoggerFactory
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -33,13 +29,11 @@ class UploadChunk @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val treatmentsPlugin: TreatmentsPlugin, private val treatmentsPlugin: TreatmentsPlugin,
private val configBuilderPlugin: ConfigBuilderPlugin private val activePlugin: ActivePluginProvider
) { ) {
private val MAX_UPLOAD_SIZE = T.days(7).msecs() // don't change this private val MAX_UPLOAD_SIZE = T.days(7).msecs() // don't change this
private val log = StacktraceLoggerWrapper.getLogger(L.TIDEPOOL)
fun getNext(session: Session?): String? { fun getNext(session: Session?): String? {
if (session == null) if (session == null)
return null return null
@ -49,7 +43,7 @@ class UploadChunk @Inject constructor(
val result = get(session.start, session.end) val result = get(session.start, session.end)
if (result.length < 3) { if (result.length < 3) {
if (L.isEnabled(L.TIDEPOOL)) log.debug("No records in this time period, setting start to best end time") aapsLogger.debug(LTag.TIDEPOOL, "No records in this time period, setting start to best end time")
setLastEnd(Math.max(session.end, getOldestRecordTimeStamp())) setLastEnd(Math.max(session.end, getOldestRecordTimeStamp()))
} }
return result return result
@ -57,13 +51,13 @@ class UploadChunk @Inject constructor(
operator fun get(start: Long, end: Long): String { operator fun get(start: Long, end: Long): String {
if (L.isEnabled(L.TIDEPOOL)) log.debug("Syncing data between: " + DateUtil.dateAndTimeString(start) + " -> " + DateUtil.dateAndTimeString(end)) aapsLogger.debug(LTag.TIDEPOOL, "Syncing data between: " + DateUtil.dateAndTimeString(start) + " -> " + DateUtil.dateAndTimeString(end))
if (end <= start) { if (end <= start) {
if (L.isEnabled(L.TIDEPOOL)) log.debug("End is <= start: " + DateUtil.dateAndTimeString(start) + " " + DateUtil.dateAndTimeString(end)) aapsLogger.debug(LTag.TIDEPOOL, "End is <= start: " + DateUtil.dateAndTimeString(start) + " " + DateUtil.dateAndTimeString(end))
return "" return ""
} }
if (end - start > MAX_UPLOAD_SIZE) { if (end - start > MAX_UPLOAD_SIZE) {
if (L.isEnabled(L.TIDEPOOL)) log.debug("More than max range - rejecting") aapsLogger.debug(LTag.TIDEPOOL, "More than max range - rejecting")
return "" return ""
} }
@ -162,8 +156,7 @@ class UploadChunk @Inject constructor(
} }
fun newInstanceOrNull(ps: ProfileSwitch): ProfileElement? = try { fun newInstanceOrNull(ps: ProfileSwitch): ProfileElement? = try {
ProfileElement(ps, configBuilderPlugin.activePumpPlugin?.serialNumber() ProfileElement(ps, activePlugin.activePump.serialNumber())
?: InstanceId.instanceId())
} catch (e: Throwable) { } catch (e: Throwable) {
null null
} }

View file

@ -66,7 +66,8 @@ class ActionStringHandler @Inject constructor(
private val danaRv2Plugin: DanaRv2Plugin, private val danaRv2Plugin: DanaRv2Plugin,
private val danaRSPlugin: DanaRSPlugin, private val danaRSPlugin: DanaRSPlugin,
private val danaRPump: DanaRPump, private val danaRPump: DanaRPump,
private val hardLimits: HardLimits private val hardLimits: HardLimits,
private val carbsGenerator: CarbsGenerator
) { ) {
private val TIMEOUT = 65 * 1000 private val TIMEOUT = 65 * 1000
@ -240,8 +241,8 @@ class ActionStringHandler @Inject constructor(
rAction = actionString rAction = actionString
} }
} else if ("tddstats" == act[0]) { } else if ("tddstats" == act[0]) {
val activePump = activePlugin.activePumpPlugin val activePump = activePlugin.activePump
if (activePump != null) { // check if DB up to date // check if DB up to date
val dummies: MutableList<TDD> = LinkedList() val dummies: MutableList<TDD> = LinkedList()
val historyList = getTDDList(dummies) val historyList = getTDDList(dummies)
if (isOldData(historyList)) { if (isOldData(historyList)) {
@ -270,7 +271,6 @@ class ActionStringHandler @Inject constructor(
rAction = "statusmessage" rAction = "statusmessage"
rMessage = generateTDDMessage(historyList, dummies) rMessage = generateTDDMessage(historyList, dummies)
} }
}
} else if ("ecarbs" == act[0]) { ////////////////////////////////////////////// ECARBS } else if ("ecarbs" == act[0]) { ////////////////////////////////////////////// ECARBS
val carbs = SafeParse.stringToInt(act[1]) val carbs = SafeParse.stringToInt(act[1])
val starttime = SafeParse.stringToInt(act[2]) val starttime = SafeParse.stringToInt(act[2])
@ -316,13 +316,13 @@ class ActionStringHandler @Inject constructor(
val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault())
var message = "" var message = ""
val refTDD = profile.baseBasalSum() * 2 val refTDD = profile.baseBasalSum() * 2
val pump = activePlugin.activePumpPlugin val pump = activePlugin.activePump
if (df.format(Date(historyList[0].date)) == df.format(Date())) { if (df.format(Date(historyList[0].date)) == df.format(Date())) {
val tdd = historyList[0].getTotal() val tdd = historyList[0].getTotal()
historyList.removeAt(0) historyList.removeAt(0)
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n"
message += "\n" message += "\n"
} else if (pump != null && pump is DanaRPlugin) { } else if (pump is DanaRPlugin) {
val tdd = danaRPump.dailyTotalUnits val tdd = danaRPump.dailyTotalUnits
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n"
message += "\n" message += "\n"
@ -360,7 +360,7 @@ class ActionStringHandler @Inject constructor(
} }
private fun isOldData(historyList: List<TDD>): Boolean { private fun isOldData(historyList: List<TDD>): Boolean {
val activePump = activePlugin.activePumpPlugin ?: return false val activePump = activePlugin.activePump
val startsYesterday = activePump === danaRPlugin || activePump === danaRSPlugin || activePump === danaRv2Plugin || activePump === danaRKoreanPlugin || activePump === localInsightPlugin val startsYesterday = activePump === danaRPlugin || activePump === danaRSPlugin || activePump === danaRv2Plugin || activePump === danaRKoreanPlugin || activePump === localInsightPlugin
val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault())
return historyList.size < 3 || df.format(Date(historyList[0].date)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) return historyList.size < 3 || df.format(Date(historyList[0].date)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0))
@ -391,7 +391,7 @@ class ActionStringHandler @Inject constructor(
} }
private val pumpStatus: String private val pumpStatus: String
get() = activePlugin.activePumpPlugin?.shortStatus(false) ?: "" get() = activePlugin.activePump.shortStatus(false)
// decide if enabled/disabled closed/open; what Plugin as APS? // decide if enabled/disabled closed/open; what Plugin as APS?
private val loopStatus: String private val loopStatus: String
@ -405,7 +405,7 @@ class ActionStringHandler @Inject constructor(
"OPEN LOOP\n" "OPEN LOOP\n"
} }
val aps = activePlugin.activeAPS val aps = activePlugin.activeAPS
ret += "APS: " + if (aps == null) "NO APS SELECTED!" else (aps as PluginBase).name ret += "APS: " + (aps as PluginBase).name
if (loopPlugin.lastRun != null) { if (loopPlugin.lastRun != null) {
if (loopPlugin.lastRun.lastAPSRun != null) ret += "\nLast Run: " + DateUtil.timeString(loopPlugin.lastRun.lastAPSRun) if (loopPlugin.lastRun.lastAPSRun != null) ret += "\nLast Run: " + DateUtil.timeString(loopPlugin.lastRun.lastAPSRun)
if (loopPlugin.lastRun.lastTBREnact != 0L) ret += "\nLast Enact: " + DateUtil.timeString(loopPlugin.lastRun.lastTBREnact) if (loopPlugin.lastRun.lastTBREnact != 0L) ret += "\nLast Enact: " + DateUtil.timeString(loopPlugin.lastRun.lastTBREnact)
@ -442,9 +442,7 @@ class ActionStringHandler @Inject constructor(
var ret = "" var ret = ""
if (!Config.APS) if (!Config.APS)
return "Only apply in APS mode!" return "Only apply in APS mode!"
if (activePlugin.activePumpPlugin == null) val usedAPS = activePlugin.activeAPS
return resourceHelper.gs((R.string.nopumpselected))
val usedAPS = activePlugin.activeAPS ?: return "No active APS :(!"
val result = usedAPS.lastAPSResult ?: return "Last result not available!" val result = usedAPS.lastAPSResult ?: return "Last result not available!"
ret += if (!result.isChangeRequested) { ret += if (!result.isChangeRequested) {
resourceHelper.gs(R.string.nochangerequested) + "\n" resourceHelper.gs(R.string.nochangerequested) + "\n"
@ -519,9 +517,9 @@ class ActionStringHandler @Inject constructor(
private fun doECarbs(carbs: Int, time: Long, duration: Int) { private fun doECarbs(carbs: Int, time: Long, duration: Int) {
if (carbs > 0) { if (carbs > 0) {
if (duration == 0) { if (duration == 0) {
CarbsGenerator.createCarb(carbs, time, CareportalEvent.CARBCORRECTION, "watch") carbsGenerator.createCarb(carbs, time, CareportalEvent.CARBCORRECTION, "watch")
} else { } else {
CarbsGenerator.generateCarbs(carbs, time, duration, "watch eCarbs") carbsGenerator.generateCarbs(carbs, time, duration, "watch eCarbs")
} }
} }
} }
@ -587,7 +585,7 @@ class ActionStringHandler @Inject constructor(
detailedBolusInfo.insulin = amount detailedBolusInfo.insulin = amount
detailedBolusInfo.carbs = carbs.toDouble() detailedBolusInfo.carbs = carbs.toDouble()
detailedBolusInfo.source = Source.USER detailedBolusInfo.source = Source.USER
val storesCarbs = activePlugin.activePumpPlugin?.pumpDescription?.storesCarbInfo ?: return val storesCarbs = activePlugin.activePump.pumpDescription.storesCarbInfo
if (detailedBolusInfo.insulin > 0 || storesCarbs) { if (detailedBolusInfo.insulin > 0 || storesCarbs) {
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {

View file

@ -37,11 +37,11 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
@ -66,7 +66,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
@Inject public ProfileFunction profileFunction; @Inject public ProfileFunction profileFunction;
@Inject public DefaultValueHelper defaultValueHelper; @Inject public DefaultValueHelper defaultValueHelper;
@Inject public NSDeviceStatus nsDeviceStatus; @Inject public NSDeviceStatus nsDeviceStatus;
@Inject public ConfigBuilderPlugin configBuilderPlugin; @Inject public ActivePluginProvider activePlugin;
@Inject public LoopPlugin loopPlugin; @Inject public LoopPlugin loopPlugin;
@Inject public IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject public IobCobCalculatorPlugin iobCobCalculatorPlugin;
@Inject public TreatmentsPlugin treatmentsPlugin; @Inject public TreatmentsPlugin treatmentsPlugin;
@ -267,7 +267,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
} }
private void cancelBolus() { private void cancelBolus() {
configBuilderPlugin.getActivePump().stopBolusDelivering(); activePlugin.getActivePump().stopBolusDelivering();
} }
private void sendData() { private void sendData() {

View file

@ -117,7 +117,6 @@ class StatusLinePlugin @Inject constructor(
private fun buildStatusString(profile: Profile): String { private fun buildStatusString(profile: Profile): String {
var status = "" var status = ""
if (activePlugin.activePumpPlugin == null) return ""
if (!loopPlugin.isEnabled(PluginType.LOOP)) { if (!loopPlugin.isEnabled(PluginType.LOOP)) {
status += resourceHelper.gs(R.string.disabledloop) + "\n" status += resourceHelper.gs(R.string.disabledloop) + "\n"
lastLoopStatus = false lastLoopStatus = false

View file

@ -1,59 +0,0 @@
package info.nightscout.androidaps.plugins.insulin;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
/**
* Created by mike on 17.04.2017.
*/
public class InsulinFragment extends Fragment {
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
} catch (Exception e) {
FabricPrivacy.getInstance().logException(e);
}
return null;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(ConfigBuilderPlugin.getPlugin().getActiveInsulin().getFriendlyName());
insulinComment.setText(ConfigBuilderPlugin.getPlugin().getActiveInsulin().getComment());
insulinDia.setText(MainApp.gs(R.string.dia) + ": " + ConfigBuilderPlugin.getPlugin().getActiveInsulin().getDia() + "h");
insulinGraph.show(ConfigBuilderPlugin.getPlugin().getActiveInsulin());
}
}

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.plugins.insulin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.insulin_fragment.*
import javax.inject.Inject
class InsulinFragment : DaggerFragment() {
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var resourceHelper: ResourceHelper
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.insulin_fragment, container, false)
}
override fun onResume() {
super.onResume()
insulin_name?.setText(activePlugin.getActiveInsulin().getFriendlyName())
insulin_comment?.setText(activePlugin.getActiveInsulin().getComment())
insulin_dia?.text = resourceHelper.gs(R.string.dia) + ": " + activePlugin.getActiveInsulin().getDia() + "h"
insuling_graph?.show(activePlugin.getActiveInsulin())
}
}

View file

@ -40,5 +40,6 @@ class InsulinOrefRapidActingPlugin @Inject constructor(
pluginDescription pluginDescription
.pluginName(R.string.rapid_acting_oref) .pluginName(R.string.rapid_acting_oref)
.description(R.string.description_insulin_rapid) .description(R.string.description_insulin_rapid)
.setDefault()
} }
} }

View file

@ -29,13 +29,13 @@ import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
@ -61,7 +61,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final ConfigBuilderPlugin configBuilderPlugin; private final ActivePluginProvider activePlugin;
private final TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private final SensitivityOref1Plugin sensitivityOref1Plugin; private final SensitivityOref1Plugin sensitivityOref1Plugin;
private final SensitivityAAPSPlugin sensitivityAAPSPlugin; private final SensitivityAAPSPlugin sensitivityAAPSPlugin;
@ -98,7 +98,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
SP sp, SP sp,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
ConfigBuilderPlugin configBuilderPlugin, ActivePluginProvider activePlugin,
TreatmentsPlugin treatmentsPlugin, TreatmentsPlugin treatmentsPlugin,
SensitivityOref1Plugin sensitivityOref1Plugin, SensitivityOref1Plugin sensitivityOref1Plugin,
SensitivityAAPSPlugin sensitivityAAPSPlugin, SensitivityAAPSPlugin sensitivityAAPSPlugin,
@ -118,7 +118,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
this.rxBus = rxBus; this.rxBus = rxBus;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.configBuilderPlugin = configBuilderPlugin; this.activePlugin = activePlugin;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.sensitivityOref1Plugin = sensitivityOref1Plugin; this.sensitivityOref1Plugin = sensitivityOref1Plugin;
this.sensitivityAAPSPlugin = sensitivityAAPSPlugin; this.sensitivityAAPSPlugin = sensitivityAAPSPlugin;
@ -766,7 +766,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { AutosensResult detectSensitivityWithLock(long fromTime, long toTime) {
synchronized (dataLock) { synchronized (dataLock) {
return configBuilderPlugin.getActiveSensitivity().detectSensitivity(this, fromTime, toTime); return activePlugin.getActiveSensitivity().detectSensitivity(this, fromTime, toTime);
} }
} }

View file

@ -94,7 +94,7 @@ class LocalProfileFragment : DaggerFragment() {
} }
fun build() { fun build() {
val pumpDescription = activePlugin.activePumpPlugin?.pumpDescription ?: return val pumpDescription = activePlugin.activePump.pumpDescription
val units = if (localProfilePlugin.currentProfile().mgdl) Constants.MGDL else Constants.MMOL val units = if (localProfilePlugin.currentProfile().mgdl) Constants.MGDL else Constants.MMOL
localprofile_name.removeTextChangedListener(textWatch) localprofile_name.removeTextChangedListener(textWatch)

View file

@ -44,7 +44,8 @@ class LocalProfilePlugin @Inject constructor(
.enableByDefault(true) .enableByDefault(true)
.pluginName(R.string.localprofile) .pluginName(R.string.localprofile)
.shortName(R.string.localprofile_shortname) .shortName(R.string.localprofile_shortname)
.description(R.string.description_profile_local), .description(R.string.description_profile_local)
.setDefault(),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
), ProfileInterface { ), ProfileInterface {

View file

@ -106,7 +106,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
switch (view.getId()) { switch (view.getId()) {
case R.id.combo_refresh_button: case R.id.combo_refresh_button:
refreshButton.setEnabled(false); refreshButton.setEnabled(false);
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("User request", new Callback() { commandQueue.readStatus("User request", new Callback() {
@Override @Override
public void run() { public void run() {
runOnUiThread(() -> refreshButton.setEnabled(true)); runOnUiThread(() -> refreshButton.setEnabled(true));

View file

@ -1,59 +0,0 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
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.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
public class RileyLinkBluetoothStateReceiver extends BroadcastReceiver {
private static Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP);
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
PumpInterface activePump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (action != null && activePump != null) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
case BluetoothAdapter.STATE_TURNING_OFF:
case BluetoothAdapter.STATE_TURNING_ON:
break;
case BluetoothAdapter.STATE_ON: {
LOG.debug("RileyLinkBluetoothStateReceiver: Bluetooth back on. Sending broadcast to RileyLink Framework");
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected);
}
break;
}
}
}
public void unregisterBroadcasts() {
MainApp.instance().unregisterReceiver(this);
}
public void registerBroadcasts() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
MainApp.instance().registerReceiver(this, filter);
}
}

View file

@ -0,0 +1,43 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import javax.inject.Inject
class RileyLinkBluetoothStateReceiver : BroadcastReceiver() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activePlugin: ActivePluginProvider
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action != null) {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
when (state) {
BluetoothAdapter.STATE_OFF, BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_TURNING_ON -> {
}
BluetoothAdapter.STATE_ON -> {
aapsLogger.debug("RileyLinkBluetoothStateReceiver: Bluetooth back on. Sending broadcast to RileyLink Framework")
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected)
}
}
}
}
fun unregisterBroadcasts(context: Context) {
context.unregisterReceiver(this)
}
fun registerBroadcasts(context: Context) {
val filter = IntentFilter()
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
context.registerReceiver(this, filter)
}
}

View file

@ -95,7 +95,7 @@ public abstract class RileyLinkService extends Service {
} }
if (bluetoothStateReceiver!=null) { if (bluetoothStateReceiver!=null) {
bluetoothStateReceiver.unregisterBroadcasts(); bluetoothStateReceiver.unregisterBroadcasts(this);
} }
} }
@ -111,7 +111,7 @@ public abstract class RileyLinkService extends Service {
bluetoothStateReceiver = new RileyLinkBluetoothStateReceiver(); bluetoothStateReceiver = new RileyLinkBluetoothStateReceiver();
bluetoothStateReceiver.registerBroadcasts(); bluetoothStateReceiver.registerBroadcasts(this);
//LOG.debug("onCreate(): It's ALIVE!"); //LOG.debug("onCreate(): It's ALIVE!");
} }

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRS.services; package info.nightscout.androidaps.plugins.pump.danaRS.services;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Binder; import android.os.Binder;
import android.os.IBinder; import android.os.IBinder;
@ -10,7 +11,6 @@ import javax.inject.Inject;
import dagger.android.DaggerService; import dagger.android.DaggerService;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -26,7 +26,6 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@ -95,8 +94,7 @@ public class DanaRSService extends DaggerService {
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject CommandQueueProvider commandQueue; @Inject CommandQueueProvider commandQueue;
@Inject MainApp mainApp; @Inject Context context;
@Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject DanaRSPlugin danaRSPlugin; @Inject DanaRSPlugin danaRSPlugin;
@Inject DanaRPump danaRPump; @Inject DanaRPump danaRPump;
@Inject DanaRSMessageHashTable danaRSMessageHashTable; @Inject DanaRSMessageHashTable danaRSMessageHashTable;
@ -175,7 +173,7 @@ public class DanaRSService extends DaggerService {
danaRPump.setLastConnection(System.currentTimeMillis()); danaRPump.setLastConnection(System.currentTimeMillis());
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
PumpInterface pump = configBuilderPlugin.getActivePump(); PumpInterface pump = activePlugin.getActivePump();
if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) { if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal
@ -215,12 +213,12 @@ public class DanaRSService extends DaggerService {
if (Math.abs(timeDiff) > 60 * 60 * 1.5) { if (Math.abs(timeDiff) > 60 * 60 * 1.5) {
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds - large difference"); aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds - large difference");
//If time-diff is very large, warn user until we can synchronize history readings properly //If time-diff is very large, warn user until we can synchronize history readings properly
Intent i = new Intent(mainApp, ErrorHelperActivity.class); Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.error); i.putExtra("soundid", R.raw.error);
i.putExtra("status", resourceHelper.gs(R.string.largetimediff)); i.putExtra("status", resourceHelper.gs(R.string.largetimediff));
i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle)); i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainApp.startActivity(i); context.startActivity(i);
//deinitialize pump //deinitialize pump
danaRPump.setLastConnection(0); danaRPump.setLastConnection(0);

View file

@ -24,6 +24,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
@ -83,7 +84,7 @@ import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
@ -99,6 +100,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
@Inject DanaRPlugin danaRPlugin; @Inject DanaRPlugin danaRPlugin;
@Inject DanaRKoreanPlugin danaRKoreanPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin;
@Inject DanaRv2Plugin danaRv2Plugin; @Inject DanaRv2Plugin danaRv2Plugin;
@Inject ActivePluginProvider activePlugin;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject CommandQueueProvider commandQueue; @Inject CommandQueueProvider commandQueue;
@Inject Context context; @Inject Context context;
@ -106,6 +108,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
@Inject DetailedBolusInfoStorage detailedBolusInfoStorage; @Inject DetailedBolusInfoStorage detailedBolusInfoStorage;
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject SP sp;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -215,7 +218,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
danaRPump.setLastConnection(System.currentTimeMillis()); danaRPump.setLastConnection(System.currentTimeMillis());
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); PumpInterface pump = activePlugin.getActivePump();
if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) { if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin)); mSerialIOThread.sendMessage(new MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin));
@ -385,7 +388,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))); rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus)));
mBolusingTreatment = t; mBolusingTreatment = t;
final int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); final int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0);
MessageBase start; MessageBase start;
if (preferencesSpeed == 0) if (preferencesSpeed == 0)
start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount); start = new MsgBolusStart(aapsLogger, constraintChecker, danaRPump, amount);
@ -447,7 +450,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
SystemClock.sleep(1000); SystemClock.sleep(1000);
} }
// do not call loadEvents() directly, reconnection may be needed // do not call loadEvents() directly, reconnection may be needed
ConfigBuilderPlugin.getPlugin().getCommandQueue().loadEvents(new Callback() { commandQueue.loadEvents(new Callback() {
@Override @Override
public void run() { public void run() {
// load last bolus status // load last bolus status

View file

@ -22,7 +22,6 @@ import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock; import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus;
@ -32,6 +31,7 @@ import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose; import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose;
import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI; import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
@ -40,6 +40,7 @@ import io.reactivex.disposables.CompositeDisposable;
public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener { public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener {
@Inject LocalInsightPlugin localInsightPlugin; @Inject LocalInsightPlugin localInsightPlugin;
@Inject CommandQueue commandQueue;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -110,10 +111,10 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
switch (localInsightPlugin.getOperatingMode()) { switch (localInsightPlugin.getOperatingMode()) {
case PAUSED: case PAUSED:
case STOPPED: case STOPPED:
ConfigBuilderPlugin.getPlugin().getCommandQueue().startPump(operatingModeCallback); commandQueue.startPump(operatingModeCallback);
break; break;
case STARTED: case STARTED:
ConfigBuilderPlugin.getPlugin().getCommandQueue().stopPump(operatingModeCallback); commandQueue.stopPump(operatingModeCallback);
} }
} }
} else if (v == tbrOverNotification) { } else if (v == tbrOverNotification) {
@ -129,8 +130,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
}); });
} }
}; };
ConfigBuilderPlugin.getPlugin().getCommandQueue() commandQueue.setTBROverNotification(tbrOverNotificationCallback, !notificationBlock.isEnabled());
.setTBROverNotification(tbrOverNotificationCallback, !notificationBlock.isEnabled());
} }
} else if (v == refresh) { } else if (v == refresh) {
refresh.setEnabled(false); refresh.setEnabled(false);
@ -143,7 +143,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
}); });
} }
}; };
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("InsightRefreshButton", refreshCallback); commandQueue.readStatus("InsightRefreshButton", refreshCallback);
} }
} }

View file

@ -58,7 +58,8 @@ class VirtualPumpPlugin @Inject constructor(
.shortName(R.string.virtualpump_shortname) .shortName(R.string.virtualpump_shortname)
.preferencesId(R.xml.pref_virtualpump) .preferencesId(R.xml.pref_virtualpump)
.neverVisible(Config.NSCLIENT) .neverVisible(Config.NSCLIENT)
.description(R.string.description_pump_virtual), .description(R.string.description_pump_virtual)
.setDefault(),
injector, aapsLogger, resourceHelper, commandQueue injector, aapsLogger, resourceHelper, commandQueue
), PumpInterface { ), PumpInterface {

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.sensitivity; package info.nightscout.androidaps.plugins.sensitivity;
import androidx.annotation.NonNull;
import androidx.collection.LongSparseArray; import androidx.collection.LongSparseArray;
import java.util.ArrayList; import java.util.ArrayList;
@ -19,7 +20,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
@ -35,13 +36,16 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
private SP sp; private SP sp;
private ProfileFunction profileFunction;
private ResourceHelper resourceHelper;
@Inject @Inject
public SensitivityAAPSPlugin( public SensitivityAAPSPlugin(
HasAndroidInjector injector, HasAndroidInjector injector,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
SP sp SP sp,
ProfileFunction profileFunction
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.SENSITIVITY) .mainType(PluginType.SENSITIVITY)
@ -52,20 +56,21 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
injector, aapsLogger, resourceHelper, sp injector, aapsLogger, resourceHelper, sp
); );
this.sp = sp; this.sp = sp;
this.profileFunction = profileFunction;
} }
@Override @NonNull @Override
public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) {
LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
String age = sp.getString(R.string.key_age, ""); String age = sp.getString(R.string.key_age, "");
int defaultHours = 24; int defaultHours = 24;
if (age.equals(MainApp.gs(R.string.key_adult))) defaultHours = 24; if (age.equals(resourceHelper.gs(R.string.key_adult))) defaultHours = 24;
if (age.equals(MainApp.gs(R.string.key_teenage))) defaultHours = 4; if (age.equals(resourceHelper.gs(R.string.key_teenage))) defaultHours = 4;
if (age.equals(MainApp.gs(R.string.key_child))) defaultHours = 4; if (age.equals(resourceHelper.gs(R.string.key_child))) defaultHours = 4;
int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours); int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours);
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = profileFunction.getProfile();
if (profile == null) { if (profile == null) {
getAapsLogger().error("No profile"); getAapsLogger().error("No profile");

View file

@ -49,7 +49,8 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin {
.pluginName(R.string.sensitivityoref0) .pluginName(R.string.sensitivityoref0)
.shortName(R.string.sensitivity_shortname) .shortName(R.string.sensitivity_shortname)
.preferencesId(R.xml.pref_absorption_oref0) .preferencesId(R.xml.pref_absorption_oref0)
.description(R.string.description_sensitivity_oref0), .description(R.string.description_sensitivity_oref0)
.setDefault(),
injector, aapsLogger, resourceHelper, sp injector, aapsLogger, resourceHelper, sp
); );
this.profileFunction = profileFunction; this.profileFunction = profileFunction;

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
@ -33,12 +33,15 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton @Singleton
public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
private ProfileFunction profileFunction;
@Inject @Inject
public SensitivityOref1Plugin( public SensitivityOref1Plugin(
HasAndroidInjector injector, HasAndroidInjector injector,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
SP sp SP sp,
ProfileFunction profileFunction
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.SENSITIVITY) .mainType(PluginType.SENSITIVITY)
@ -49,6 +52,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
.description(R.string.description_sensitivity_oref1), .description(R.string.description_sensitivity_oref1),
injector, aapsLogger, resourceHelper, sp injector, aapsLogger, resourceHelper, sp
); );
this.profileFunction = profileFunction;
} }
@Override @Override
@ -57,7 +61,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
// dependency, this should be avoided // dependency, this should be avoided
LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = profileFunction.getProfile();
if (profile == null) { if (profile == null) {
getAapsLogger().error("No profile"); getAapsLogger().error("No profile");

View file

@ -38,7 +38,8 @@ class DexcomPlugin @Inject constructor(
.pluginName(R.string.dexcom_app_patched) .pluginName(R.string.dexcom_app_patched)
.shortName(R.string.dexcom_short) .shortName(R.string.dexcom_short)
.preferencesId(R.xml.pref_bgsourcedexcom) .preferencesId(R.xml.pref_bgsourcedexcom)
.description(R.string.description_source_dexcom), .description(R.string.description_source_dexcom)
.setDefault(),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
), BgSourceInterface { ), BgSourceInterface {

View file

@ -1,59 +0,0 @@
package info.nightscout.androidaps.plugins.treatments;
import android.content.Intent;
import androidx.annotation.Nullable;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.T;
import static info.nightscout.androidaps.utils.DateUtil.now;
public class CarbsGenerator {
public static void generateCarbs(int amount, long startTime, int duration, @Nullable String notes) {
long remainingCarbs = amount;
int ticks = (duration * 4); //duration guaranteed to be integer greater zero
for (int i = 0; i < ticks; i++){
long carbTime = startTime + i * 15 * 60 * 1000;
int smallCarbAmount = (int) Math.round((1d * remainingCarbs) / (ticks-i)); //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs
remainingCarbs -= smallCarbAmount;
if (smallCarbAmount > 0)
createCarb(smallCarbAmount, carbTime, CareportalEvent.MEALBOLUS, notes);
}
}
public static void createCarb(int carbs, long time, String eventType, @Nullable String notes) {
DetailedBolusInfo carbInfo = new DetailedBolusInfo();
carbInfo.date = time;
carbInfo.eventType = eventType;
carbInfo.carbs = carbs;
carbInfo.context = MainApp.instance();
carbInfo.source = Source.USER;
carbInfo.notes = notes;
if (ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo && carbInfo.date <= now() && carbInfo.date > now()- T.mins(2).msecs()) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(carbInfo, 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.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
} else {
// Don't send to pump if it is in the future or more than 5 minutes in the past
// as pumps might return those as as "now" when reading the history.
TreatmentsPlugin.getPlugin().addToHistoryTreatment(carbInfo, false);
}
}
}

View file

@ -0,0 +1,65 @@
package info.nightscout.androidaps.plugins.treatments
import android.content.Context
import android.content.Intent
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class CarbsGenerator @Inject constructor(
private val resourceHelper: ResourceHelper,
private val activePlugin: ActivePluginProvider,
private val commandQueue: CommandQueueProvider,
private val context: Context
) {
fun generateCarbs(amount: Int, startTime: Long, duration: Int, notes: String) {
var remainingCarbs = amount.toLong()
val ticks = duration * 4 //duration guaranteed to be integer greater zero
for (i in 0 until ticks) {
val carbTime = startTime + i * 15 * 60 * 1000
val smallCarbAmount = Math.round(1.0 * remainingCarbs / (ticks - i)).toInt() //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs
remainingCarbs -= smallCarbAmount.toLong()
if (smallCarbAmount > 0) createCarb(smallCarbAmount, carbTime, CareportalEvent.MEALBOLUS, notes)
}
}
fun createCarb(carbs: Int, time: Long, eventType: String, notes: String) {
val carbInfo = DetailedBolusInfo()
carbInfo.date = time
carbInfo.eventType = eventType
carbInfo.carbs = carbs.toDouble()
carbInfo.context = context
carbInfo.source = Source.USER
carbInfo.notes = notes
if (activePlugin.activePump.pumpDescription.storesCarbInfo && carbInfo.date <= DateUtil.now() && carbInfo.date > DateUtil.now() - T.mins(2).msecs()) {
commandQueue.bolus(carbInfo, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(context, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
}
})
} else {
// Don't send to pump if it is in the future or more than 5 minutes in the past
// as pumps might return those as as "now" when reading the history.
activePlugin.activeTreatments.addToHistoryTreatment(carbInfo, false)
}
}
}

View file

@ -23,8 +23,8 @@ import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DbObjectBase; import info.nightscout.androidaps.db.DbObjectBase;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
@ -39,7 +39,7 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase {
@Inject public DefaultValueHelper defaultValueHelper; @Inject public DefaultValueHelper defaultValueHelper;
@Inject public ResourceHelper resourceHelper; @Inject public ResourceHelper resourceHelper;
@Inject public ProfileFunction profileFunction; @Inject public ProfileFunction profileFunction;
@Inject public ConfigBuilderPlugin configBuilderPlugin; @Inject public ActivePluginProvider activePlugin;
public static final String TABLE_TREATMENTS = "Treatments"; public static final String TABLE_TREATMENTS = "Treatments";
@ -290,7 +290,7 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase {
if (!isValid) if (!isValid)
return new Iob(); return new Iob();
InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); InsulinInterface insulinInterface = activePlugin.getActiveInsulin();
return insulinInterface.iobCalcForTreatment(this, time, dia); return insulinInterface.iobCalcForTreatment(this, time, dia);
} }

View file

@ -9,8 +9,8 @@ import androidx.fragment.app.FragmentTransaction
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.treatments.fragments.* import info.nightscout.androidaps.plugins.treatments.fragments.*
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.plusAssign
@ -24,14 +24,11 @@ class TreatmentsFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@Inject
lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject
lateinit var treatmentsPlugin: TreatmentsPlugin
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.treatments_fragment, container, false) return inflater.inflate(R.layout.treatments_fragment, container, false)
@ -103,8 +100,7 @@ class TreatmentsFragment : DaggerFragment() {
} }
private fun updateGui() { private fun updateGui() {
if (configBuilderPlugin.activePumpPlugin?.pumpDescription?.isExtendedBolusCapable == true if (activePlugin.activePump.pumpDescription.isExtendedBolusCapable || treatmentsPlugin.extendedBolusesFromHistory.size() > 0)
|| treatmentsPlugin.extendedBolusesFromHistory.size() > 0)
treatments_extendedboluses?.visibility = View.VISIBLE treatments_extendedboluses?.visibility = View.VISIBLE
else else
treatments_extendedboluses?.visibility = View.GONE treatments_extendedboluses?.visibility = View.GONE

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.treatments; package info.nightscout.androidaps.plugins.treatments;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@ -39,7 +40,7 @@ import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
@ -48,7 +49,6 @@ import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
@ -66,12 +66,12 @@ import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface {
private final MainApp mainApp; private final Context context;
private final SP sp; private final SP sp;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final ConfigBuilderPlugin configBuilderPlugin; private final ActivePluginProvider activePlugin;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -104,10 +104,10 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
MainApp mainApp, Context context,
SP sp, SP sp,
ProfileFunction profileFunction, ProfileFunction profileFunction,
ConfigBuilderPlugin configBuilderPlugin ActivePluginProvider activePlugin
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.TREATMENT) .mainType(PluginType.TREATMENT)
@ -115,15 +115,16 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
.pluginName(R.string.treatments) .pluginName(R.string.treatments)
.shortName(R.string.treatments_shortname) .shortName(R.string.treatments_shortname)
.alwaysEnabled(true) .alwaysEnabled(true)
.description(R.string.description_treatments), .description(R.string.description_treatments)
.setDefault(),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
); );
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.mainApp = mainApp; this.context = context;
this.rxBus = rxBus; this.rxBus = rxBus;
this.sp = sp; this.sp = sp;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.configBuilderPlugin = configBuilderPlugin; this.activePlugin = activePlugin;
treatmentsPlugin = this; treatmentsPlugin = this;
} }
@ -244,9 +245,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
if (profile == null) if (profile == null)
return total; return total;
PumpInterface pumpInterface = configBuilderPlugin.getActivePumpPlugin(); PumpInterface pumpInterface = activePlugin.getActivePump();
if (pumpInterface == null)
return total;
double dia = profile.getDia(); double dia = profile.getDia();
@ -401,11 +400,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) { public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) {
IobTotal total = new IobTotal(time); IobTotal total = new IobTotal(time);
InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); PumpInterface pumpInterface = activePlugin.getActivePump();
PumpInterface pumpInterface = configBuilderPlugin.getActivePumpPlugin();
if (pumpInterface == null)
return total;
synchronized (tempBasals) { synchronized (tempBasals) {
for (Integer pos = 0; pos < tempBasals.size(); pos++) { for (Integer pos = 0; pos < tempBasals.size(); pos++) {
@ -459,11 +454,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public IobTotal getCalculationToTimeTempBasals(long time, long truncateTime, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) { public IobTotal getCalculationToTimeTempBasals(long time, long truncateTime, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) {
IobTotal total = new IobTotal(time); IobTotal total = new IobTotal(time);
InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); PumpInterface pumpInterface = activePlugin.getActivePump();
PumpInterface pumpInterface = configBuilderPlugin.getActivePumpPlugin();
if (pumpInterface == null)
return total;
synchronized (tempBasals) { synchronized (tempBasals) {
for (int pos = 0; pos < tempBasals.size(); pos++) { for (int pos = 0; pos < tempBasals.size(); pos++) {
@ -526,7 +517,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
if (tb != null) if (tb != null)
return tb; return tb;
ExtendedBolus eb = getExtendedBolusFromHistory(time); ExtendedBolus eb = getExtendedBolusFromHistory(time);
if (eb != null && configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) if (eb != null && activePlugin.getActivePump().isFakingTempsByExtendedBoluses())
return new TemporaryBasal(eb); return new TemporaryBasal(eb);
return null; return null;
} }
@ -544,11 +535,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(extendedBolus); boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(extendedBolus);
if (newRecordCreated) { if (newRecordCreated) {
if (extendedBolus.durationInMinutes == 0) { if (extendedBolus.durationInMinutes == 0) {
if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses())
NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId);
else else
NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId);
} else if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) } else if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses())
NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin);
else else
NSUpload.uploadExtendedBolus(extendedBolus); NSUpload.uploadExtendedBolus(extendedBolus);
@ -640,12 +631,12 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date)); String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date));
Intent i = new Intent(mainApp, ErrorHelperActivity.class); Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.error); i.putExtra("soundid", R.raw.error);
i.putExtra("title", resourceHelper.gs(R.string.error_adding_treatment_title)); i.putExtra("title", resourceHelper.gs(R.string.error_adding_treatment_title));
i.putExtra("status", status); i.putExtra("status", status);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainApp.startActivity(i); context.startActivity(i);
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash"); bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash");
@ -745,7 +736,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
profileSwitch.source = Source.USER; profileSwitch.source = Source.USER;
profileSwitch.profileName = profileFunction.getProfileName(System.currentTimeMillis(), false, false); profileSwitch.profileName = profileFunction.getProfileName(System.currentTimeMillis(), false, false);
profileSwitch.profileJson = profileFunction.getProfile().getData().toString(); profileSwitch.profileJson = profileFunction.getProfile().getData().toString();
profileSwitch.profilePlugin = configBuilderPlugin.getActiveProfileInterface().getClass().getName(); profileSwitch.profilePlugin = activePlugin.getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration; profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeShift != 0; profileSwitch.isCPP = percentage != 100 || timeShift != 0;
profileSwitch.timeshift = timeShift; profileSwitch.timeshift = timeShift;

View file

@ -9,11 +9,14 @@ import dagger.Lazy
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.BolusProgressHelperActivity import info.nightscout.androidaps.activities.BolusProgressHelperActivity
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.dialogs.BolusProgressDialog import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventBolusRequested import info.nightscout.androidaps.events.EventBolusRequested
import info.nightscout.androidaps.events.EventNewBasalProfile
import info.nightscout.androidaps.events.EventProfileNeedsUpdate
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
@ -28,10 +31,13 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.queue.commands.*
import info.nightscout.androidaps.queue.commands.Command.CommandType import info.nightscout.androidaps.queue.commands.Command.CommandType
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.build.BuildHelper import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -88,14 +94,43 @@ class CommandQueue @Inject constructor(
val activePlugin: Lazy<ActivePluginProvider>, val activePlugin: Lazy<ActivePluginProvider>,
val context: Context, val context: Context,
val sp: SP, val sp: SP,
private val buildHelper: BuildHelper private val buildHelper: BuildHelper,
val fabricPrivacy: FabricPrivacy
) : CommandQueueProvider { ) : CommandQueueProvider {
private val disposable = CompositeDisposable()
private val queue = LinkedList<Command>() private val queue = LinkedList<Command>()
private var thread: QueueThread? = null private var thread: QueueThread? = null
var performing: Command? = null var performing: Command? = null
init {
disposable.add(rxBus
.toObservable(EventProfileNeedsUpdate::class.java)
.observeOn(Schedulers.io())
.subscribe({
aapsLogger.debug(LTag.PROFILE, "onProfileSwitch")
profileFunction.getProfile()?.let {
setProfile(it, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(context, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", resourceHelper.gs(R.string.failedupdatebasalprofile))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
if (result.enacted) rxBus.send(EventNewBasalProfile())
}
})
}
}) { exception: Throwable -> fabricPrivacy.logException(exception) }
)
}
private fun executingNowError(): PumpEnactResult = private fun executingNowError(): PumpEnactResult =
PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.executingrightnow)) PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.executingrightnow))
@ -172,7 +207,7 @@ class CommandQueue @Inject constructor(
override fun independentConnect(reason: String, callback: Callback?) { override fun independentConnect(reason: String, callback: Callback?) {
aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue")
val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper) val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, fabricPrivacy)
tempCommandQueue.readStatus(reason, callback) tempCommandQueue.readStatus(reason, callback)
} }

View file

@ -100,7 +100,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() {
var shouldUploadStatus = false var shouldUploadStatus = false
if (Config.NSCLIENT) return if (Config.NSCLIENT) return
if (Config.PUMPCONTROL) shouldUploadStatus = true if (Config.PUMPCONTROL) shouldUploadStatus = true
if (usedAPS == null || !loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null) if (!loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null)
shouldUploadStatus = true shouldUploadStatus = true
else if (DateUtil.isOlderThan(usedAPS.lastAPSRun, 5)) shouldUploadStatus = true else if (DateUtil.isOlderThan(usedAPS.lastAPSRun, 5)) shouldUploadStatus = true
if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY) && shouldUploadStatus) { if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY) && shouldUploadStatus) {
@ -110,7 +110,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() {
} }
private fun checkPump() { private fun checkPump() {
val pump = activePlugin.activePumpPlugin ?: return val pump = activePlugin.activePump
val profile = profileFunction.getProfile() ?: return val profile = profileFunction.getProfile() ?: return
val lastConnection = pump.lastDataTime() val lastConnection = pump.lastDataTime()
val isStatusOutdated = lastConnection + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis() val isStatusOutdated = lastConnection + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis()

View file

@ -1,46 +0,0 @@
package info.nightscout.androidaps.receivers;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
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;
public class TimeDateOrTZChangeReceiver extends BroadcastReceiver {
private static Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP);
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
PumpInterface activePump = ConfigBuilderPlugin.getPlugin().getActivePump();
LOG.debug("Date, Time and/or TimeZone changed.");
if (action != null && activePump != null) {
LOG.debug("Date, Time and/or TimeZone changed. Notifying pump driver.");
activePump.timeDateOrTimeZoneChanged();
}
}
public void registerBroadcasts(MainApp mainApp) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
mainApp.registerReceiver(this, filter);
}
}

View file

@ -0,0 +1,34 @@
package info.nightscout.androidaps.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
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 javax.inject.Inject
class TimeDateOrTZChangeReceiver : BroadcastReceiver() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activePlugin: ActivePluginProvider
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
val activePump: PumpInterface = activePlugin.getActivePump()
aapsLogger.debug(LTag.PUMP, "Date, Time and/or TimeZone changed.")
if (action != null) {
aapsLogger.debug(LTag.PUMP, "Date, Time and/or TimeZone changed. Notifying pump driver.")
activePump.timeDateOrTimeZoneChanged()
}
}
fun registerBroadcasts(context: Context) {
val filter = IntentFilter()
filter.addAction(Intent.ACTION_TIME_CHANGED)
filter.addAction(Intent.ACTION_DATE_CHANGED)
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED)
context.registerReceiver(this, filter)
}
}

View file

@ -243,8 +243,7 @@ class SWDefinition @Inject constructor(
}, null) }, null)
} }
} }
.visibility { activePlugin.activeBgSource != null && (activePlugin.activeBgSource as PluginBase).preferencesId > 0 }) .visibility { (activePlugin.activeBgSource as PluginBase).preferencesId > 0 })
.validator { activePlugin.activeBgSource != null }
private val screenProfile = SWScreen(R.string.configbuilder_profile) private val screenProfile = SWScreen(R.string.configbuilder_profile)
.skippable(false) .skippable(false)
.add(SWInfotext() .add(SWInfotext()
@ -265,7 +264,7 @@ class SWDefinition @Inject constructor(
.skippable(false) .skippable(false)
.add(SWFragment(this) .add(SWFragment(this)
.add(LocalProfileFragment())) .add(LocalProfileFragment()))
.validator { localProfilePlugin.getProfile()?.getDefaultProfile()?.isValid("StartupWizard") == true } .validator { localProfilePlugin.profile?.getDefaultProfile()?.isValid("StartupWizard") == true }
.visibility { localProfilePlugin.isEnabled(PluginType.PROFILE) } .visibility { localProfilePlugin.isEnabled(PluginType.PROFILE) }
private val screenProfileSwitch = SWScreen(R.string.careportal_profileswitch) private val screenProfileSwitch = SWScreen(R.string.careportal_profileswitch)
.skippable(false) .skippable(false)
@ -285,22 +284,19 @@ class SWDefinition @Inject constructor(
.add(SWButton() .add(SWButton()
.text(R.string.pumpsetup) .text(R.string.pumpsetup)
.action { .action {
val plugin = activePlugin.activePump as PluginBase? val plugin = activePlugin.activePump as PluginBase
if (plugin != null) {
PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable { PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", Runnable {
val i = Intent(activity, PreferencesActivity::class.java) val i = Intent(activity, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId) i.putExtra("id", plugin.preferencesId)
activity!!.startActivity(i) activity!!.startActivity(i)
}, null) }, null)
} }
} .visibility { (activePlugin.activePump as PluginBase).preferencesId > 0 })
.visibility { activePlugin.activePumpPlugin != null && (activePlugin.activePump as PluginBase?)!!.preferencesId > 0 })
.add(SWButton() .add(SWButton()
.text(R.string.readstatus) .text(R.string.readstatus)
.action { commandQueue.readStatus("Clicked connect to pump", null) } .action { commandQueue.readStatus("Clicked connect to pump", null) })
.visibility { activePlugin.activePumpPlugin != null })
.add(SWEventListener(resourceHelper, rxBus, EventPumpStatusChanged::class.java)) .add(SWEventListener(resourceHelper, rxBus, EventPumpStatusChanged::class.java))
.validator { activePlugin.activePumpPlugin != null && activePlugin.getActivePumpPlugin()!!.isInitialized() } .validator { activePlugin.activePump.isInitialized }
private val screenAps = SWScreen(R.string.configbuilder_aps) private val screenAps = SWScreen(R.string.configbuilder_aps)
.skippable(false) .skippable(false)
.add(SWInfotext() .add(SWInfotext()
@ -324,8 +320,7 @@ class SWDefinition @Inject constructor(
}, null) }, null)
} }
} }
.visibility { activePlugin.activeAPS != null && (activePlugin.activeAPS as PluginBase?)!!.preferencesId > 0 }) .visibility { (activePlugin.activeAPS as PluginBase).preferencesId > 0 })
.validator { activePlugin.activeAPS != null }
.visibility { Config.APS } .visibility { Config.APS }
private val screenApsMode = SWScreen(R.string.apsmode_title) private val screenApsMode = SWScreen(R.string.apsmode_title)
.skippable(false) .skippable(false)
@ -386,11 +381,11 @@ class SWDefinition @Inject constructor(
.validator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted } .validator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted }
.visibility { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && Config.APS } .visibility { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && Config.APS }
private fun SWDefinitionFull() { // List all the screens here private fun swDefinitionFull() { // List all the screens here
add(screenSetupWizard) add(screenSetupWizard)
.add(screenLanguage) .add(screenLanguage)
.add(screenEula) .add(screenEula)
.add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimalization .add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimization
.add(screenPermissionBt) .add(screenPermissionBt)
.add(screenPermissionStore) .add(screenPermissionStore)
.add(screenImport) .add(screenImport)
@ -412,11 +407,11 @@ class SWDefinition @Inject constructor(
.add(getScreenObjectives) .add(getScreenObjectives)
} }
private fun SWDefinitionPumpControl() { // List all the screens here private fun swDefinitionPumpControl() { // List all the screens here
add(screenSetupWizard) add(screenSetupWizard)
.add(screenLanguage) .add(screenLanguage)
.add(screenEula) .add(screenEula)
.add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimalization .add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimization
.add(screenPermissionBt) .add(screenPermissionBt)
.add(screenPermissionStore) .add(screenPermissionStore)
.add(screenImport) .add(screenImport)
@ -434,11 +429,11 @@ class SWDefinition @Inject constructor(
.add(screenSensitivity) .add(screenSensitivity)
} }
private fun SWDefinitionNSClient() { // List all the screens here private fun swDefinitionNSClient() { // List all the screens here
add(screenSetupWizard) add(screenSetupWizard)
.add(screenLanguage) .add(screenLanguage)
.add(screenEula) .add(screenEula)
.add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimalization .add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimization
.add(screenPermissionStore) .add(screenPermissionStore)
.add(screenImport) .add(screenImport)
.add(screenUnits) .add(screenUnits)
@ -451,6 +446,6 @@ class SWDefinition @Inject constructor(
} }
init { init {
if (Config.APS) SWDefinitionFull() else if (Config.PUMPCONTROL) SWDefinitionPumpControl() else if (Config.NSCLIENT) SWDefinitionNSClient() if (Config.APS) swDefinitionFull() else if (Config.PUMPCONTROL) swDefinitionPumpControl() else if (Config.NSCLIENT) swDefinitionNSClient()
} }
} }

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
@ -54,7 +55,7 @@ public class SWCheckbox extends SWItem {
@Override @Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) { public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
ArrayList<PluginBase> pluginsInCategory; ArrayList<PluginBase> pluginsInCategory;
pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.PUMP); pluginsInCategory = PluginStore.Companion.getInstance().getSpecificPluginsList(PluginType.PUMP);
PluginBase found = null; PluginBase found = null;
for (PluginBase p : pluginsInCategory) { for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(PluginType.PUMP) && found == null) { if (p.isEnabled(PluginType.PUMP) && found == null) {

View file

@ -9,17 +9,16 @@ import android.widget.RadioGroup;
import android.widget.TextView; import android.widget.TextView;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate; import info.nightscout.androidaps.setupwizard.events.EventSWUpdate;
public class SWPlugin extends SWItem { public class SWPlugin extends SWItem {
@ -53,7 +52,7 @@ public class SWPlugin extends SWItem {
radioGroup = new RadioGroup(context); radioGroup = new RadioGroup(context);
radioGroup.clearCheck(); radioGroup.clearCheck();
ArrayList<PluginBase> pluginsInCategory = MainApp.getSpecificPluginsList(pType); ArrayList<PluginBase> pluginsInCategory = PluginStore.Companion.getInstance().getSpecificPluginsList(pType);
radioGroup.setOrientation(LinearLayout.VERTICAL); radioGroup.setOrientation(LinearLayout.VERTICAL);
radioGroup.setVisibility(View.VISIBLE); radioGroup.setVisibility(View.VISIBLE);

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.utils;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
/** /**
* Created by mike on 11.07.2016. * Created by mike on 11.07.2016.
@ -46,13 +46,13 @@ public class DecimalFormatter {
} }
public static String toPumpSupportedBolus(double value) { public static String toPumpSupportedBolus(double value) {
return ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().bolusStep <= 0.051 return PluginStore.Companion.getInstance().getActivePump().getPumpDescription().bolusStep <= 0.051
? to2Decimal(value) ? to2Decimal(value)
: to1Decimal(value); : to1Decimal(value);
} }
public static DecimalFormat pumpSupportedBolusFormat() { public static DecimalFormat pumpSupportedBolusFormat() {
return ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().bolusStep <= 0.051 return PluginStore.Companion.getInstance().getActivePump().getPumpDescription().bolusStep <= 0.051
? new DecimalFormat("0.00") ? new DecimalFormat("0.00")
: new DecimalFormat("0.0"); : new DecimalFormat("0.0");
} }

View file

@ -6,9 +6,9 @@ import com.google.firebase.analytics.FirebaseAnalytics
import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -28,7 +28,7 @@ class FabricPrivacy @Inject constructor(
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
private val mainApp: MainApp, private val mainApp: MainApp,
private val signatureVerifierPlugin: SignatureVerifierPlugin, private val signatureVerifierPlugin: SignatureVerifierPlugin,
private val configBuilderPlugin: ConfigBuilderPlugin private val activePlugin: ActivePluginProvider
) { ) {
init { init {
@ -37,6 +37,7 @@ class FabricPrivacy @Inject constructor(
companion object { companion object {
private lateinit var instance: FabricPrivacy private lateinit var instance: FabricPrivacy
@JvmStatic @JvmStatic
fun getInstance(): FabricPrivacy = instance fun getInstance(): FabricPrivacy = instance
} }
@ -129,11 +130,11 @@ class FabricPrivacy @Inject constructor(
mainApp.firebaseAnalytics.setUserProperty("Remote", remote) mainApp.firebaseAnalytics.setUserProperty("Remote", remote)
val hashes: List<String> = signatureVerifierPlugin.shortHashes() val hashes: List<String> = signatureVerifierPlugin.shortHashes()
if (hashes.isNotEmpty()) mainApp.firebaseAnalytics.setUserProperty("Hash", hashes[0]) if (hashes.isNotEmpty()) mainApp.firebaseAnalytics.setUserProperty("Hash", hashes[0])
configBuilderPlugin.activePumpPlugin?.let { mainApp.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } activePlugin.activePump.let { mainApp.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) }
configBuilderPlugin.activeAPS?.let { mainApp.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } activePlugin.activeAPS.let { mainApp.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) }
configBuilderPlugin.activeBgSource?.let { mainApp.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) } activePlugin.activeBgSource.let { mainApp.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) }
mainApp.firebaseAnalytics.setUserProperty("Profile", configBuilderPlugin.activeProfileInterface.javaClass.simpleName) mainApp.firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName)
configBuilderPlugin.activeSensitivity.let { mainApp.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } activePlugin.activeSensitivity.let { mainApp.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) }
configBuilderPlugin.activeInsulin.let { mainApp.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } activePlugin.activeInsulin.let { mainApp.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) }
} }
} }

View file

@ -79,9 +79,9 @@ class LocalAlertUtils @Inject constructor(
} }
fun notifyPumpStatusRead() { //TODO: persist the actual time the pump is read and simplify the whole logic when to alarm fun notifyPumpStatusRead() { //TODO: persist the actual time the pump is read and simplify the whole logic when to alarm
val pump = activePlugin.activePumpPlugin val pump = activePlugin.activePump
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
if (pump != null && profile != null) { if (profile != null) {
val lastConnection = pump.lastDataTime() val lastConnection = pump.lastDataTime()
val earliestAlarmTime = lastConnection + pumpUnreachableThreshold() val earliestAlarmTime = lastConnection + pumpUnreachableThreshold()
if (sp.getLong("nextPumpDisconnectedAlarm", 0L) < earliestAlarmTime) { if (sp.getLong("nextPumpDisconnectedAlarm", 0L) < earliestAlarmTime) {

View file

@ -6,10 +6,10 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.db.TDD
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
@ -28,9 +28,9 @@ class TddCalculator @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
val mainApp: MainApp, val mainApp: MainApp,
val sp: SP, val sp: SP,
val configBuilderPlugin: ConfigBuilderPlugin, val activePlugin: ActivePluginProvider,
val profileFunction: ProfileFunction val profileFunction: ProfileFunction
) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, configBuilderPlugin) { ) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin) {
init { init {
service = TreatmentService() // plugin is not started service = TreatmentService() // plugin is not started

View file

@ -55,7 +55,6 @@ class ConstraintsCheckerTest : TestBase() {
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@ -64,7 +63,6 @@ class ConstraintsCheckerTest : TestBase() {
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var mainApp: MainApp
val rxBus = RxBusWrapper() val rxBus = RxBusWrapper()
private var buildHelper = BuildHelper() private var buildHelper = BuildHelper()
@ -121,15 +119,15 @@ class ConstraintsCheckerTest : TestBase() {
//SafetyPlugin //SafetyPlugin
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
constraintChecker = ConstraintChecker(mainApp) constraintChecker = ConstraintChecker(activePlugin)
danaRPump = DanaRPump(aapsLogger, sp, injector) danaRPump = DanaRPump(aapsLogger, sp, injector)
hardLimits = HardLimits(aapsLogger, sp, resourceHelper, context) hardLimits = HardLimits(aapsLogger, sp, resourceHelper, context)
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, configBuilderPlugin, sp) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp)
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue)
danaRPlugin = DanaRPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, treatmentsPlugin, sp, commandQueue, danaRPump) danaRPlugin = DanaRPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, treatmentsPlugin, sp, commandQueue, danaRPump)
danaRSPlugin = DanaRSPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump, detailedBolusInfoStorage) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, treatmentsPlugin, sp, commandQueue, danaRPump, detailedBolusInfoStorage)
insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, treatmentsPlugin, sp, commandQueue) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, treatmentsPlugin, sp, commandQueue, profileFunction)
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits)
openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits)
openAPSMAPlugin = OpenAPSMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits) openAPSMAPlugin = OpenAPSMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits)
@ -142,7 +140,7 @@ class ConstraintsCheckerTest : TestBase() {
constraintsPluginsList.add(danaRSPlugin) constraintsPluginsList.add(danaRSPlugin)
constraintsPluginsList.add(insightPlugin) constraintsPluginsList.add(insightPlugin)
constraintsPluginsList.add(openAPSSMBPlugin) constraintsPluginsList.add(openAPSSMBPlugin)
`when`(mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)).thenReturn(constraintsPluginsList) `when`(activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)).thenReturn(constraintsPluginsList)
objectivesPlugin.onStart() objectivesPlugin.onStart()
} }
@ -150,7 +148,6 @@ class ConstraintsCheckerTest : TestBase() {
@Test @Test
fun isLoopInvocationAllowedTest() { fun isLoopInvocationAllowedTest() {
`when`(activePlugin.activePump).thenReturn(comboPlugin) `when`(activePlugin.activePump).thenReturn(comboPlugin)
`when`(activePlugin.activePumpPlugin).thenReturn(comboPlugin)
comboPlugin.setPluginEnabled(PluginType.PUMP, true) comboPlugin.setPluginEnabled(PluginType.PUMP, true)
comboPlugin.setValidBasalRateProfileSelectedOnPump(false) comboPlugin.setValidBasalRateProfileSelectedOnPump(false)
val c = constraintChecker.isLoopInvocationAllowed() val c = constraintChecker.isLoopInvocationAllowed()
@ -231,6 +228,7 @@ class ConstraintsCheckerTest : TestBase() {
// applyBasalConstraints tests // applyBasalConstraints tests
@Test @Test
fun basalRateShouldBeLimited() { fun basalRateShouldBeLimited() {
`when`(activePlugin.activePump).thenReturn(danaRPlugin)
// DanaR, RS // DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
@ -257,6 +255,7 @@ class ConstraintsCheckerTest : TestBase() {
@Test @Test
fun percentBasalRateShouldBeLimited() { fun percentBasalRateShouldBeLimited() {
`when`(activePlugin.activePump).thenReturn(danaRPlugin)
// DanaR, RS // DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
@ -277,13 +276,15 @@ class ConstraintsCheckerTest : TestBase() {
// Apply all limits // Apply all limits
val i = constraintChecker.getMaxBasalPercentAllowed(validProfile) val i = constraintChecker.getMaxBasalPercentAllowed(validProfile)
Assert.assertEquals(100, i.value()) Assert.assertEquals(100, i.value())
Assert.assertEquals(8, i.reasonList.size) // 6x Safety & RS & R Assert.assertEquals(9, i.reasonList.size) // 7x Safety & RS & R
Assert.assertEquals("Safety: Limiting max percent rate to 100% because of pump limit", i.getMostLimitedReasons(aapsLogger)) Assert.assertEquals("Safety: Limiting max percent rate to 100% because of pump limit", i.getMostLimitedReasons(aapsLogger))
} }
// applyBolusConstraints tests // applyBolusConstraints tests
@Test @Test
fun bolusAmountShouldBeLimited() { fun bolusAmountShouldBeLimited() {
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(virtualPumpPlugin.pumpDescription).thenReturn(PumpDescription())
// DanaR, RS // DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)

View file

@ -4,6 +4,7 @@ import dagger.Lazy
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.TestBase import info.TestBase
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -38,7 +39,7 @@ class ConfigBuilderPluginTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var aapsLogger: AAPSLogger
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var nsProfilePlugin: NSProfilePlugin @Mock lateinit var activePlugin: ActivePluginProvider
lateinit var configBuilderPlugin: ConfigBuilderPlugin lateinit var configBuilderPlugin: ConfigBuilderPlugin
@ -55,6 +56,6 @@ class ConfigBuilderPluginTest : TestBase() {
@Before @Before
fun prepareMock() { fun prepareMock() {
configBuilderPlugin = ConfigBuilderPlugin(insulinOrefRapidActingPlugin, localProfilePlugin, virtualPumpPlugin, treatmentsPlugin, sensitivityOref0Plugin, sensitivityOref1Plugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, commandQueue, nsProfilePlugin) configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, commandQueue)
} }
} }

View file

@ -27,7 +27,7 @@ class ActionLoopDisableTest : ActionsTestBase() {
`when`(virtualPumpPlugin.specialEnableCondition()).thenReturn(true) `when`(virtualPumpPlugin.specialEnableCondition()).thenReturn(true)
val pumpDescription = PumpDescription().apply { isTempBasalCapable = true } val pumpDescription = PumpDescription().apply { isTempBasalCapable = true }
`when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription)
`when`(configBuilderPlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(resourceHelper.gs(R.string.disableloop)).thenReturn("Disable loop") `when`(resourceHelper.gs(R.string.disableloop)).thenReturn("Disable loop")
`when`(resourceHelper.gs(R.string.alreadydisabled)).thenReturn("Disable loop") `when`(resourceHelper.gs(R.string.alreadydisabled)).thenReturn("Disable loop")

View file

@ -26,7 +26,7 @@ class ActionLoopEnableTest : ActionsTestBase() {
`when`(virtualPumpPlugin.specialEnableCondition()).thenReturn(true) `when`(virtualPumpPlugin.specialEnableCondition()).thenReturn(true)
val pumpDescription = PumpDescription().apply { isTempBasalCapable = true } val pumpDescription = PumpDescription().apply { isTempBasalCapable = true }
`when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription)
`when`(configBuilderPlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(resourceHelper.gs(R.string.enableloop)).thenReturn("Enable loop") `when`(resourceHelper.gs(R.string.enableloop)).thenReturn("Enable loop")
`when`(resourceHelper.gs(R.string.alreadyenabled)).thenReturn("Already enabled") `when`(resourceHelper.gs(R.string.alreadyenabled)).thenReturn("Already enabled")

View file

@ -21,7 +21,7 @@ class ActionLoopSuspendTest : ActionsTestBase() {
fun setup() { fun setup() {
`when`(virtualPumpPlugin.specialEnableCondition()).thenReturn(true) `when`(virtualPumpPlugin.specialEnableCondition()).thenReturn(true)
`when`(configBuilderPlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(resourceHelper.gs(R.string.suspendloop)).thenReturn("Suspend loop") `when`(resourceHelper.gs(R.string.suspendloop)).thenReturn("Suspend loop")
`when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.suspendloopforXmin), ArgumentMatchers.anyInt())).thenReturn("Suspend loop for %d min") `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.suspendloopforXmin), ArgumentMatchers.anyInt())).thenReturn("Suspend loop for %d min")

View file

@ -34,7 +34,7 @@ class TriggerPumpLastConnectionTest : TriggerTestBase() {
fun shouldRunTest() { fun shouldRunTest() {
// System.currentTimeMillis() is always 0 // System.currentTimeMillis() is always 0
// and so is every last connection time // and so is every last connection time
PowerMockito.`when`(activePlugin.activePumpPlugin).thenReturn(virtualPumpPlugin) PowerMockito.`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
Assert.assertEquals(0L, virtualPumpPlugin.lastDataTime()) Assert.assertEquals(0L, virtualPumpPlugin.lastDataTime())
PowerMockito.`when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min PowerMockito.`when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min
var t = TriggerPumpLastConnection(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL) var t = TriggerPumpLastConnection(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL)

View file

@ -167,7 +167,7 @@ class SmsCommunicatorPluginTest : TestBase() {
null null
}.`when`(commandQueue).extendedBolus(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Callback::class.java)) }.`when`(commandQueue).extendedBolus(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Callback::class.java))
`when`(activePlugin.activePumpPlugin).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin)
`when`(virtualPumpPlugin.shortStatus(ArgumentMatchers.anyBoolean())).thenReturn("Virtual Pump") `when`(virtualPumpPlugin.shortStatus(ArgumentMatchers.anyBoolean())).thenReturn("Virtual Pump")

View file

@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.insulin
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Iob import info.nightscout.androidaps.data.Iob
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.Companion.MIN_DIA import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.Companion.MIN_DIA
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.plugins.treatments.Treatment
@ -60,7 +60,7 @@ class InsulinOrefBasePluginTest {
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var rxBus: RxBusWrapper @Mock lateinit var rxBus: RxBusWrapper
@Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var aapsLogger: AAPSLogger
@Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin @Mock lateinit var activePlugin: ActivePluginProvider
private var injector: HasAndroidInjector = HasAndroidInjector { private var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -68,7 +68,7 @@ class InsulinOrefBasePluginTest {
it.defaultValueHelper = defaultValueHelper it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.configBuilderPlugin = configBuilderPlugin it.activePlugin = activePlugin
} }
} }
} }

View file

@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.plugins.treatments.Treatment
@ -26,7 +26,7 @@ class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest : DanaRSTestBase() {
@Mock lateinit var rxBus: RxBusWrapper @Mock lateinit var rxBus: RxBusWrapper
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var danaRSPlugin: DanaRSPlugin @Mock lateinit var danaRSPlugin: DanaRSPlugin
private var treatmentInjector: HasAndroidInjector = HasAndroidInjector { private var treatmentInjector: HasAndroidInjector = HasAndroidInjector {
@ -35,7 +35,7 @@ class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest : DanaRSTestBase() {
it.defaultValueHelper = defaultValueHelper it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.configBuilderPlugin = configBuilderPlugin it.activePlugin = activePlugin
} }
} }
} }

View file

@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
@ -28,7 +29,7 @@ class DanaRS_Packet_Notify_Delivery_CompleteTest : DanaRSTestBase() {
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var danaRSPlugin: DanaRSPlugin @Mock lateinit var danaRSPlugin: DanaRSPlugin
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin @Mock lateinit var activePlugin: ActivePluginProvider
private var treatmentInjector: HasAndroidInjector = HasAndroidInjector { private var treatmentInjector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -36,7 +37,7 @@ class DanaRS_Packet_Notify_Delivery_CompleteTest : DanaRSTestBase() {
it.defaultValueHelper = defaultValueHelper it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.configBuilderPlugin = configBuilderPlugin it.activePlugin = activePlugin
} }
} }
} }

View file

@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm
import android.content.Context import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper 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.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
@ -31,7 +31,7 @@ class DanaRS_Packet_Notify_Delivery_Rate_DisplayTest : DanaRSTestBase() {
@Mock lateinit var defaultValueHelper: DefaultValueHelper @Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var configBuilderPlugin: ConfigBuilderPlugin @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@ -47,7 +47,7 @@ class DanaRS_Packet_Notify_Delivery_Rate_DisplayTest : DanaRSTestBase() {
it.defaultValueHelper = defaultValueHelper it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.configBuilderPlugin = configBuilderPlugin it.activePlugin = activePlugin
} }
} }
} }

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.queue.commands.Command
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.build.BuildHelper import info.nightscout.androidaps.utils.build.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -32,7 +32,7 @@ import org.powermock.modules.junit4.PowerMockRunner
import java.util.* import java.util.*
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class, ToastUtils::class, Context::class, TreatmentsPlugin::class) @PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class, ToastUtils::class, Context::class, TreatmentsPlugin::class, FabricPrivacy::class)
class CommandQueueTest : TestBase() { class CommandQueueTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var aapsLogger: AAPSLogger
@ -45,6 +45,7 @@ class CommandQueueTest : TestBase() {
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var fabricPrivacy: FabricPrivacy
private val buildHelper = BuildHelper() private val buildHelper = BuildHelper()
@ -63,7 +64,7 @@ class CommandQueueTest : TestBase() {
@Before @Before
fun prepareMock() { fun prepareMock() {
commandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, buildHelper) commandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, buildHelper, fabricPrivacy)
val pumpDescription = PumpDescription() val pumpDescription = PumpDescription()
pumpDescription.basalMinimumRate = 0.1 pumpDescription.basalMinimumRate = 0.1
@ -86,7 +87,8 @@ class CommandQueueTest : TestBase() {
val percentageConstraint = Constraint(0) val percentageConstraint = Constraint(0)
`when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint) `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint)
} }
/*
/*
@Test @Test
fun doTests() { fun doTests() {
@ -131,8 +133,8 @@ class CommandQueueTest : TestBase() {
// add setProfile // add setProfile
// TODO: this crash the test // TODO: this crash the test
// commandQueue.setProfile(validProfile, null) // commandQueue.setProfile(validProfile, null)
// Assert.assertEquals(3, commandQueue.size()) // Assert.assertEquals(3, commandQueue.size())
// add loadHistory // add loadHistory
commandQueue.loadHistory(0.toByte(), null) commandQueue.loadHistory(0.toByte(), null)
@ -184,7 +186,7 @@ class CommandQueueTest : TestBase() {
Assert.assertFalse(queued) Assert.assertFalse(queued)
Assert.assertEquals(commandQueue.size(), 1) Assert.assertEquals(commandQueue.size(), 1)
} }
*/ */
@Test @Test
fun smbIsRejectedIfLastKnownBolusIsOutdated() { fun smbIsRejectedIfLastKnownBolusIsOutdated() {
// given // given