ConfigBuilder refactor

This commit is contained in:
Milos Kozak 2020-04-24 22:39:56 +02:00
parent bb9d462995
commit 752a49573c
50 changed files with 426 additions and 488 deletions

View file

@ -8,7 +8,6 @@ import com.j256.ormlite.table.DatabaseTable;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
@ -18,16 +17,18 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.utils.DateUtil;
@ -37,7 +38,10 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
public class CareportalEvent implements DataPointWithLabelInterface, Interval {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE);
@Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper;
@Inject AAPSLogger aapsLogger;
@DatabaseField(id = true)
public long date;
@ -77,7 +81,13 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
public static final String MBG = "Mbg"; // comming from entries
@Deprecated
public CareportalEvent() {
MainApp.instance().androidInjector().inject(this);
}
public CareportalEvent(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
}
public CareportalEvent(NSMbg mbg) {
@ -90,7 +100,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return System.currentTimeMillis() - date;
}
public double getHoursFromStart() {
private double getHoursFromStart() {
return (System.currentTimeMillis() - date) / (60 * 60 * 1000.0);
}
@ -125,11 +135,11 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
}
//Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
public static Map<TimeUnit, Long> computeDiff(long date1, long date2) {
private static Map<TimeUnit, Long> computeDiff(long date1, long date2) {
long diffInMillies = date2 - date1;
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
List<TimeUnit> units = new ArrayList<>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit, Long> result = new LinkedHashMap<TimeUnit, Long>();
Map<TimeUnit, Long> result = new LinkedHashMap<>();
long milliesRest = diffInMillies;
for (TimeUnit unit : units) {
long diff = unit.convert(milliesRest, TimeUnit.MILLISECONDS);
@ -141,12 +151,12 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
}
public static boolean isEvent5minBack(List<CareportalEvent> list, long time) {
public boolean isEvent5minBack(List<CareportalEvent> list, long time) {
for (int i = 0; i < list.size(); i++) {
CareportalEvent event = list.get(i);
if (event.date <= time && event.date > (time - T.mins(5).msecs())) {
if (L.isEnabled(L.DATABASE))
log.debug("Found event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
aapsLogger.debug("Found event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString());
return true;
}
}
@ -160,18 +170,18 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return date;
}
double yValue = 0;
private double yValue = 0;
@Override
public double getY() {
String units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits();
String units = profileFunction.getUnits();
if (eventType.equals(MBG)) {
double mbg = 0d;
try {
JSONObject object = new JSONObject(json);
mbg = object.getDouble("mgdl");
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return Profile.fromMgdlToUnits(mbg, units);
}
@ -184,7 +194,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
units = object.getString("units");
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
if (glucose != 0d) {
double mmol = 0d;
@ -215,7 +225,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
if (object.has("notes"))
return StringUtils.abbreviate(object.getString("notes"), 40);
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return Translator.translate(eventType);
}
@ -226,7 +236,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
if (object.has("notes"))
return object.getString("notes");
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return "";
}
@ -257,14 +267,14 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@Override
public float getSize() {
boolean isTablet = MainApp.resources().getBoolean(R.bool.isTablet);
boolean isTablet = resourceHelper.gb(R.bool.isTablet);
return isTablet ? 12 : 10;
}
@Override
public int getColor() {
if (eventType.equals(ANNOUNCEMENT))
return MainApp.gc(R.color.notificationAnnouncement);
return resourceHelper.gc(R.color.notificationAnnouncement);
if (eventType.equals(MBG))
return Color.RED;
if (eventType.equals(BGCHECK))
@ -277,7 +287,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
}
// Interval interface
Long cuttedEnd = null;
private Long cuttedEnd = null;
@Override
public long durationInMsec() {
@ -286,7 +296,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
if (object.has("duration"))
return object.getInt("duration") * 60 * 1000L;
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return 0;
}

View file

@ -7,6 +7,10 @@ import org.slf4j.Logger;
import java.util.Objects;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
@ -15,8 +19,8 @@ import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.PluginStore;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.utils.DateUtil;
@ -31,6 +35,9 @@ import info.nightscout.androidaps.utils.SP;
public class TemporaryBasal implements Interval, DbObjectBase {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE);
@Inject public ProfileFunction profileFunction;
private HasAndroidInjector injector;
@DatabaseField(id = true)
public long date;
@ -59,7 +66,15 @@ public class TemporaryBasal implements Interval, DbObjectBase {
public double netExtendedRate = 0d;
@Deprecated
public TemporaryBasal() {
injector = MainApp.instance();
injector.androidInjector().inject(this);
}
public TemporaryBasal(HasAndroidInjector injector) {
this.injector = injector;
injector.androidInjector().inject(this);
}
public TemporaryBasal date(long date) {
@ -95,7 +110,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
double basal = profileFunction.getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source;
@ -109,7 +124,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public TemporaryBasal clone() {
TemporaryBasal t = new TemporaryBasal();
TemporaryBasal t = new TemporaryBasal(injector);
t.date = date;
t.isValid = isValid;
t.source = source;
@ -404,7 +419,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
public String toStringFull() {
if (isFakeExtended) {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";
Double currentBasalRate = profile.getBasal();
@ -428,7 +443,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
double rate;
if (isFakeExtended) {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";
double currentBasalRate = profile.getBasal();
@ -438,7 +453,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile != null) {
double basal = profile.getBasal();
if (basal != 0) {
@ -453,7 +468,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
private String getCalcuatedPercentageIfNeeded() {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";
@ -479,7 +494,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
}
public String toStringVeryShort() {
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
Profile profile = profileFunction.getProfile();
if (profile == null)
return "null";

View file

@ -9,10 +9,12 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
@ -152,6 +154,8 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectTreatment(treatment: Treatment)
fun injectBgReading(bgReading: BgReading)
fun injectProfileSwitch(profileSwitch: ProfileSwitch)
fun injectTemporaryBasal(temporaryBasal: TemporaryBasal)
fun injectCareportalEvent(careportalEvent: CareportalEvent)
fun injectNotification(notificationWithAction: NotificationWithAction)

View file

@ -14,7 +14,9 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.PluginBase
@ -37,6 +39,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs
import info.nightscout.androidaps.plugins.general.maintenance.formats.ClassicPrefsFormat
import info.nightscout.androidaps.plugins.general.maintenance.formats.EncryptedPrefsFormat
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
@ -98,11 +101,14 @@ open class AppModule {
fun providesPlugins(@PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>,
@PluginsModule.PumpDriver pumpDrivers: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.NotNSClient notNsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>): List<@JvmSuppressWildcards PluginBase> {
@PluginsModule.NSClient nsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>)
: List<@JvmSuppressWildcards PluginBase> {
val plugins = allConfigs.toMutableMap()
if (Config.PUMPDRIVERS) plugins += pumpDrivers.get()
if (Config.APS) plugins += aps.get()
if (!Config.NSCLIENT) plugins += notNsClient.get()
if (Config.NSCLIENT) plugins += nsClient.get()
return plugins.toList().sortedBy { it.first }.map { it.second }
}
@ -233,6 +239,8 @@ open class AppModule {
@ContributesAndroidInjector fun bgReadingInjector(): BgReading
@ContributesAndroidInjector fun treatmentInjector(): Treatment
@ContributesAndroidInjector fun profileSwitchInjector(): ProfileSwitch
@ContributesAndroidInjector fun temporaryBasalInjector(): TemporaryBasal
@ContributesAndroidInjector fun careportalEventInjector(): CareportalEvent
@ContributesAndroidInjector fun notificationWithActionInjector(): NotificationWithAction

View file

@ -165,7 +165,7 @@ abstract class PluginsModule {
abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase
@Binds
@NotNSClient
@NSClient
@IntoMap
@IntKey(180)
abstract fun bindCareportalPlugin(plugin: CareportalPlugin): PluginBase
@ -213,7 +213,7 @@ abstract class PluginsModule {
abstract fun bindTreatmentsPlugin(plugin: TreatmentsPlugin): PluginBase
@Binds
@NotNSClient
@AllConfigs
@IntoSet
abstract fun bindSafetyPlugin(plugin: SafetyPlugin): PluginBase
@ -359,6 +359,9 @@ abstract class PluginsModule {
@Qualifier
annotation class NotNSClient
@Qualifier
annotation class NSClient
@Qualifier
annotation class APS

View file

@ -183,7 +183,7 @@ class CareDialog : DialogFragmentWithDate() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.date = eventTime
careportalEvent.source = Source.USER
careportalEvent.eventType = when (options) {

View file

@ -7,6 +7,7 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.common.base.Joiner
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
@ -40,6 +41,7 @@ class FillDialog : DialogFragmentWithDate() {
@Inject lateinit var ctx: Context
@Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var injector: HasAndroidInjector
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
@ -161,7 +163,7 @@ class FillDialog : DialogFragmentWithDate() {
}
private fun generateCareportalEvent(eventType: String, time: Long, notes: String) {
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.source = Source.USER
careportalEvent.date = time
careportalEvent.json = generateJson(eventType, time, notes).toString()

View file

@ -744,7 +744,7 @@ public class LoopPlugin extends PluginBase {
} catch (JSONException e) {
getAapsLogger().error("Unhandled exception", e);
}
CareportalEvent event = new CareportalEvent();
CareportalEvent event = new CareportalEvent(getInjector());
event.date = DateUtil.now();
event.source = Source.USER;
event.eventType = CareportalEvent.OPENAPSOFFLINE;

View file

@ -1,344 +0,0 @@
package info.nightscout.androidaps.plugins.configBuilder;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppInitialized;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui;
import info.nightscout.androidaps.utils.alertDialogs.OKDialog;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
* Created by mike on 05.08.2016.
*/
@Singleton
public class ConfigBuilderPlugin extends PluginBase {
private static ConfigBuilderPlugin configBuilderPlugin;
private final ActivePluginProvider activePlugin;
private final SP sp;
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
/**
* @deprecated Use dagger to get an instance
*/
@Deprecated
public ProfileFunction getProfileFunction() {
if (profileFunction == null)
throw new IllegalStateException("Accessing profileFunction before first instantiation");
return profileFunction;
}
@Deprecated
static public ConfigBuilderPlugin getPlugin() {
if (configBuilderPlugin == null)
throw new IllegalStateException("Accessing ConfigBuilder before first instantiation");
return configBuilderPlugin;
}
/*
* Written by Adrian:
* The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app.
* In order to make the transition to DI, while legacy code is still calling `getPlugin()`,
* I'd instantiate this plugin very very early on (first injected dependency in MainApp) and use
* Lazy dependencies in this constructor.
* */
@Inject
public ConfigBuilderPlugin(
ActivePluginProvider activePlugin,
HasAndroidInjector injector,
SP sp,
RxBusWrapper rxBus,
AAPSLogger aapsLogger,
ResourceHelper resourceHelper,
ProfileFunction profileFunction
) {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(ConfigBuilderFragment.class.getName())
.showInList(true)
.alwaysEnabled(true)
.alwaysVisible(false)
.pluginName(R.string.configbuilder)
.shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector
);
this.activePlugin = activePlugin;
this.sp = sp;
this.rxBus = rxBus;
this.aapsLogger = aapsLogger;
this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction;
configBuilderPlugin = this; // TODO: only while transitioning to Dagger
}
public void initialize() {
upgradeSettings();
((PluginStore) activePlugin).loadDefaults();
loadSettings();
setAlwaysEnabledPluginsEnabled();
rxBus.send(new EventAppInitialized());
}
private void setAlwaysEnabledPluginsEnabled() {
for (PluginBase plugin : activePlugin.getPluginsList()) {
if (plugin.getPluginDescription().alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true);
}
storeSettings("setAlwaysEnabledPluginsEnabled");
}
public void storeSettings(String from) {
activePlugin.getPluginsList();
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing settings from: " + from);
activePlugin.verifySelectionInCategories();
for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().alwaysVisible)
continue;
if (p.getPluginDescription().alwaysEnabled && p.getPluginDescription().neverVisible)
continue;
savePref(p, type, true);
if (type == PluginType.PUMP) {
if (p instanceof ProfileInterface) { // Store state of optional Profile interface
savePref(p, PluginType.PROFILE, false);
}
}
}
}
private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
sp.putBoolean(settingEnabled, p.isEnabled(type));
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (storeVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
sp.putBoolean(settingVisible, p.isFragmentVisible());
getAapsLogger().debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible());
}
}
private void loadSettings() {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loading stored settings");
for (PluginBase p : activePlugin.getPluginsList()) {
PluginType type = p.getType();
loadPref(p, type, true);
if (p.getType() == PluginType.PUMP) {
if (p instanceof ProfileInterface) {
loadPref(p, PluginType.PROFILE, false);
}
}
}
activePlugin.verifySelectionInCategories();
}
private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
if (sp.contains(settingEnabled))
p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false));
else if (p.getType() == type && (p.getPluginDescription().enableByDefault || p.getPluginDescription().alwaysEnabled)) {
p.setPluginEnabled(type, true);
}
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (loadVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
if (sp.contains(settingVisible))
p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
else if (p.getType() == type && p.getPluginDescription().visibleByDefault) {
p.setFragmentVisible(type, true);
}
getAapsLogger().debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible());
}
}
// Detect settings prior 1.60
private void upgradeSettings() {
if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return;
getAapsLogger().debug(LTag.CONFIGBUILDER, "Upgrading stored settings");
for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, "Processing " + p.getName());
for (int type = 1; type < 11; type++) {
PluginType newType;
switch (type) {
case 1:
newType = PluginType.GENERAL;
break;
case 2:
newType = PluginType.TREATMENT;
break;
case 3:
newType = PluginType.SENSITIVITY;
break;
case 4:
newType = PluginType.PROFILE;
break;
case 5:
newType = PluginType.APS;
break;
case 6:
newType = PluginType.PUMP;
break;
case 7:
newType = PluginType.CONSTRAINTS;
break;
case 8:
newType = PluginType.LOOP;
break;
case 9:
newType = PluginType.BGSOURCE;
break;
case 10:
newType = PluginType.INSULIN;
break;
default:
newType = PluginType.GENERAL;
break;
}
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
if (sp.contains(settingEnabled))
p.setPluginEnabled(newType, sp.getBoolean(settingEnabled, false));
if (sp.contains(settingVisible))
p.setFragmentVisible(newType, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
sp.remove(settingEnabled);
sp.remove(settingVisible);
if (newType == p.getType()) {
savePref(p, newType, true);
}
}
}
}
public void logPluginStatus() {
for (PluginBase p : activePlugin.getPluginsList()) {
getAapsLogger().debug(LTag.CONFIGBUILDER, p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
(p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
(p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
(p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
(p.isEnabled(PluginType.APS) ? " APS" : "") +
(p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
(p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
(p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
(p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
(p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
);
}
}
// Ask when switching to physical pump plugin
public void switchAllowed(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
if (changedPlugin.getType() == PluginType.PUMP && !changedPlugin.getName().equals(resourceHelper.gs(R.string.virtualpump)))
confirmPumpPluginActivation(changedPlugin, newState, activity, type);
else
performPluginSwitch(changedPlugin, newState, type);
}
private void confirmPumpPluginActivation(@NonNull PluginBase changedPlugin, boolean newState, @Nullable FragmentActivity activity, @NonNull PluginType type) {
boolean allowHardwarePump = sp.getBoolean("allow_hardware_pump", false);
if (allowHardwarePump || activity == null) {
performPluginSwitch(changedPlugin, newState, type);
} else {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), () -> {
performPluginSwitch(changedPlugin, newState, type);
sp.putBoolean("allow_hardware_pump", true);
aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!");
}, () -> {
rxBus.send(new EventConfigBuilderUpdateGui());
aapsLogger.debug(LTag.PUMP, "User does not allow switching to HW pump!");
});
}
}
public void performPluginSwitch(PluginBase changedPlugin, boolean enabled, @NonNull PluginType type) {
changedPlugin.setPluginEnabled(type, enabled);
changedPlugin.setFragmentVisible(type, enabled);
processOnEnabledCategoryChanged(changedPlugin, type);
storeSettings("CheckedCheckboxEnabled");
rxBus.send(new EventRebuildTabs());
rxBus.send(new EventConfigBuilderChange());
rxBus.send(new EventConfigBuilderUpdateGui());
logPluginStatus();
}
public void processOnEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
ArrayList<PluginBase> pluginsInCategory = null;
switch (type) {
// Multiple selection allowed
case GENERAL:
case CONSTRAINTS:
case LOOP:
break;
// Single selection allowed
case INSULIN:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface.class);
break;
case SENSITIVITY:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface.class);
break;
case APS:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface.class);
break;
case PROFILE:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case BGSOURCE:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case TREATMENT:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface.class);
break;
case PUMP:
pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface.class);
break;
}
if (pluginsInCategory != null) {
boolean newSelection = changedPlugin.isEnabled(type);
if (newSelection) { // new plugin selected -> disable others
for (PluginBase p : pluginsInCategory) {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
p.setPluginEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
pluginsInCategory.get(0).setPluginEnabled(type, true);
}
}
}
}

View file

@ -0,0 +1,191 @@
package info.nightscout.androidaps.plugins.configBuilder
import androidx.fragment.app.FragmentActivity
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventAppInitialized
import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui
import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ConfigBuilderPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
private val sp: SP,
private val rxBus: RxBusWrapper,
private val activePlugin: ActivePluginProvider
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(ConfigBuilderFragment::class.java.name)
.showInList(true)
.alwaysEnabled(true)
.alwaysVisible(false)
.pluginName(R.string.configbuilder)
.shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector
) {
fun initialize() {
(activePlugin as PluginStore).loadDefaults()
loadSettings()
setAlwaysEnabledPluginsEnabled()
rxBus.send(EventAppInitialized())
}
private fun setAlwaysEnabledPluginsEnabled() {
for (plugin in activePlugin.pluginsList) {
if (plugin.pluginDescription.alwaysEnabled) plugin.setPluginEnabled(plugin.getType(), true)
}
storeSettings("setAlwaysEnabledPluginsEnabled")
}
fun storeSettings(from: String) {
activePlugin.pluginsList
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from")
activePlugin.verifySelectionInCategories()
for (p in activePlugin.pluginsList) {
val type = p.getType()
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwaysVisible) continue
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.neverVisible) continue
savePref(p, type, true)
if (type == PluginType.PUMP) {
if (p is ProfileInterface) { // Store state of optional Profile interface
savePref(p, PluginType.PROFILE, false)
}
}
}
}
private fun savePref(p: PluginBase, type: PluginType, storeVisible: Boolean) {
val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled"
sp.putBoolean(settingEnabled, p.isEnabled(type))
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type))
if (storeVisible) {
val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible"
sp.putBoolean(settingVisible, p.isFragmentVisible())
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible())
}
}
private fun loadSettings() {
aapsLogger.debug(LTag.CONFIGBUILDER, "Loading stored settings")
for (p in activePlugin.pluginsList) {
val type = p.getType()
loadPref(p, type, true)
if (p.getType() == PluginType.PUMP) {
if (p is ProfileInterface) {
loadPref(p, PluginType.PROFILE, false)
}
}
}
activePlugin.verifySelectionInCategories()
}
private fun loadPref(p: PluginBase, type: PluginType, loadVisible: Boolean) {
val settingEnabled = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Enabled"
if (sp.contains(settingEnabled)) p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false)) else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
p.setPluginEnabled(type, true)
}
aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type))
if (loadVisible) {
val settingVisible = "ConfigBuilder_" + type.name + "_" + p.javaClass.simpleName + "_Visible"
if (sp.contains(settingVisible)) p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false)) else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
p.setFragmentVisible(type, true)
}
aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible())
}
}
fun logPluginStatus() {
for (p in activePlugin.pluginsList) {
aapsLogger.debug(LTag.CONFIGBUILDER, p.name + ":" +
(if (p.isEnabled(PluginType.GENERAL)) " GENERAL" else "") +
(if (p.isEnabled(PluginType.TREATMENT)) " TREATMENT" else "") +
(if (p.isEnabled(PluginType.SENSITIVITY)) " SENSITIVITY" else "") +
(if (p.isEnabled(PluginType.PROFILE)) " PROFILE" else "") +
(if (p.isEnabled(PluginType.APS)) " APS" else "") +
(if (p.isEnabled(PluginType.PUMP)) " PUMP" else "") +
(if (p.isEnabled(PluginType.CONSTRAINTS)) " CONSTRAINTS" else "") +
(if (p.isEnabled(PluginType.LOOP)) " LOOP" else "") +
(if (p.isEnabled(PluginType.BGSOURCE)) " BGSOURCE" else "") +
if (p.isEnabled(PluginType.INSULIN)) " INSULIN" else ""
)
}
}
// Ask when switching to physical pump plugin
fun switchAllowed(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
if (changedPlugin.getType() == PluginType.PUMP && changedPlugin.name != resourceHelper.gs(R.string.virtualpump)) confirmPumpPluginActivation(changedPlugin, newState, activity, type) else performPluginSwitch(changedPlugin, newState, type)
}
private fun confirmPumpPluginActivation(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
val allowHardwarePump = sp.getBoolean("allow_hardware_pump", false)
if (allowHardwarePump || activity == null) {
performPluginSwitch(changedPlugin, newState, type)
} else {
showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), Runnable {
performPluginSwitch(changedPlugin, newState, type)
sp.putBoolean("allow_hardware_pump", true)
aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!")
}, Runnable {
rxBus.send(EventConfigBuilderUpdateGui())
aapsLogger.debug(LTag.PUMP, "User does not allow switching to HW pump!")
})
}
}
fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) {
changedPlugin.setPluginEnabled(type, enabled)
changedPlugin.setFragmentVisible(type, enabled)
processOnEnabledCategoryChanged(changedPlugin, type)
storeSettings("CheckedCheckboxEnabled")
rxBus.send(EventRebuildTabs())
rxBus.send(EventConfigBuilderChange())
rxBus.send(EventConfigBuilderUpdateGui())
logPluginStatus()
}
fun processOnEnabledCategoryChanged(changedPlugin: PluginBase, type: PluginType?) {
var pluginsInCategory: ArrayList<PluginBase>? = null
when (type) {
PluginType.INSULIN -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(InsulinInterface::class.java)
PluginType.SENSITIVITY -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(SensitivityInterface::class.java)
PluginType.APS -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APSInterface::class.java)
PluginType.PROFILE -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileInterface::class.java)
PluginType.BGSOURCE -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSourceInterface::class.java)
PluginType.TREATMENT -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface::class.java)
PluginType.PUMP -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(PumpInterface::class.java)
else -> {
}
}
if (pluginsInCategory != null) {
val newSelection = changedPlugin.isEnabled(type!!)
if (newSelection) { // new plugin selected -> disable others
for (p in pluginsInCategory) {
if (p.name == changedPlugin.name) {
// this is new selected
} else {
p.setPluginEnabled(type, false)
p.setFragmentVisible(type, false)
}
}
} else { // enable first plugin in list
pluginsInCategory[0].setPluginEnabled(type, true)
}
}
}
}

View file

@ -73,11 +73,10 @@ public class NSUpload {
}
}
public static void uploadTempBasalStartPercent(TemporaryBasal temporaryBasal) {
public static void uploadTempBasalStartPercent(TemporaryBasal temporaryBasal, Profile profile) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(temporaryBasal.date);
double absoluteRate = 0;
if (profile != null) {
absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d;
@ -264,16 +263,16 @@ public class NSUpload {
}
}
public static void uploadTempTarget(TempTarget tempTarget) {
public static void uploadTempTarget(TempTarget tempTarget, ProfileFunction profileFunction) {
try {
JSONObject data = new JSONObject();
data.put("eventType", CareportalEvent.TEMPORARYTARGET);
data.put("duration", tempTarget.durationInMinutes);
if (tempTarget.low > 0) {
data.put("reason", tempTarget.reason);
data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()));
data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()));
data.put("units", ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits());
data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, profileFunction.getUnits()));
data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, profileFunction.getUnits()));
data.put("units", profileFunction.getUnits());
}
data.put("created_at", DateUtil.toISOString(tempTarget.date));
data.put("enteredBy", MainApp.gs(R.string.app_name));

View file

@ -470,7 +470,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
// OpenAPSSMB only
// Add expected zero temp basal for next 240 mins
IobTotal basalIobWithZeroTemp = basalIob.copy();
TemporaryBasal t = new TemporaryBasal()
TemporaryBasal t = new TemporaryBasal(injector)
.date(now + 60 * 1000L)
.duration(240)
.absolute(0);
@ -517,7 +517,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
// OpenAPSSMB only
// Add expected zero temp basal for next 240 mins
IobTotal basalIobWithZeroTemp = basalIob.copy();
TemporaryBasal t = new TemporaryBasal()
TemporaryBasal t = new TemporaryBasal(injector)
.date(now + 60 * 1000L)
.duration(240)
.absolute(0);

View file

@ -776,7 +776,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
PumpState state = commandResult.state;
if (state.tbrActive && state.tbrPercent == adjustedPercent
&& (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) {
TemporaryBasal tempStart = new TemporaryBasal()
TemporaryBasal tempStart = new TemporaryBasal(getInjector())
.date(state.timestamp)
.duration(state.tbrRemainingDuration)
.percent(state.tbrPercent)
@ -822,7 +822,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()).success(false).enacted(false);
}
if (!cancelResult.state.tbrActive) {
TemporaryBasal tempBasal = new TemporaryBasal()
TemporaryBasal tempBasal = new TemporaryBasal(getInjector())
.date(cancelResult.state.timestamp)
.duration(0)
.source(Source.USER);
@ -973,7 +973,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
if (aapsTbr == null || aapsTbr.percentRate != 0) {
getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended");
TemporaryBasal newTempBasal = new TemporaryBasal()
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
.date(now)
.percent(0)
.duration(15)
@ -1099,7 +1099,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) {
getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR");
TemporaryBasal newTempBasal = new TemporaryBasal()
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
.date(now)
.percent(state.tbrPercent)
.duration(state.tbrRemainingDuration)
@ -1107,7 +1107,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active");
TemporaryBasal tempStop = new TemporaryBasal()
TemporaryBasal tempStop = new TemporaryBasal(getInjector())
.date(now)
.duration(0)
.source(Source.USER);
@ -1116,13 +1116,13 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
&& (aapsTbr.percentRate != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) {
getAapsLogger().debug(LTag.PUMP, "AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR");
TemporaryBasal tempStop = new TemporaryBasal()
TemporaryBasal tempStop = new TemporaryBasal(getInjector())
.date(now - 1000)
.duration(0)
.source(Source.USER);
treatmentsPlugin.addToHistoryTempBasal(tempStop);
TemporaryBasal newTempBasal = new TemporaryBasal()
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
.date(now)
.percent(state.tbrPercent)
.duration(state.tbrRemainingDuration)

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
@ -25,7 +26,8 @@ class MessageHashTableR @Inject constructor(
danaRKoreanPlugin: DanaRKoreanPlugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider
activePlugin: ActivePluginProvider,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
@ -36,7 +38,7 @@ class MessageHashTableR @Inject constructor(
put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED
put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
@ -11,7 +12,8 @@ import kotlin.math.ceil
class MsgStatusTempBasal(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump,
private val activePlugin: ActivePluginProvider
private val activePlugin: ActivePluginProvider,
private val injector: HasAndroidInjector
) : MessageBase() {
init {
@ -52,10 +54,10 @@ class MsgStatusTempBasal(
val tempBasal = activePlugin.activeTreatments.getRealTempBasalFromHistory(System.currentTimeMillis())
if (danaRPump.isTempBasalInProgress) {
if (tempBasal.percentRate != danaRPump.tempBasalPercent) { // Close current temp basal
val tempStop = TemporaryBasal().date(danaRPump.tempBasalStart - 1000).source(Source.USER)
val tempStop = TemporaryBasal(injector).date(danaRPump.tempBasalStart - 1000).source(Source.USER)
activePlugin.activeTreatments.addToHistoryTempBasal(tempStop)
// Create new
val newTempBasal = TemporaryBasal()
val newTempBasal = TemporaryBasal(injector)
.date(danaRPump.tempBasalStart)
.percent(danaRPump.tempBasalPercent)
.duration(danaRPump.tempBasalTotalSec / 60)
@ -63,12 +65,12 @@ class MsgStatusTempBasal(
activePlugin.activeTreatments.addToHistoryTempBasal(newTempBasal)
}
} else { // Close current temp basal
val tempStop = TemporaryBasal().date(now).source(Source.USER)
val tempStop = TemporaryBasal(injector).date(now).source(Source.USER)
activePlugin.activeTreatments.addToHistoryTempBasal(tempStop)
}
} else {
if (danaRPump.isTempBasalInProgress) { // Create new
val newTempBasal = TemporaryBasal()
val newTempBasal = TemporaryBasal(injector)
.date(danaRPump.tempBasalStart)
.percent(danaRPump.tempBasalPercent)
.duration(danaRPump.tempBasalTotalSec / 60)

View file

@ -55,7 +55,7 @@ import io.reactivex.schedulers.Schedulers;
*/
public abstract class AbstractDanaRExecutionService extends DaggerService {
@Inject HasAndroidInjector injector;
@Inject protected HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject RxBusWrapper rxBus;
@Inject SP sp;

View file

@ -11,6 +11,7 @@ import java.util.Date;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
@ -91,6 +92,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
@Inject ActivePluginProvider activePlugin;
@Inject ProfileFunction profileFunction;
@Inject SP sp;
@Inject HasAndroidInjector injector;
public DanaRExecutionService() {
}
@ -147,7 +149,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus)));
MsgStatus statusMsg = new MsgStatus(aapsLogger, danaRPump);
MsgStatusBasic statusBasicMsg = new MsgStatusBasic(aapsLogger, danaRPump);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector);
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin);
MsgCheckValue checkValue = new MsgCheckValue(aapsLogger, danaRPump, danaRPlugin);
@ -239,7 +241,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(aapsLogger, percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@ -248,7 +250,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop(aapsLogger));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRKorean.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
@ -26,7 +27,8 @@ class MessageHashTableRKorean @Inject constructor(
danaRKoreanPlugin: DanaRKoreanPlugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider
activePlugin: ActivePluginProvider,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
@ -36,7 +38,7 @@ class MessageHashTableRKorean @Inject constructor(
put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA
put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic_k(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus_k(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS

View file

@ -138,7 +138,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus)));
//MsgStatus_k statusMsg = new MsgStatus_k();
MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(aapsLogger, danaRPump);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin);
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector);
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin);
MsgCheckValue_k checkValue = new MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin);
@ -228,7 +228,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(aapsLogger, percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@ -237,7 +237,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop(aapsLogger));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin));
mSerialIOThread.sendMessage(new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector));
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -21,7 +22,8 @@ class DanaRSMessageHashTable @Inject constructor(
danaRSPlugin: DanaRSPlugin,
activePlugin: ActivePluginProvider,
constraintChecker: ConstraintChecker,
detailedBolusInfoStorage: DetailedBolusInfoStorage
detailedBolusInfoStorage: DetailedBolusInfoStorage,
injector: HasAndroidInjector
) {
var messages: HashMap<Int, DanaRS_Packet> = HashMap()
@ -99,7 +101,7 @@ class DanaRSMessageHashTable @Inject constructor(
put(DanaRS_Packet_History_Temporary(aapsLogger, rxBus))
// APS
put(DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 0))
put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, 0))
put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector,0))
put(DanaRS_Packet_APS_Set_Event_History(aapsLogger, 0, 0, 0, 0))
}
}

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.db.ExtendedBolus
@ -25,6 +26,7 @@ open class DanaRS_Packet_APS_History_Events(
private val activePlugin: ActivePluginProvider,
private val danaRSPlugin: DanaRSPlugin,
private val detailedBolusInfoStorage: DetailedBolusInfoStorage,
private val injector: HasAndroidInjector,
private var from: Long
) : DanaRS_Packet() {
@ -75,7 +77,7 @@ open class DanaRS_Packet_APS_History_Events(
val datetime = dateTimeSecFromBuff(data, 1) // 6 bytes
val param1 = (intFromBuff(data, 7, 1) shl 8 and 0xFF00) + (intFromBuff(data, 8, 1) and 0xFF)
val param2 = (intFromBuff(data, 9, 1) shl 8 and 0xFF00) + (intFromBuff(data, 10, 1) and 0xFF)
val temporaryBasal = TemporaryBasal().date(datetime).source(Source.PUMP).pumpId(datetime)
val temporaryBasal = TemporaryBasal(injector).date(datetime).source(Source.PUMP).pumpId(datetime)
val extendedBolus = ExtendedBolus().date(datetime).source(Source.PUMP).pumpId(datetime)
val status: String
when (recordCode.toInt()) {

View file

@ -271,10 +271,10 @@ public class DanaRSService extends DaggerService {
DanaRS_Packet_APS_History_Events msg;
if (lastHistoryFetched == 0) {
msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, 0);
msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, 0);
aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history");
} else {
msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, lastHistoryFetched);
msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, lastHistoryFetched);
aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched));
}
bleComm.sendMessage(msg);

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
@ -32,7 +33,8 @@ class MessageHashTableRv2 @Inject constructor(
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider,
detailedBolusInfoStorage: DetailedBolusInfoStorage,
treatmentsPlugin: TreatmentsPlugin
treatmentsPlugin: TreatmentsPlugin,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
@ -91,7 +93,7 @@ class MessageHashTableRv2 @Inject constructor(
put(MsgCheckValue_v2(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue)) // 0xF0F1 CMD_PUMP_CHECK_VALUE
put(MsgStatusAPS_v2(aapsLogger, danaRPump)) // 0xE001 CMD_PUMPSTATUS_APS
put(MsgSetAPSTempBasalStart_v2(aapsLogger, 0, false, false)) // 0xE002 CMD_PUMPSET_APSTEMP
put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin)) // 0xE003 CMD_GET_HISTORY
put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector)) // 0xE003 CMD_GET_HISTORY
put(MsgSetHistoryEntry_v2(aapsLogger, 0, 0, 0, 0)) // 0xE004 CMD_SET_HISTORY_ENTRY
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.db.ExtendedBolus
@ -25,6 +26,7 @@ class MsgHistoryEvents_v2 constructor(
val danaRv2Plugin: DanaRv2Plugin,
val rxBus: RxBusWrapper,
val treatmentsPlugin: TreatmentsPlugin,
private val injector: HasAndroidInjector,
var from: Long = 0
) : MessageBase() {
@ -61,7 +63,7 @@ class MsgHistoryEvents_v2 constructor(
val datetime = dateTimeSecFromBuff(bytes, 1) // 6 bytes
val param1 = intFromBuff(bytes, 7, 2)
val param2 = intFromBuff(bytes, 9, 2)
val temporaryBasal = TemporaryBasal()
val temporaryBasal = TemporaryBasal(injector)
.date(datetime)
.source(Source.PUMP)
.pumpId(datetime)

View file

@ -455,7 +455,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
if (!isConnected())
return new PumpEnactResult(injector).success(false);
SystemClock.sleep(300);
MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, lastHistoryFetched);
MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, lastHistoryFetched);
aapsLogger.debug(LTag.PUMP, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched));
mSerialIOThread.sendMessage(msg);

View file

@ -1229,7 +1229,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
InsightPumpID stoppedEvent = MainApp.getDbHelper().getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp);
if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue;
long tbrStart = stoppedEvent.timestamp + 10000;
TemporaryBasal temporaryBasal = new TemporaryBasal();
TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector());
temporaryBasal.durationInMinutes = (int) ((pumpID.timestamp - tbrStart) / 60000);
temporaryBasal.date = tbrStart;
temporaryBasal.source = Source.PUMP;
@ -1355,7 +1355,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
pumpID.timestamp = timestamp;
pumpID.eventType = "StartOfTBR";
MainApp.getDbHelper().createOrUpdate(pumpID);
TemporaryBasal temporaryBasal = new TemporaryBasal();
TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector());
temporaryBasal.durationInMinutes = event.getDuration();
temporaryBasal.source = Source.PUMP;
temporaryBasal.pumpId = pumpID.id;
@ -1374,7 +1374,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
pumpID.eventType = "EndOfTBR";
pumpID.timestamp = timestamp;
MainApp.getDbHelper().createOrUpdate(pumpID);
TemporaryBasal temporaryBasal = new TemporaryBasal();
TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector());
temporaryBasal.durationInMinutes = 0;
temporaryBasal.source = Source.PUMP;
temporaryBasal.pumpId = pumpID.id;
@ -1572,7 +1572,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", CareportalEvent.NOTE);
data.put("notes", note);
CareportalEvent careportalEvent = new CareportalEvent();
CareportalEvent careportalEvent = new CareportalEvent(getInjector());
careportalEvent.date = date;
careportalEvent.source = Source.USER;
careportalEvent.eventType = CareportalEvent.NOTE;
@ -1606,7 +1606,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", event);
CareportalEvent careportalEvent = new CareportalEvent();
CareportalEvent careportalEvent = new CareportalEvent(getInjector());
careportalEvent.date = date;
careportalEvent.source = Source.USER;
careportalEvent.eventType = event;

View file

@ -1030,7 +1030,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
pumpStatusLocal.tempBasalAmount = absoluteRate;
pumpStatusLocal.tempBasalLength = durationInMinutes;
TemporaryBasal tempStart = new TemporaryBasal() //
TemporaryBasal tempStart = new TemporaryBasal(getInjector()) //
.date(System.currentTimeMillis()) //
.duration(durationInMinutes) //
.absolute(absoluteRate) //
@ -1371,7 +1371,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (response) {
aapsLogger.info(LTag.PUMP, getLogPrefix() + "cancelTempBasal - Cancel TBR successful.");
TemporaryBasal tempBasal = new TemporaryBasal() //
TemporaryBasal tempBasal = new TemporaryBasal(getInjector()) //
.date(System.currentTimeMillis()) //
.duration(0) //
.source(Source.USER);

View file

@ -239,7 +239,7 @@ class VirtualPumpPlugin @Inject constructor(
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult {
val tempBasal = TemporaryBasal()
val tempBasal = TemporaryBasal(injector)
.date(System.currentTimeMillis())
.absolute(absoluteRate)
.duration(durationInMinutes)
@ -259,7 +259,7 @@ class VirtualPumpPlugin @Inject constructor(
}
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult {
val tempBasal = TemporaryBasal()
val tempBasal = TemporaryBasal(injector)
.date(System.currentTimeMillis())
.percent(percent)
.duration(durationInMinutes)
@ -307,7 +307,7 @@ class VirtualPumpPlugin @Inject constructor(
result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
if (treatmentsPlugin.isTempBasalInProgress) {
result.enacted = true
val tempStop = TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER)
val tempStop = TemporaryBasal(injector).date(System.currentTimeMillis()).source(Source.USER)
treatmentsPlugin.addToHistoryTempBasal(tempStop)
//tempBasal = null;
aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result")

View file

@ -109,7 +109,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
}
// reset deviations after site change
if (CareportalEvent.isEvent5minBack(siteChanges, autosensData.time)) {
if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) {
deviationsArray.clear();
pastSensitivity += "(SITECHANGE)";
}

View file

@ -118,7 +118,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
String pastSensitivity = pastSensitivityArray.get(hoursegment);
// reset deviations after site change
if (CareportalEvent.isEvent5minBack(siteChanges, autosensData.time)) {
if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) {
deviationsArray.clear();
pastSensitivity += "(SITECHANGE)";
}

View file

@ -111,7 +111,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin
}
// reset deviations after site change
if (CareportalEvent.isEvent5minBack(siteChanges, autosensData.time)) {
if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) {
data.clear();
pastSensitivity += "(SITECHANGE)";
}

View file

@ -102,7 +102,7 @@ class DexcomPlugin @Inject constructor(
jsonObject.put("glucose", meter.getInt("meterValue"))
jsonObject.put("units", Constants.MGDL)
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.date = timestamp
careportalEvent.source = Source.USER
careportalEvent.eventType = CareportalEvent.BGCHECK
@ -122,7 +122,7 @@ class DexcomPlugin @Inject constructor(
jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime))
jsonObject.put("eventType", CareportalEvent.SENSORCHANGE)
val careportalEvent = CareportalEvent()
val careportalEvent = CareportalEvent(injector)
careportalEvent.date = sensorInsertionTime
careportalEvent.source = Source.USER
careportalEvent.eventType = CareportalEvent.SENSORCHANGE

View file

@ -402,7 +402,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue;
if (truncate && t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal();
TemporaryBasal dummyTemp = new TemporaryBasal(getInjector());
dummyTemp.copyFrom(t);
dummyTemp.cutEndTo(truncateTime);
calc = dummyTemp.iobCalc(time, profile);
@ -477,7 +477,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue;
if (t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal();
TemporaryBasal dummyTemp = new TemporaryBasal(getInjector());
dummyTemp.copyFrom(t);
dummyTemp.cutEndTo(truncateTime);
calc = dummyTemp.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget);
@ -586,7 +586,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
else if (tempBasal.isAbsolute)
NSUpload.uploadTempBasalStartAbsolute(tempBasal, null);
else
NSUpload.uploadTempBasalStartPercent(tempBasal);
NSUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date));
}
return newRecordCreated;
}
@ -706,7 +706,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public void addToHistoryTempTarget(TempTarget tempTarget) {
//log.debug("Adding new TemporaryBasal record" + profileSwitch.log());
MainApp.getDbHelper().createOrUpdate(tempTarget);
NSUpload.uploadTempTarget(tempTarget);
NSUpload.uploadTempTarget(tempTarget, profileFunction);
}
@Override

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.data
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
@ -9,21 +12,23 @@ import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class NonOverlappingIntervalsTest {
class NonOverlappingIntervalsTest : TestBase() {
private val startDate = DateUtil.now()
var list = NonOverlappingIntervals<TemporaryBasal>()
val injector = HasAndroidInjector { AndroidInjector {} }
@Test
fun doTests() {
// create one 10h interval and test value in and out
list.add(TemporaryBasal().date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
list.add(TemporaryBasal(injector).date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs()))
Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01)
Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1))
// stop temp after 5h
list.add(TemporaryBasal().date(startDate + T.hours(5).msecs()).duration(0))
list.add(TemporaryBasal(injector).date(startDate + T.hours(5).msecs()).duration(0))
Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs()))
Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01)
Assert.assertEquals(1.0, list.getValueByInterval(startDate + T.hours(5).msecs() - 1)!!.absoluteRate, 0.01)
@ -31,7 +36,7 @@ class NonOverlappingIntervalsTest {
Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1))
// insert 1h interval inside
list.add(TemporaryBasal().date(startDate + T.hours(3).msecs()).duration(T.hours(1).mins().toInt()).absolute(2.0))
list.add(TemporaryBasal(injector).date(startDate + T.hours(3).msecs()).duration(T.hours(1).mins().toInt()).absolute(2.0))
Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs()))
Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01)
Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(5).msecs() - 1))
@ -44,7 +49,7 @@ class NonOverlappingIntervalsTest {
@Test
fun testCopyConstructor() {
list.reset()
list.add(TemporaryBasal().date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
list.add(TemporaryBasal(injector).date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0))
val list2 = NonOverlappingIntervals(list)
Assert.assertEquals(1, list2.list.size.toLong())
}

View file

@ -2,20 +2,14 @@ package info.nightscout.androidaps.plugins.aps.loop
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
@ -35,6 +29,8 @@ class APSResultTest : TestBaseWithProfile() {
@Mock lateinit var sp: SP
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
private val injector = HasAndroidInjector { AndroidInjector { } }
private var closedLoopEnabled = Constraint(false)
private val pumpDescription = PumpDescription()
@ -79,36 +75,36 @@ class APSResultTest : TestBaseWithProfile() {
Assert.assertEquals(false, apsResult.isChangeRequested)
// request equal temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(70).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request zero temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(10).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(10).duration(30))
apsResult.tempBasalRequested(true).percent(0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request high temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(190).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(190).duration(30))
apsResult.tempBasalRequested(true).percent(200).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request slightly different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(80).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(70).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(70).duration(30))
apsResult.tempBasalRequested(true).percent(120).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// it should work with absolute temps too
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.0).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.0).duration(30))
apsResult.tempBasalRequested(true).percent(100).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(2.0).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30))
apsResult.tempBasalRequested(true).percent(50).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
@ -124,39 +120,39 @@ class APSResultTest : TestBaseWithProfile() {
Assert.assertEquals(false, apsResult.isChangeRequested)
// request equal temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(2.0).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(2.0).duration(30))
apsResult.tempBasalRequested(true).rate(2.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(200).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30))
apsResult.tempBasalRequested(true).rate(2.0).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request zero temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(0.1).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(0.1).duration(30))
apsResult.tempBasalRequested(true).rate(0.0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request high temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(34.9).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(34.9).duration(30))
apsResult.tempBasalRequested(true).rate(35.0).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// request slightly different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.1).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30))
apsResult.tempBasalRequested(true).rate(1.2).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().absolute(1.1).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).absolute(1.1).duration(30))
apsResult.tempBasalRequested(true).rate(1.5).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
// it should work with percent temps too
// request different temp
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(110).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(110).duration(30))
apsResult.tempBasalRequested(true).rate(1.1).duration(30)
Assert.assertEquals(false, apsResult.isChangeRequested)
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal().percent(200).duration(30))
`when`(treatmentsPlugin.getTempBasalFromHistory(ArgumentMatchers.anyLong())).thenReturn(TemporaryBasal(injector).percent(200).duration(30))
apsResult.tempBasalRequested(true).rate(0.5).duration(30)
Assert.assertEquals(true, apsResult.isChangeRequested)
}
@ -173,7 +169,7 @@ class APSResultTest : TestBaseWithProfile() {
it.resourceHelper = resourceHelper
}
apsResult.rate(10.0)
val apsResult2 = apsResult.newAndClone(HasAndroidInjector { AndroidInjector { Unit } })
val apsResult2 = apsResult.newAndClone(injector)
Assert.assertEquals(apsResult.rate, apsResult2.rate, 0.0)
}

View file

@ -6,7 +6,6 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
@ -28,7 +27,6 @@ class ConfigBuilderPluginTest : TestBase() {
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var profileFunction: ProfileFunction
lateinit var configBuilderPlugin: ConfigBuilderPlugin
@ -45,6 +43,6 @@ class ConfigBuilderPluginTest : TestBase() {
@Before
fun prepareMock() {
configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, profileFunction)
configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, resourceHelper, sp, RxBusWrapper(), activePlugin)
}
}

View file

@ -16,9 +16,11 @@ import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConfigBuilderPlugin::class)
class AutomationEventTest : TestBase() {
@Mock lateinit var loopPlugin: LoopPlugin

View file

@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.mockito.Mock
import org.powermock.core.classloader.annotations.PrepareForTest
@PrepareForTest(VirtualPumpPlugin::class, RxBusWrapper::class, LocalProfilePlugin::class, SmsCommunicatorPlugin::class)
@PrepareForTest(VirtualPumpPlugin::class, RxBusWrapper::class, LocalProfilePlugin::class, SmsCommunicatorPlugin::class, ConfigBuilderPlugin::class)
open class ActionsTestBase : TestBaseWithProfile() {
@Mock lateinit var sp: SP

View file

@ -1,8 +1,10 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Before
@ -11,7 +13,15 @@ import org.mockito.Mock
open class DanaRTestBase : TestBase() {
@Mock lateinit var sp: SP
@Mock lateinit var injector: HasAndroidInjector
@Mock lateinit var profileFunction: ProfileFunction
val injector = HasAndroidInjector {
AndroidInjector {
if (it is TemporaryBasal) {
it.profileFunction = profileFunction
}
}
}
lateinit var danaRPump: DanaRPump

View file

@ -20,7 +20,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTableRTest : DanaRTestBase() {
@Mock lateinit var rxBus: RxBusWrapper
@ -36,7 +36,7 @@ class MessageHashTableRTest : DanaRTestBase() {
@Test fun runTest() {
Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTable = MessageHashTableR(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin)
val messageHashTable = MessageHashTableR(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin, injector)
val testMessage = messageHashTable.findMessage(0x41f2)
Assert.assertEquals("CMD_HISTORY_ALL", testMessage.messageName)
}

View file

@ -14,7 +14,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class, ConfigBuilderPlugin::class)
class MsgInitConnStatusTimeTest : DanaRTestBase() {
@Mock lateinit var resourceHelper: ResourceHelper

View file

@ -1,15 +1,18 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConfigBuilderPlugin::class)
class MsgStatusTempBasalTest : DanaRTestBase() {
@Mock lateinit var activePlugin: ActivePluginProvider
@ -17,7 +20,7 @@ class MsgStatusTempBasalTest : DanaRTestBase() {
@Test fun runTest() {
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin)
val packet = MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin)
val packet = MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)
// test message decoding
// test message decoding
packet.handleMessage(createArray(34, 1.toByte()))

View file

@ -19,7 +19,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTableRKoreanTest : DanaRSTestBase() {
@Mock lateinit var constraintChecker: ConstraintChecker
@ -32,7 +32,7 @@ class MessageHashTableRKoreanTest : DanaRSTestBase() {
@Test fun runTest() {
Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTable = MessageHashTableRKorean(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin)
val messageHashTable = MessageHashTableRKorean(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, activePlugin, injector)
val testMessage = messageHashTable.findMessage(0x41f2)
Assert.assertEquals("CMD_HISTORY_ALL", testMessage.messageName)
}

View file

@ -28,7 +28,7 @@ class DanaRSMessageHashTableTest : DanaRSTestBase() {
fun runTest() {
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val danaRSMessageHashTable = DanaRSMessageHashTable(aapsLogger, rxBus, resourceHelper, danaRPump, danaRSPlugin, activePlugin, constraintChecker, detailedBolusInfoStorage)
val danaRSMessageHashTable = DanaRSMessageHashTable(aapsLogger, rxBus, resourceHelper, danaRPump, danaRSPlugin, activePlugin, constraintChecker, detailedBolusInfoStorage, injector)
val forTesting: DanaRS_Packet = DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, 0, 0, 0)
val testPacket: DanaRS_Packet = danaRSMessageHashTable.findMessage(forTesting.command)
Assert.assertEquals(BleCommandUtil.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY.toLong(), testPacket.getOpCode().toLong())

View file

@ -1,7 +1,10 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Before
@ -10,7 +13,14 @@ import org.mockito.Mock
open class DanaRSTestBase : TestBaseWithProfile() {
@Mock lateinit var sp: SP
@Mock lateinit var injector: HasAndroidInjector
val injector = HasAndroidInjector {
AndroidInjector {
if (it is TemporaryBasal) {
it.profileFunction = profileFunction
}
}
}
lateinit var danaRPump: DanaRPump

View file

@ -24,7 +24,7 @@ class DanaRS_Packet_APS_History_EventsTest : DanaRSTestBase() {
@Test fun runTest() {
val now = DateUtil.now()
val testPacket = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, now)
val testPacket = DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, now)
// test getRequestedParams
val returnedValues = testPacket.requestParams
val expectedValues = getCalender(now)

View file

@ -23,7 +23,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class, ConfigBuilderPlugin::class)
class MessageHashTable_rv2Test : DanaRTestBase() {
@Mock lateinit var rxBus: RxBusWrapper
@ -41,7 +41,7 @@ class MessageHashTable_rv2Test : DanaRTestBase() {
@Test
fun runTest() {
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
val messageHashTableRv2 = MessageHashTableRv2(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue, activePlugin, detailedBolusInfoStorage, treatmentsPlugin)
val messageHashTableRv2 = MessageHashTableRv2(aapsLogger, rxBus, resourceHelper, constraintChecker, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue, activePlugin, detailedBolusInfoStorage, treatmentsPlugin, injector)
val forTesting: MessageBase = MsgStatusAPS_v2(aapsLogger, danaRPump)
val testPacket: MessageBase = messageHashTableRv2.findMessage(forTesting.command)
Assert.assertEquals(0xE001, testPacket.command.toLong())

View file

@ -17,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class, DanaRv2Plugin::class)
@PrepareForTest(DanaRKoreanPlugin::class, DanaRPlugin::class, DanaRv2Plugin::class, ConfigBuilderPlugin::class)
class MsgCheckValue_v2Test : DanaRTestBase() {
val rxBus = RxBusWrapper()

View file

@ -23,7 +23,7 @@ class MsgHistoryEvents_v2Test : DanaRTestBase() {
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Test @Throws(Exception::class) fun runTest() {
var packet = MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, RxBusWrapper(), treatmentsPlugin, 0)
var packet = MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, RxBusWrapper(), treatmentsPlugin, injector, 0)
// test message decoding
val array = ByteArray(100)

View file

@ -1,6 +1,8 @@
package info.nightscout.androidaps.plugins.treatments
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.DatabaseHelper
@ -32,6 +34,14 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
@Mock lateinit var databaseHelper: DatabaseHelper
@Mock lateinit var treatmentService: TreatmentService
val injector = HasAndroidInjector {
AndroidInjector {
if (it is TemporaryBasal) {
it.profileFunction = profileFunction
}
}
}
lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin
lateinit var sot: TreatmentsPlugin
@ -53,7 +63,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
fun `zero TBR should produce zero absolute insulin`() {
val now = DateUtil.now()
val tbrs : MutableList<TemporaryBasal> = ArrayList()
tbrs.add(TemporaryBasal().date(now - T.hours(30). msecs()).duration(10000).percent(0))
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30). msecs()).duration(10000).percent(0))
`when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs)
sot.initializeData(T.hours(30). msecs())
@ -69,7 +79,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
sot.initializeData(T.hours(30). msecs())
val iob100pct = sot.getAbsoluteIOBTempBasals(now)
tbrs.add(TemporaryBasal().date(now - T.hours(30). msecs()).duration(10000).percent(90))
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30). msecs()).duration(10000).percent(90))
sot.initializeData(T.hours(30). msecs())
val iob90pct = sot.getAbsoluteIOBTempBasals(now)
Assert.assertTrue(iob100pct.iob > iob90pct.iob)
@ -83,7 +93,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
sot.initializeData(T.hours(30). msecs())
val iob100pct = sot.getAbsoluteIOBTempBasals(now)
tbrs.add(TemporaryBasal().date(now - T.hours(30). msecs()).duration(10000).percent(110))
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30). msecs()).duration(10000).percent(110))
sot.initializeData(T.hours(30). msecs())
val iob110pct = sot.getAbsoluteIOBTempBasals(now)
Assert.assertEquals(1.1, iob110pct.iob / iob100pct.iob, 0.0001)