remove ProfileFunctions dependency

This commit is contained in:
Milos Kozak 2020-03-17 22:56:14 +01:00
parent 8b9bbd2170
commit 7e9402b939
52 changed files with 298 additions and 1037 deletions

View file

@ -62,6 +62,10 @@ public class BgReading implements DataPointWithLabelInterface {
MainApp.instance().androidInjector().inject(this); MainApp.instance().androidInjector().inject(this);
} }
public BgReading(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
}
public BgReading(NSSgv sgv) { public BgReading(NSSgv sgv) {
date = sgv.getMills(); date = sgv.getMills();
value = sgv.getMgdl(); value = sgv.getMgdl();

View file

@ -9,7 +9,6 @@ import org.apache.commons.lang3.StringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
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;
@ -26,7 +25,7 @@ import info.nightscout.androidaps.data.Profile;
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.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg; import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment; 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.DataPointWithLabelInterface;
@ -168,7 +167,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@Override @Override
public double getY() { public double getY() {
String units = ProfileFunctions.getSystemUnits(); String units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits();
if (eventType.equals(MBG)) { if (eventType.equals(MBG)) {
double mbg = 0d; double mbg = 0d;
try { try {

View file

@ -15,8 +15,8 @@ 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.PluginStore;
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;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
@ -95,7 +95,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
} }
public TemporaryBasal(ExtendedBolus extendedBolus) { public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = ProfileFunctions.getInstance().getProfile(extendedBolus.date).getBasal(extendedBolus.date); double basal = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date; this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid; this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source; this.source = extendedBolus.source;
@ -404,7 +404,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
public String toStringFull() { public String toStringFull() {
if (isFakeExtended) { if (isFakeExtended) {
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null) if (profile == null)
return "null"; return "null";
Double currentBasalRate = profile.getBasal(); Double currentBasalRate = profile.getBasal();
@ -428,7 +428,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
double rate; double rate;
if (isFakeExtended) { if (isFakeExtended) {
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null) if (profile == null)
return "null"; return "null";
double currentBasalRate = profile.getBasal(); double currentBasalRate = profile.getBasal();
@ -438,7 +438,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
} }
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) { if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile != null) { if (profile != null) {
double basal = profile.getBasal(); double basal = profile.getBasal();
if (basal != 0) { if (basal != 0) {
@ -453,7 +453,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
} }
private String getCalcuatedPercentageIfNeeded() { private String getCalcuatedPercentageIfNeeded() {
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null) if (profile == null)
return "null"; return "null";
@ -479,7 +479,7 @@ public class TemporaryBasal implements Interval, DbObjectBase {
} }
public String toStringVeryShort() { public String toStringVeryShort() {
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
if (profile == null) if (profile == null)
return "null"; return "null";

View file

@ -59,8 +59,8 @@ open class AppModule {
@Provides @Provides
@Singleton @Singleton
fun provideProfileFunction(sp: SP): ProfileFunction { fun provideProfileFunction(aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider): ProfileFunction {
return ProfileFunctionImplementation(sp) return ProfileFunctionImplementation(aapsLogger, sp, resourceHelper, activePlugin)
} }
@Provides @Provides
@ -92,6 +92,7 @@ open class AppModule {
@ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB
@ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA @ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA
@ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA @ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA
@ContributesAndroidInjector @ContributesAndroidInjector
fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS

View file

@ -40,6 +40,7 @@ import info.nightscout.androidaps.plugins.source.BGSourceFragment
import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment
@ -79,16 +80,11 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesTidepoolFragment(): TidepoolFragment @ContributesAndroidInjector abstract fun contributesTidepoolFragment(): TidepoolFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment @ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment
abstract fun contributesTreatmentsBolusFragment(): TreatmentsBolusFragment @ContributesAndroidInjector abstract fun contributesTreatmentsTempTargetFragment(): TreatmentsTempTargetFragment
@ContributesAndroidInjector @ContributesAndroidInjector abstract fun contributesTreatmentsExtendedBolusesFragment(): TreatmentsExtendedBolusesFragment
abstract fun contributesTreatmentsTempTargetFragment(): TreatmentsTempTargetFragment @ContributesAndroidInjector abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment
@ContributesAndroidInjector
abstract fun contributesTreatmentsCareportalFragment(): TreatmentsCareportalFragment
@ContributesAndroidInjector
abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment
@ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment @ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment

View file

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

View file

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

View file

@ -81,7 +81,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
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")
?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) ?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, ok, textWatcher)
} }
override fun submit(): Boolean { override fun submit(): Boolean {
@ -94,7 +94,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
if (insulinAfterConstraints > 0) { if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>") actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
if (recordOnlyChecked) if (recordOnlyChecked)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.bolusrecordedonly) + "</font>") actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.bolusrecordedonly) + "</font>")
if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints))

View file

@ -111,7 +111,7 @@ class WizardDialog : DaggerDialogFragment() {
?: 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 = activePlugin.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(activePlugin.activePump), 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")
?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) ?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher)
initDialog() initDialog()

View file

@ -39,7 +39,7 @@ public class APSResult {
@Inject public AAPSLogger aapsLogger; @Inject public AAPSLogger aapsLogger;
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
@Inject SP sp; @Inject SP sp;
@Inject ActivePluginProvider activePluginProvider; @Inject ActivePluginProvider activePlugin;
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@ -101,7 +101,7 @@ public class APSResult {
@Override @Override
public String toString() { public String toString() {
final PumpInterface pump = activePluginProvider.getActivePump(); final PumpInterface pump = activePlugin.getActivePump();
if (isChangeRequested()) { if (isChangeRequested()) {
String ret; String ret;
// rate // rate
@ -120,7 +120,7 @@ public class APSResult {
// smb // smb
if (smb != 0) if (smb != 0)
ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U\n"); ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U\n");
// reason // reason
ret += resourceHelper.gs(R.string.reason) + ": " + reason; ret += resourceHelper.gs(R.string.reason) + ": " + reason;
@ -130,7 +130,7 @@ public class APSResult {
} }
public Spanned toSpanned() { public Spanned toSpanned() {
final PumpInterface pump = activePluginProvider.getActivePump(); final PumpInterface pump = activePlugin.getActivePump();
if (isChangeRequested()) { if (isChangeRequested()) {
String ret; String ret;
// rate // rate
@ -149,7 +149,7 @@ public class APSResult {
// smb // smb
if (smb != 0) if (smb != 0)
ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U<br>"); ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U<br>");
// reason // reason
ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;"); ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
@ -314,7 +314,7 @@ public class APSResult {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now); TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now);
PumpInterface pump = activePluginProvider.getActivePump(); PumpInterface pump = activePlugin.getActivePump();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
if (profile == null) { if (profile == null) {

View file

@ -53,17 +53,17 @@ public class ConfigBuilderPlugin extends PluginBase {
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 ProfileFunction profileFunction;
/** /**
* @deprecated Use dagger to get an instance * @deprecated Use dagger to get an instance
*/ */
@Deprecated @Deprecated
public CommandQueueProvider getCommandQueue() { public ProfileFunction getProfileFunction() {
if (commandQueue == null) if (profileFunction == null)
throw new IllegalStateException("Accessing commandQueue before first instantiation"); throw new IllegalStateException("Accessing profileFunction before first instantiation");
return commandQueue; return profileFunction;
} }
@Deprecated @Deprecated
@ -88,7 +88,7 @@ public class ConfigBuilderPlugin extends PluginBase {
RxBusWrapper rxBus, RxBusWrapper rxBus,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
CommandQueueProvider commandQueue ProfileFunction profileFunction
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
@ -106,7 +106,7 @@ public class ConfigBuilderPlugin extends PluginBase {
this.rxBus = rxBus; this.rxBus = rxBus;
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.commandQueue = commandQueue; this.profileFunction = profileFunction;
configBuilderPlugin = this; // TODO: only while transitioning to Dagger configBuilderPlugin = this; // TODO: only while transitioning to Dagger
} }

View file

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

View file

@ -1,148 +0,0 @@
package info.nightscout.androidaps.plugins.configBuilder;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import info.nightscout.androidaps.BuildConfig;
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.data.ProfileStore;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
public class ProfileFunctions implements ProfileFunction {
private static Logger log = StacktraceLoggerWrapper.getLogger(L.PROFILE);
private static ProfileFunctions profileFunctions = null;
@Deprecated
public static ProfileFunctions getInstance() {
if (profileFunctions == null)
profileFunctions = new ProfileFunctions();
return profileFunctions;
}
@NotNull
public String getProfileName() {
return getProfileName(System.currentTimeMillis(), true, false);
}
@NotNull
public String getProfileName(boolean customized) {
return getProfileName(System.currentTimeMillis(), customized, false);
}
@NotNull
public String getProfileNameWithDuration() {
return getProfileName(System.currentTimeMillis(), true, true);
}
@NotNull
public String getProfileName(long time, boolean customized, boolean showRemainingTime) {
String profileName = MainApp.gs(R.string.noprofileselected);
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = PluginStore.Companion.getInstance().getActiveProfileInterface();
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
profileName = customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
profileName = profileSwitch.profileName;
}
}
if (showRemainingTime && profileSwitch.durationInMinutes != 0) {
profileName += DateUtil.untilString(profileSwitch.originalEnd());
}
return profileName;
}
return profileName;
}
public boolean isProfileValid(@NotNull String from) {
Profile profile = getProfile();
return profile != null && profile.isValid(from);
}
@Nullable
public Profile getProfile() {
return getProfile(System.currentTimeMillis());
}
@NotNull
public String getUnits() {
return getSystemUnits();
}
@NotNull
@Deprecated
public static String getSystemUnits() {
return SP.getString(R.string.key_units, Constants.MGDL);
}
@Nullable
public Profile getProfile(long time) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = PluginStore.Companion.getInstance().getActiveProfileInterface();
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return profileSwitch.getProfileObject();
} else if (activeProfile.getProfile() != null) {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profile;
}
}
if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "CatchedError");
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, BuildConfig.BUILDVERSION);
bundle.putString(FirebaseAnalytics.Param.START_DATE, String.valueOf(time));
bundle.putString(FirebaseAnalytics.Param.VALUE, activeTreatments.getProfileSwitchesFromHistory().toString());
FabricPrivacy.getInstance().logCustom(bundle);
}
log.error("getProfile at the end: returning null");
return null;
}
@NotNull
public ProfileSwitch prepareProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, long date) {
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = date;
profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
profileSwitch.profilePlugin = PluginStore.Companion.getInstance().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeShift != 0;
profileSwitch.timeshift = timeShift;
profileSwitch.percentage = percentage;
return profileSwitch;
}
}

View file

@ -5,25 +5,21 @@ import android.content.SharedPreferences;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import androidx.preference.PreferenceManager;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.preference.PreferenceManager;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
@ -43,7 +39,6 @@ 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.PluginStore;
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;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
@ -78,7 +73,7 @@ public class NSUpload {
try { try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false); boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
Profile profile = ProfileFunctions.getInstance().getProfile(temporaryBasal.date); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(temporaryBasal.date);
double absoluteRate = 0; double absoluteRate = 0;
if (profile != null) { if (profile != null) {
absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d; absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d;
@ -163,8 +158,8 @@ public class NSUpload {
} }
public static void uploadDeviceStatus(LoopPlugin loopPlugin) { public static void uploadDeviceStatus(LoopPlugin loopPlugin) {
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile();
String profileName = ProfileFunctions.getInstance().getProfileName(); String profileName = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfileName();
if (profile == null || profileName == null) { if (profile == null || profileName == null) {
log.error("Profile is null. Skipping upload"); log.error("Profile is null. Skipping upload");
@ -272,9 +267,9 @@ public class NSUpload {
data.put("duration", tempTarget.durationInMinutes); data.put("duration", tempTarget.durationInMinutes);
if (tempTarget.low > 0) { if (tempTarget.low > 0) {
data.put("reason", tempTarget.reason); data.put("reason", tempTarget.reason);
data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, ProfileFunctions.getSystemUnits())); data.put("targetBottom", Profile.fromMgdlToUnits(tempTarget.low, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()));
data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, ProfileFunctions.getSystemUnits())); data.put("targetTop", Profile.fromMgdlToUnits(tempTarget.high, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits()));
data.put("units", ProfileFunctions.getSystemUnits()); data.put("units", ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits());
} }
data.put("created_at", DateUtil.toISOString(tempTarget.date)); data.put("created_at", DateUtil.toISOString(tempTarget.date));
data.put("enteredBy", MainApp.gs(R.string.app_name)); data.put("enteredBy", MainApp.gs(R.string.app_name));

View file

@ -1139,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())); tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end(), resourceHelper));
} 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));
@ -1239,7 +1239,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
quickWizardButton.setVisibility(View.VISIBLE); quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g"; String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
BolusWizard wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false); BolusWizard wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false);
text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.getCalculatedTotalInsulin()) + "U"; text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.getCalculatedTotalInsulin(), pump) + "U";
quickWizardButton.setText(text); quickWizardButton.setText(text);
if (wizard.getCalculatedTotalInsulin() <= 0) if (wizard.getCalculatedTotalInsulin() <= 0)
quickWizardButton.setVisibility(View.GONE); quickWizardButton.setVisibility(View.GONE);

View file

@ -32,8 +32,8 @@ 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.PluginStore;
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;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DoubleDataPoint; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DoubleDataPoint;
@ -68,7 +68,7 @@ public class GraphData {
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
public GraphData(GraphView graph, IobCobCalculatorPlugin iobCobCalculatorPlugin) { public GraphData(GraphView graph, IobCobCalculatorPlugin iobCobCalculatorPlugin) {
units = ProfileFunctions.getSystemUnits(); units = ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits();
this.graph = graph; this.graph = graph;
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
} }
@ -151,7 +151,7 @@ public class GraphData {
double lastBaseBasal = 0; double lastBaseBasal = 0;
double lastTempBasal = 0; double lastTempBasal = 0;
for (long time = fromTime; time < toTime; time += 60 * 1000L) { for (long time = fromTime; time < toTime; time += 60 * 1000L) {
Profile profile = ProfileFunctions.getInstance().getProfile(time); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(time);
if (profile == null) continue; if (profile == null) continue;
BasalData basalData = iobCobCalculatorPlugin.getBasalData(profile, time); BasalData basalData = iobCobCalculatorPlugin.getBasalData(profile, time);
double baseBasalValue = basalData.basal; double baseBasalValue = basalData.basal;
@ -263,9 +263,9 @@ public class GraphData {
TempTarget tt = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(time); TempTarget tt = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(time);
double value; double value;
if (tt == null) { if (tt == null) {
value = Profile.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2, ProfileFunctions.getSystemUnits()); value = Profile.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2, ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits());
} else { } else {
value = Profile.fromMgdlToUnits(tt.target(), ProfileFunctions.getSystemUnits()); value = Profile.fromMgdlToUnits(tt.target(), ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits());
} }
if (lastTarget != value) { if (lastTarget != value) {
if (lastTarget != -1) if (lastTarget != -1)
@ -360,7 +360,7 @@ public class GraphData {
double maxIAValue = 0; double maxIAValue = 0;
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
Profile profile = ProfileFunctions.getInstance().getProfile(time); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(time);
double act = 0d; double act = 0d;
if (profile == null) continue; if (profile == null) continue;
total = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile); total = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile);
@ -412,7 +412,7 @@ public class GraphData {
Scale iobScale = new Scale(); Scale iobScale = new Scale();
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
Profile profile = ProfileFunctions.getInstance().getProfile(time); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(time);
double iob = 0d; double iob = 0d;
if (profile != null) if (profile != null)
iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob; iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob;

View file

@ -222,7 +222,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
} else if (bolusMinAgo < 60) { } else if (bolusMinAgo < 60) {
ago = DateUtil.minAgo(bolus.timestamp); ago = DateUtil.minAgo(bolus.timestamp);
} else { } else {
ago = DateUtil.hourAgo(bolus.timestamp); ago = DateUtil.hourAgo(bolus.timestamp, resourceHelper);
} }
lastBolusView.setText(resourceHelper.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); lastBolusView.setText(resourceHelper.gs(R.string.combo_last_bolus, bolus.amount, unit, ago));
} else { } else {

View file

@ -164,7 +164,7 @@ class DanaRFragment : DaggerFragment() {
val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0 val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0
if (agoHours < 6) if (agoHours < 6)
// max 6h back // max 6h back
danar_lastbolus.text = DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) danar_lastbolus.text = DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount)
else else
danar_lastbolus.text = "" danar_lastbolus.text = ""
} }

View file

@ -297,7 +297,7 @@ class MedtronicFragment : DaggerFragment() {
} else if (bolusMinAgo < 60) { } else if (bolusMinAgo < 60) {
ago = DateUtil.minAgo(pumpStatus.lastBolusTime.time) ago = DateUtil.minAgo(pumpStatus.lastBolusTime.time)
} else { } else {
ago = DateUtil.hourAgo(pumpStatus.lastBolusTime.time) ago = DateUtil.hourAgo(pumpStatus.lastBolusTime.time, resourceHelper)
} }
medtronic_lastbolus.text = resourceHelper.gs(R.string.combo_last_bolus, bolus, unit, ago) medtronic_lastbolus.text = resourceHelper.gs(R.string.combo_last_bolus, bolus, unit, ago)
} else { } else {

View file

@ -245,7 +245,7 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase {
@Override @Override
public String getLabel() { public String getLabel() {
String label = ""; String label = "";
if (insulin > 0) label += DecimalFormatter.toPumpSupportedBolus(insulin) + "U"; if (insulin > 0) label += DecimalFormatter.toPumpSupportedBolus(insulin, activePlugin.getActivePump()) + "U";
if (carbs > 0) if (carbs > 0)
label += "~" + DecimalFormatter.to0Decimal(carbs) + "g"; label += "~" + DecimalFormatter.to0Decimal(carbs) + "g";
return label; return label;

View file

@ -107,7 +107,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
val careportalEvent = careportalEventList[position] val careportalEvent = careportalEventList[position]
holder.ns.visibility = if (NSUpload.isIdValid(careportalEvent._id)) View.VISIBLE else View.GONE holder.ns.visibility = if (NSUpload.isIdValid(careportalEvent._id)) View.VISIBLE else View.GONE
holder.date.text = DateUtil.dateAndTimeString(careportalEvent.date) holder.date.text = DateUtil.dateAndTimeString(careportalEvent.date)
holder.duration.text = if (careportalEvent.durationInMsec() == 0L) "" else DateUtil.niceTimeScalar(careportalEvent.durationInMsec()) holder.duration.text = if (careportalEvent.durationInMsec() == 0L) "" else DateUtil.niceTimeScalar(careportalEvent.durationInMsec(), resourceHelper)
holder.note.text = careportalEvent.notes holder.note.text = careportalEvent.notes
holder.type.text = Translator.translate(careportalEvent.eventType) holder.type.text = Translator.translate(careportalEvent.eventType)
holder.remove.tag = careportalEvent holder.remove.tag = careportalEvent

View file

@ -14,6 +14,9 @@ import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import javax.inject.Inject;
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.data.Intervals; import info.nightscout.androidaps.data.Intervals;
@ -21,6 +24,7 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
@ -34,7 +38,9 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
public class TreatmentsExtendedBolusesFragment extends Fragment { public class TreatmentsExtendedBolusesFragment extends DaggerFragment {
@Inject ActivePluginProvider activePlugin;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private RecyclerView recyclerView; private RecyclerView recyclerView;
@ -74,7 +80,7 @@ public class TreatmentsExtendedBolusesFragment extends Fragment {
holder.date.setText(DateUtil.dateAndTimeString(extendedBolus.date) + " - " + DateUtil.timeString(extendedBolus.end())); holder.date.setText(DateUtil.dateAndTimeString(extendedBolus.date) + " - " + DateUtil.timeString(extendedBolus.end()));
} }
holder.duration.setText(DecimalFormatter.to0Decimal(extendedBolus.durationInMinutes) + " min"); holder.duration.setText(DecimalFormatter.to0Decimal(extendedBolus.durationInMinutes) + " min");
holder.insulin.setText(DecimalFormatter.toPumpSupportedBolus(extendedBolus.insulin) + " U"); holder.insulin.setText(DecimalFormatter.toPumpSupportedBolus(extendedBolus.insulin, activePlugin.getActivePump()) + " U");
holder.realDuration.setText(DecimalFormatter.to0Decimal(extendedBolus.getRealDuration()) + " min"); holder.realDuration.setText(DecimalFormatter.to0Decimal(extendedBolus.getRealDuration()) + " min");
IobTotal iob = extendedBolus.iobCalc(System.currentTimeMillis()); IobTotal iob = extendedBolus.iobCalc(System.currentTimeMillis());
holder.iob.setText(DecimalFormatter.to2Decimal(iob.iob) + " U"); holder.iob.setText(DecimalFormatter.to2Decimal(iob.iob) + " U");

View file

@ -23,7 +23,7 @@ import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
@ -84,7 +84,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment {
} }
holder.duration.setText(DecimalFormatter.to0Decimal(tempBasal.durationInMinutes, " min")); holder.duration.setText(DecimalFormatter.to0Decimal(tempBasal.durationInMinutes, " min"));
if (tempBasal.isAbsolute) { if (tempBasal.isAbsolute) {
Profile profile = ProfileFunctions.getInstance().getProfile(tempBasal.date); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(tempBasal.date);
if (profile != null) { if (profile != null) {
holder.absolute.setText(DecimalFormatter.to2Decimal(tempBasal.tempBasalConvertedToAbsolute(tempBasal.date, profile), " U/h")); holder.absolute.setText(DecimalFormatter.to2Decimal(tempBasal.tempBasalConvertedToAbsolute(tempBasal.date, profile), " U/h"));
holder.percent.setText(""); holder.percent.setText("");
@ -99,7 +99,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment {
holder.realDuration.setText(DecimalFormatter.to0Decimal(tempBasal.getRealDuration(), " min")); holder.realDuration.setText(DecimalFormatter.to0Decimal(tempBasal.getRealDuration(), " min"));
long now = DateUtil.now(); long now = DateUtil.now();
IobTotal iob = new IobTotal(now); IobTotal iob = new IobTotal(now);
Profile profile = ProfileFunctions.getInstance().getProfile(now); Profile profile = ConfigBuilderPlugin.getPlugin().getProfileFunction().getProfile(now);
if (profile != null) if (profile != null)
iob = tempBasal.iobCalc(now, profile); iob = tempBasal.iobCalc(now, profile);
holder.iob.setText(DecimalFormatter.to2Decimal(iob.basaliob, " U")); holder.iob.setText(DecimalFormatter.to2Decimal(iob.basaliob, " U"));

View file

@ -12,7 +12,7 @@ import java.text.DecimalFormat;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.setupwizard.SWNumberValidator; import info.nightscout.androidaps.setupwizard.SWNumberValidator;
import info.nightscout.androidaps.utils.NumberPicker; import info.nightscout.androidaps.utils.NumberPicker;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
@ -64,10 +64,10 @@ public class SWEditNumberWithUnits extends SWItem {
layout.addView(l); layout.addView(l);
double initValue = SP.getDouble(preferenceId, init); double initValue = SP.getDouble(preferenceId, init);
initValue = Profile.toCurrentUnits(ProfileFunctions.getSystemUnits(), initValue); initValue = Profile.toCurrentUnits(ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits(), initValue);
NumberPicker numberPicker = new NumberPicker(context); NumberPicker numberPicker = new NumberPicker(context);
if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) if (ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits().equals(Constants.MMOL))
numberPicker.setParams(initValue, min, max, 0.1d, new DecimalFormat("0.0"), false, null, watcher); numberPicker.setParams(initValue, min, max, 0.1d, new DecimalFormat("0.0"), false, null, watcher);
else else
numberPicker.setParams(initValue, min * 18, max * 18, 1d, new DecimalFormat("0"), false, null, watcher); numberPicker.setParams(initValue, min * 18, max * 18, 1d, new DecimalFormat("0"), false, null, watcher);

View file

@ -63,7 +63,7 @@ class ActivityMonitor @Inject constructor(
if (key.startsWith("Monitor") && key.endsWith("total")) { if (key.startsWith("Monitor") && key.endsWith("total")) {
val v = if (value is Long) value else SafeParse.stringToLong(value as String) val v = if (value is Long) value else SafeParse.stringToLong(value as String)
val activity = key.split("_")[1].replace("Activity", "") val activity = key.split("_")[1].replace("Activity", "")
val duration = DateUtil.niceTimeScalar(v as Long) val duration = DateUtil.niceTimeScalar(v as Long, resourceHelper)
val start = sp.getLong(key.replace("total", "start"), 0) val start = sp.getLong(key.replace("total", "start"), 0)
val days = T.msecs(DateUtil.now() - start).days() val days = T.msecs(DateUtil.now() - start).days()
result += "<b><span style=\"color:yellow\">$activity:</span></b> <b>$duration</b> in <b>$days</b> days<br>" result += "<b><span style=\"color:yellow\">$activity:</span></b> <b>$duration</b> in <b>$days</b> days<br>"

View file

@ -21,6 +21,7 @@ import java.util.regex.Pattern;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
/** /**
* The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string &lt;-&gt; date obj * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string &lt;-&gt; date obj
@ -185,9 +186,9 @@ public class DateUtil {
return (mins > 0 ? "+" : "") + mins.toString(); return (mins > 0 ? "+" : "") + mins.toString();
} }
public static String hourAgo(long time) { public static String hourAgo(long time, ResourceHelper resourceHelper) {
double hours = (now() - time) / 1000d / 60 / 60; double hours = (now() - time) / 1000d / 60 / 60;
return MainApp.gs(R.string.hoursago, hours); return resourceHelper.gs(R.string.hoursago, hours);
} }
private static LongSparseArray<String> timeStrings = new LongSparseArray<>(); private static LongSparseArray<String> timeStrings = new LongSparseArray<>();
@ -202,19 +203,19 @@ public class DateUtil {
} }
public static String timeFrameString(long timeInMillis) { public static String timeFrameString(long timeInMillis, ResourceHelper resourceHelper) {
long remainingTimeMinutes = timeInMillis / (1000 * 60); long remainingTimeMinutes = timeInMillis / (1000 * 60);
long remainingTimeHours = remainingTimeMinutes / 60; long remainingTimeHours = remainingTimeMinutes / 60;
remainingTimeMinutes = remainingTimeMinutes % 60; remainingTimeMinutes = remainingTimeMinutes % 60;
return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + MainApp.gs(R.string.shorthour) + " ") : "") + remainingTimeMinutes + "')"; return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + resourceHelper.gs(R.string.shorthour) + " ") : "") + remainingTimeMinutes + "')";
} }
public static String sinceString(long timestamp) { public static String sinceString(long timestamp, ResourceHelper resourceHelper) {
return timeFrameString(System.currentTimeMillis() - timestamp); return timeFrameString(System.currentTimeMillis() - timestamp, resourceHelper);
} }
public static String untilString(long timestamp) { public static String untilString(long timestamp, ResourceHelper resourceHelper) {
return timeFrameString(timestamp - System.currentTimeMillis()); return timeFrameString(timestamp - System.currentTimeMillis(), resourceHelper);
} }
public static long now() { public static long now() {
@ -247,26 +248,26 @@ public class DateUtil {
return TimeZone.getDefault().getOffset(timestamp) / 60000; return TimeZone.getDefault().getOffset(timestamp) / 60000;
} }
public static String niceTimeScalar(long t) { public static String niceTimeScalar(long t, ResourceHelper resourceHelper) {
String unit = MainApp.gs(R.string.unit_second); String unit = resourceHelper.gs(R.string.unit_second);
t = t / 1000; t = t / 1000;
if (t != 1) unit = MainApp.gs(R.string.unit_seconds); if (t != 1) unit = resourceHelper.gs(R.string.unit_seconds);
if (t > 59) { if (t > 59) {
unit = MainApp.gs(R.string.unit_minute); unit = resourceHelper.gs(R.string.unit_minute);
t = t / 60; t = t / 60;
if (t != 1) unit = MainApp.gs(R.string.unit_minutes); if (t != 1) unit = resourceHelper.gs(R.string.unit_minutes);
if (t > 59) { if (t > 59) {
unit = MainApp.gs(R.string.unit_hour); unit = resourceHelper.gs(R.string.unit_hour);
t = t / 60; t = t / 60;
if (t != 1) unit = MainApp.gs(R.string.unit_hours); if (t != 1) unit = resourceHelper.gs(R.string.unit_hours);
if (t > 24) { if (t > 24) {
unit = MainApp.gs(R.string.unit_day) + "\""; unit = resourceHelper.gs(R.string.unit_day) + "\"";
t = t / 24; t = t / 24;
if (t != 1) unit = MainApp.gs(R.string.unit_days) + "\""; if (t != 1) unit = resourceHelper.gs(R.string.unit_days) + "\"";
if (t > 28) { if (t > 28) {
unit = MainApp.gs(R.string.unit_week) + "\""; unit = resourceHelper.gs(R.string.unit_week) + "\"";
t = t / 7; t = t / 7;
if (t != 1) unit = MainApp.gs(R.string.unit_weeks) + "\""; if (t != 1) unit = resourceHelper.gs(R.string.unit_weeks) + "\"";
} }
} }
} }

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.PluginStore; import info.nightscout.androidaps.interfaces.PumpInterface;
/** /**
* Created by mike on 11.07.2016. * Created by mike on 11.07.2016.
@ -45,14 +45,14 @@ public class DecimalFormatter {
return format3dec.format(value) + unit; return format3dec.format(value) + unit;
} }
public static String toPumpSupportedBolus(double value) { public static String toPumpSupportedBolus(double value, PumpInterface pump) {
return PluginStore.Companion.getInstance().getActivePump().getPumpDescription().bolusStep <= 0.051 return pump.getPumpDescription().bolusStep <= 0.051
? to2Decimal(value) ? to2Decimal(value)
: to1Decimal(value); : to1Decimal(value);
} }
public static DecimalFormat pumpSupportedBolusFormat() { public static DecimalFormat pumpSupportedBolusFormat(PumpInterface pump) {
return PluginStore.Companion.getInstance().getActivePump().getPumpDescription().bolusStep <= 0.051 return pump.getPumpDescription().bolusStep <= 0.051
? new DecimalFormat("0.00") ? new DecimalFormat("0.00")
: new DecimalFormat("0.0"); : new DecimalFormat("0.0");
} }

View file

@ -6,7 +6,6 @@ import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
@ -14,7 +13,7 @@ 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.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.services.Intents;
/** /**
@ -35,7 +34,7 @@ public class XdripCalibrations {
Context context = MainApp.instance().getApplicationContext(); Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putDouble("glucose_number", bg); bundle.putDouble("glucose_number", bg);
bundle.putString("units", ProfileFunctions.getSystemUnits().equals(Constants.MGDL) ? "mgdl" : "mmol"); bundle.putString("units", ConfigBuilderPlugin.getPlugin().getProfileFunction().getUnits().equals(Constants.MGDL) ? "mgdl" : "mmol");
bundle.putLong("timestamp", System.currentTimeMillis()); bundle.putLong("timestamp", System.currentTimeMillis());
Intent intent = new Intent(Intents.ACTION_REMOTE_CALIBRATION); Intent intent = new Intent(Intents.ACTION_REMOTE_CALIBRATION);
intent.putExtras(bundle); intent.putExtras(bundle);

View file

@ -1,9 +1,10 @@
package info.nightscout.androidaps.utils.extensions package info.nightscout.androidaps.utils.extensions
import info.nightscout.androidaps.interfaces.PumpInterface
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
fun Double.toSignedString(): String { fun Double.toSignedString(pump: PumpInterface): String {
val formatted = DecimalFormatter.toPumpSupportedBolus(this) val formatted = DecimalFormatter.toPumpSupportedBolus(this, pump)
return if (this > 0) "+$formatted" else formatted return if (this > 0) "+$formatted" else formatted
} }

View file

@ -1,287 +0,0 @@
package info;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.powermock.api.mockito.PowerMockito;
import java.util.Locale;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentService;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.androidaps.utils.SP;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Created by mike on 23.03.2018.
*/
public class AAPSMocker {
private static String validProfile = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}";
private static Profile profile;
private static ProfileStore profileStore;
public static final String TESTPROFILENAME = "someProfile";
public static CommandQueue queue;
public static ConfigBuilderPlugin configBuilderPlugin;
public static ProfileFunctions profileFunctions;
public static ConstraintChecker constraintChecker;
public static void mockStrings() {
Locale.setDefault(new Locale("en", "US"));
when(MainApp.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.");
when(MainApp.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences");
when(MainApp.gs(R.string.objectivenotstarted)).thenReturn("Objective %d not started");
when(MainApp.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump");
when(MainApp.gs(R.string.autosensdisabledinpreferences)).thenReturn("Autosens disabled in preferences");
when(MainApp.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences");
when(MainApp.gs(R.string.pumplimit)).thenReturn("pump limit");
when(MainApp.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value");
when(MainApp.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences");
when(MainApp.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier");
when(MainApp.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier");
when(MainApp.gs(R.string.pumplimit)).thenReturn("pump limit");
when(MainApp.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %.1f U because of %s");
when(MainApp.gs(R.string.hardlimit)).thenReturn("hard limit");
when(MainApp.gs(R.string.key_child)).thenReturn("child");
when(MainApp.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %d g because of %s");
when(MainApp.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %.1f U because of %s");
when(MainApp.gs(R.string.pumpisnottempbasalcapable)).thenReturn("Pump is not temp basal capable");
when(MainApp.gs(R.string.loop)).thenReturn("Loop");
when(MainApp.gs(R.string.loop_shortname)).thenReturn("LOOP");
when(MainApp.gs(R.string.smbalwaysdisabled)).thenReturn("SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering");
when(MainApp.gs(R.string.smbnotallowedinopenloopmode)).thenReturn("SMB not allowed in open loop mode");
when(MainApp.gs(R.string.Glimp)).thenReturn("Glimp");
when(MainApp.gs(R.string.glucose)).thenReturn("Glucose");
when(MainApp.gs(R.string.delta)).thenReturn("Delta");
when(MainApp.gs(R.string.short_avgdelta)).thenReturn("Short avg. delta");
when(MainApp.gs(R.string.long_avgdelta)).thenReturn("Long avg. delta");
when(MainApp.gs(R.string.zerovalueinprofile)).thenReturn("Invalid profile: %s");
when(MainApp.gs(R.string.success)).thenReturn("Success");
when(MainApp.gs(R.string.enacted)).thenReturn("Enacted");
when(MainApp.gs(R.string.comment)).thenReturn("Comment");
when(MainApp.gs(R.string.smb_shortname)).thenReturn("SMB");
when(MainApp.gs(R.string.canceltemp)).thenReturn("Cancel temp basal");
when(MainApp.gs(R.string.duration)).thenReturn("Duration");
when(MainApp.gs(R.string.percent)).thenReturn("Percent");
when(MainApp.gs(R.string.absolute)).thenReturn("Absolute");
when(MainApp.gs(R.string.waitingforpumpresult)).thenReturn("Waiting for result");
when(MainApp.gs(R.string.insulin_unit_shortname)).thenReturn("U");
when(MainApp.gs(R.string.minimalbasalvaluereplaced)).thenReturn("Basal value replaced by minimal supported value: %1$s");
when(MainApp.gs(R.string.basalprofilenotaligned)).thenReturn("Basal values not aligned to hours: %s");
when(MainApp.gs(R.string.minago)).thenReturn("%d min ago");
when(MainApp.gs(R.string.hoursago)).thenReturn("%.1fh ago");
when(MainApp.gs(R.string.careportal_profileswitch)).thenReturn("Profile Switch");
when(MainApp.gs(R.string.configbuilder_insulin)).thenReturn("Insulin");
when(MainApp.gs(R.string.bolusdelivering)).thenReturn("Delivering 0.0U");
when(MainApp.gs(R.string.profile_per_unit)).thenReturn("/U");
when(MainApp.gs(R.string.shortday)).thenReturn("d");
when(MainApp.gs(R.string.shorthour)).thenReturn("h");
when(MainApp.gs(R.string.profile_carbs_per_unit)).thenReturn("g/U");
when(MainApp.gs(R.string.profile_ins_units_per_hour)).thenReturn("U/h");
when(MainApp.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.");
when(MainApp.gs(R.string.sms_iob)).thenReturn("IOB:");
when(MainApp.gs(R.string.sms_lastbg)).thenReturn("Last BG:");
when(MainApp.gs(R.string.sms_minago)).thenReturn("%1$dmin ago");
when(MainApp.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed");
when(MainApp.gs(R.string.smscommunicator_stopsmswithcode)).thenReturn("To disable the SMS Remote Service reply with code %1$s.\\n\\nKeep in mind that you\\'ll able to reactivate it directly from the AAPS master smartphone only.");
when(MainApp.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2$s.");
when(MainApp.gs(R.string.smscommunicator_temptargetwithcode)).thenReturn("To set the Temp Target %1$s reply with code %2$s");
when(MainApp.gs(R.string.smscommunicator_temptargetcancel)).thenReturn("To cancel Temp Target reply with code %1$s");
when(MainApp.gs(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.");
when(MainApp.gs(R.string.smscommunicator_tt_set)).thenReturn("Target %1$s for %2$d minutes set successfully");
when(MainApp.gs(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully");
when(MainApp.gs(R.string.loopsuspendedfor)).thenReturn("Suspended (%1$d m)");
when(MainApp.gs(R.string.smscommunicator_loopisdisabled)).thenReturn("Loop is disabled");
when(MainApp.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled");
when(MainApp.gs(R.string.wrongformat)).thenReturn("Wrong format");
when(MainApp.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled");
when(MainApp.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled");
when(MainApp.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled");
when(MainApp.gs(R.string.smscommunicator_loopresumed)).thenReturn("Loop resumed");
when(MainApp.gs(R.string.smscommunicator_wrongduration)).thenReturn("Wrong duration");
when(MainApp.gs(R.string.smscommunicator_suspendreplywithcode)).thenReturn("To suspend loop for %1$d minutes reply with code %2$s");
when(MainApp.gs(R.string.smscommunicator_loopsuspended)).thenReturn("Loop suspended");
when(MainApp.gs(R.string.smscommunicator_unknowncommand)).thenReturn("Unknown command or wrong reply");
when(MainApp.gs(R.string.notconfigured)).thenReturn("Not configured");
when(MainApp.gs(R.string.smscommunicator_profilereplywithcode)).thenReturn("To switch profile to %1$s %2$d%% reply with code %3$s");
when(MainApp.gs(R.string.profileswitchcreated)).thenReturn("Profile switch created");
when(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode)).thenReturn("To stop temp basal reply with code %1$s");
when(MainApp.gs(R.string.smscommunicator_basalpctreplywithcode)).thenReturn("To start basal %1$d%% for %2$d min reply with code %3$s");
when(MainApp.gs(R.string.smscommunicator_tempbasalset_percent)).thenReturn("Temp basal %1$d%% for %2$d min started successfully");
when(MainApp.gs(R.string.smscommunicator_basalreplywithcode)).thenReturn("To start basal %1$.2fU/h for %2$d min reply with code %3$s");
when(MainApp.gs(R.string.smscommunicator_tempbasalset)).thenReturn("Temp basal %1$.2fU/h for %2$d min started successfully");
when(MainApp.gs(R.string.smscommunicator_extendedstopreplywithcode)).thenReturn("To stop extended bolus reply with code %1$s");
when(MainApp.gs(R.string.smscommunicator_extendedcanceled)).thenReturn("Extended bolus canceled");
when(MainApp.gs(R.string.smscommunicator_extendedreplywithcode)).thenReturn("To start extended bolus %1$.2fU for %2$d min reply with code %3$s");
when(MainApp.gs(R.string.smscommunicator_extendedset)).thenReturn("Extended bolus %1$.2fU for %2$d min started successfully");
when(MainApp.gs(R.string.smscommunicator_bolusreplywithcode)).thenReturn("To deliver bolus %1$.2fU reply with code %2$s");
when(MainApp.gs(R.string.smscommunicator_bolusdelivered)).thenReturn("Bolus %1$.2fU delivered successfully");
when(MainApp.gs(R.string.smscommunicator_remotebolusnotallowed)).thenReturn("Remote bolus not available. Try again later.");
when(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode)).thenReturn("To send calibration %1$.2f reply with code %2$s");
when(MainApp.gs(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip.");
when(MainApp.gs(R.string.pumpsuspended)).thenReturn("Pump suspended");
when(MainApp.gs(R.string.cob)).thenReturn("COB");
when(MainApp.gs(R.string.value_unavailable_short)).thenReturn("n/a");
when(MainApp.gs(R.string.starttemptarget)).thenReturn("Start temp target");
when(MainApp.gs(R.string.stoptemptarget)).thenReturn("Stop temp target");
when(MainApp.gs(R.string.disableloop)).thenReturn("Disable loop");
when(MainApp.gs(R.string.enableloop)).thenReturn("Enable loop");
when(MainApp.gs(R.string.resumeloop)).thenReturn("Resume loop");
when(MainApp.gs(R.string.suspendloop)).thenReturn("Suspend loop");
when(MainApp.gs(R.string.pumpNotInitialized)).thenReturn("Pump not initialized!");
when(MainApp.gs(R.string.increasingmaxbasal)).thenReturn("Increasing max basal value because setting is lower than your max basal in profile");
when(MainApp.gs(R.string.overview_bolusprogress_delivered)).thenReturn("Delivered");
when(MainApp.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2$s");
when(MainApp.gs(R.string.smscommunicator_mealbolusdelivered)).thenReturn("Meal Bolus %1$.2fU delivered successfully");
when(MainApp.gs(R.string.smscommunicator_mealbolusdelivered_tt)).thenReturn("Target %1$s for %2$d minutes");
when(MainApp.gs(R.string.smscommunicator_carbsreplywithcode)).thenReturn("To enter %1$dg at %2$s reply with code %3$s");
when(MainApp.gs(R.string.smscommunicator_carbsset)).thenReturn("Carbs %1$dg entered successfully");
}
public static MainApp mockMainApp() {
System.setProperty("disableFirebase", "true");
PowerMockito.mockStatic(MainApp.class);
MainApp mainApp = mock(MainApp.class);
when(MainApp.instance()).thenReturn(mainApp);
return mainApp;
}
public static void mockConfigBuilder() {
PowerMockito.mockStatic(ConfigBuilderPlugin.class);
configBuilderPlugin = mock(ConfigBuilderPlugin.class);
when(ConfigBuilderPlugin.getPlugin()).thenReturn(configBuilderPlugin);
}
public static void mockSP() {
PowerMockito.mockStatic(SP.class);
when(SP.getLong(anyInt(), anyLong())).thenReturn(0L);
when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false);
when(SP.getInt(anyInt(), anyInt())).thenReturn(0);
when(SP.getString(anyInt(), anyString())).thenReturn("");
}
public static void mockL() {
PowerMockito.mockStatic(L.class);
when(L.isEnabled(any())).thenReturn(true);
}
public static void mockNSUpload() {
PowerMockito.mockStatic(NSUpload.class);
}
public static void mockApplicationContext() {
Context mockedContext = mock(Context.class);
Resources mResources = mock(Resources.class);
when(MainApp.instance().getApplicationContext()).thenReturn(mockedContext);
when(mockedContext.getResources()).thenReturn(mResources);
PackageManager packageManager = mock(PackageManager.class);
when(mockedContext.getPackageManager()).thenReturn(packageManager);
}
public static DatabaseHelper mockDatabaseHelper() {
DatabaseHelper databaseHelper = mock(DatabaseHelper.class);
when(MainApp.getDbHelper()).thenReturn(databaseHelper);
return databaseHelper;
}
public static void mockCommandQueue() {
queue = mock(CommandQueue.class);
when(ConfigBuilderPlugin.getPlugin().getCommandQueue()).thenReturn(queue);
}
public static TreatmentsPlugin mockTreatmentPlugin() {
PowerMockito.mockStatic(TreatmentsPlugin.class);
TreatmentsPlugin treatmentsPlugin = PowerMockito.mock(TreatmentsPlugin.class);
when(TreatmentsPlugin.getPlugin()).thenReturn(treatmentsPlugin);
when(treatmentsPlugin.getLastCalculationTreatments()).thenReturn(new IobTotal(0));
when(treatmentsPlugin.getLastCalculationTempBasals()).thenReturn(new IobTotal(0));
TreatmentService treatmentService = PowerMockito.mock(TreatmentService.class);
when(treatmentsPlugin.getService()).thenReturn(treatmentService);
return treatmentsPlugin;
}
public static void mockTreatmentService() {
TreatmentService treatmentService = PowerMockito.mock(TreatmentService.class);
try {
PowerMockito.whenNew(TreatmentService.class).withNoArguments().thenReturn(treatmentService);
} catch (Exception e) {
}
}
/*
public static Profile getValidProfile() {
try {
if (profile == null)
profile = new Profile(new JSONObject(validProfile), Constants.MGDL);
} catch (JSONException ignored) {
}
return profile;
}
public static ProfileStore getValidProfileStore() {
try {
if (profileStore == null) {
JSONObject json = new JSONObject();
JSONObject store = new JSONObject();
JSONObject profile = new JSONObject(validProfile);
json.put("defaultProfile", TESTPROFILENAME);
json.put("store", store);
store.put(TESTPROFILENAME, profile);
profileStore = new ProfileStore(json);
}
} catch (JSONException ignored) {
Assert.fail("getValidProfileStore() failed");
}
return profileStore;
}
public static void mockProfileFunctions() {
PowerMockito.mockStatic(ProfileFunctions.class);
profileFunctions = PowerMockito.mock(ProfileFunctions.class);
PowerMockito.when(ProfileFunctions.getSystemUnits()).thenReturn(Constants.MGDL);
PowerMockito.when(ProfileFunctions.getInstance()).thenReturn(profileFunctions);
profile = getValidProfile();
PowerMockito.when(ProfileFunctions.getInstance().getProfile()).thenReturn(profile);
PowerMockito.when(ProfileFunctions.getInstance().getProfileName()).thenReturn(TESTPROFILENAME);
}
*/
public static IobCobCalculatorPlugin mockIobCobCalculatorPlugin() {
PowerMockito.mockStatic(IobCobCalculatorPlugin.class);
IobCobCalculatorPlugin iobCobCalculatorPlugin = PowerMockito.mock(IobCobCalculatorPlugin.class);
PowerMockito.when(IobCobCalculatorPlugin.getPlugin()).thenReturn(iobCobCalculatorPlugin);
Object dataLock = new Object();
PowerMockito.when(iobCobCalculatorPlugin.getDataLock()).thenReturn(dataLock);
return iobCobCalculatorPlugin;
}
}

View file

@ -1,223 +0,0 @@
package info;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.SparseArray;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyByte;
import static org.mockito.Matchers.anyChar;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
public final class BundleMock {
public static Bundle mock() {
return mock(new HashMap<String, Object>());
}
public static Bundle mock(final HashMap<String, Object> map) {
Answer unsupported = new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
throw new UnsupportedOperationException();
}
};
Answer put = new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
map.put((String)invocation.getArguments()[0], invocation.getArguments()[1]);
return null;
}
};
Answer<Object> get = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.get(invocation.getArguments()[0]);
}
};
Answer<Object> getOrDefault = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object key = invocation.getArguments()[0];
return map.containsKey(key) ? map.get(key) : invocation.getArguments()[1];
}
};
Bundle bundle = Mockito.mock(Bundle.class);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.size();
}
}).when(bundle).size();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.isEmpty();
}
}).when(bundle).isEmpty();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
map.clear();
return null;
}
}).when(bundle).clear();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.containsKey(invocation.getArguments()[0]);
}
}).when(bundle).containsKey(anyString());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.get(invocation.getArguments()[0]);
}
}).when(bundle).get(anyString());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
map.remove(invocation.getArguments()[0]);
return null;
}
}).when(bundle).remove(anyString());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return map.keySet();
}
}).when(bundle).keySet();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return BundleMock.class.getSimpleName() + "{map=" + map.toString() + "}";
}
}).when(bundle).toString();
doAnswer(put).when(bundle).putBoolean(anyString(), anyBoolean());
when(bundle.getBoolean(anyString())).thenAnswer(get);
when(bundle.getBoolean(anyString(), anyBoolean())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putByte(anyString(), anyByte());
when(bundle.getByte(anyString())).thenAnswer(get);
when(bundle.getByte(anyString(), anyByte())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putChar(anyString(), anyChar());
when(bundle.getChar(anyString())).thenAnswer(get);
when(bundle.getChar(anyString(), anyChar())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putInt(anyString(), anyShort());
when(bundle.getShort(anyString())).thenAnswer(get);
when(bundle.getShort(anyString(), anyShort())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putLong(anyString(), anyLong());
when(bundle.getLong(anyString())).thenAnswer(get);
when(bundle.getLong(anyString(), anyLong())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putFloat(anyString(), anyFloat());
when(bundle.getFloat(anyString())).thenAnswer(get);
when(bundle.getFloat(anyString(), anyFloat())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putDouble(anyString(), anyDouble());
when(bundle.getDouble(anyString())).thenAnswer(get);
when(bundle.getDouble(anyString(), anyDouble())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putString(anyString(), anyString());
when(bundle.getString(anyString())).thenAnswer(get);
when(bundle.getString(anyString(), anyString())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putBooleanArray(anyString(), any(boolean[].class));
when(bundle.getBooleanArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putLongArray(anyString(), any(long[].class));
when(bundle.getLongArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putDoubleArray(anyString(), any(double[].class));
when(bundle.getDoubleArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putIntArray(anyString(), any(int[].class));
when(bundle.getIntArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putInt(anyString(), anyInt());
when(bundle.getInt(anyString())).thenAnswer(get);
when(bundle.getInt(anyString(), anyInt())).thenAnswer(getOrDefault);
doAnswer(unsupported).when(bundle).putAll(any(Bundle.class));
when(bundle.hasFileDescriptors()).thenAnswer(unsupported);
doAnswer(put).when(bundle).putShort(anyString(), anyShort());
when(bundle.getShort(anyString())).thenAnswer(get);
when(bundle.getShort(anyString(), anyShort())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putFloat(anyString(), anyFloat());
when(bundle.getFloat(anyString())).thenAnswer(get);
when(bundle.getFloat(anyString(), anyFloat())).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putCharSequence(anyString(), any(CharSequence.class));
when(bundle.getCharSequence(anyString())).thenAnswer(get);
when(bundle.getCharSequence(anyString(), any(CharSequence.class))).thenAnswer(getOrDefault);
doAnswer(put).when(bundle).putBundle(anyString(), any(Bundle.class));
when(bundle.getBundle(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putParcelable(anyString(), any(Parcelable.class));
when(bundle.getParcelable(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putParcelableArray(anyString(), any(Parcelable[].class));
when(bundle.getParcelableArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putParcelableArrayList(anyString(), any(ArrayList.class));
when(bundle.getParcelableArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putSparseParcelableArray(anyString(), any(SparseArray.class));
when(bundle.getSparseParcelableArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putSerializable(anyString(), any(Serializable.class));
when(bundle.getSerializable(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putIntegerArrayList(anyString(), any(ArrayList.class));
when(bundle.getIntegerArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putStringArrayList(anyString(), any(ArrayList.class));
when(bundle.getStringArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putCharSequenceArrayList(anyString(), any(ArrayList.class));
when(bundle.getCharSequenceArrayList(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putCharArray(anyString(), any(char[].class));
when(bundle.getCharArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putByteArray(anyString(), any(byte[].class));
when(bundle.getByteArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putShortArray(anyString(), any(short[].class));
when(bundle.getShortArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putFloatArray(anyString(), any(float[].class));
when(bundle.getFloatArray(anyString())).thenAnswer(get);
doAnswer(put).when(bundle).putCharSequenceArray(anyString(), any(CharSequence[].class));
when(bundle.getCharSequenceArray(anyString())).thenAnswer(get);
return bundle;
}
}

View file

@ -1,68 +0,0 @@
package info;
import org.junit.Assert;
import org.mockito.ArgumentMatchers;
import org.powermock.api.mockito.PowerMockito;
import java.util.HashMap;
import info.nightscout.androidaps.utils.SP;
public class SPMocker {
static HashMap<String, Object> data = new HashMap<>();
public static void prepareMock() {
PowerMockito.mockStatic(SP.class);
try {
PowerMockito.when(SP.class, "putString", ArgumentMatchers.anyString(), ArgumentMatchers.anyString()).then(invocation -> {
String key = invocation.getArgument(0);
String value = invocation.getArgument(1);
data.put(key, value);
System.out.print("putString " + key + " " + value + "\n");
return null;
});
PowerMockito.when(SP.class, "getString", ArgumentMatchers.anyString(), ArgumentMatchers.any()).then(invocation -> {
String key = invocation.getArgument(0);
String def = invocation.getArgument(1);
String value = (String) data.get(key);
if (value == null) value = def;
System.out.print("getString " + key + " " + value + "\n");
return value;
});
PowerMockito.when(SP.class, "putBoolean", ArgumentMatchers.anyString(), ArgumentMatchers.anyBoolean()).then(invocation -> {
String key = invocation.getArgument(0);
Boolean value = invocation.getArgument(1);
data.put(key, value);
System.out.print("putBoolean " + key + " " + value + "\n");
return null;
});
PowerMockito.when(SP.class, "getBoolean", ArgumentMatchers.anyString(), ArgumentMatchers.any()).then(invocation -> {
String key = invocation.getArgument(0);
Boolean def = invocation.getArgument(1);
Boolean value = (Boolean) data.get(key);
if (value == null) value = def;
System.out.print("getBoolean " + key + " " + value + "\n");
return value;
});
PowerMockito.when(SP.class, "getDouble", ArgumentMatchers.anyString(), ArgumentMatchers.any()).then(invocation -> {
String key = invocation.getArgument(0);
Double def = invocation.getArgument(1);
Double value = (Double) data.get(key);
if (value == null) value = def;
System.out.print("getDouble " + key + " " + value + "\n");
return value;
});
} catch (Exception e) {
Assert.fail("Unable to mock the construction of the SP object: " + e.getMessage());
}
}
}

View file

@ -35,6 +35,7 @@ open class TestBase {
@Before @Before
fun setupLocale() { fun setupLocale() {
Locale.setDefault(Locale.ENGLISH) Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
} }
// Workaround for Kotlin nullability. // Workaround for Kotlin nullability.

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.db
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.AAPSMocker
import info.TestBase import info.TestBase
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
@ -21,6 +20,7 @@ import org.mockito.ArgumentMatchers
import org.mockito.Mock import org.mockito.Mock
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
import java.util.* import java.util.*
@ -48,7 +48,7 @@ class BgReadingTest : TestBase() {
@Test @Test
fun valueToUnits() { fun valueToUnits() {
val bgReading = BgReading() val bgReading = BgReading(injector)
bgReading.value = 18.0 bgReading.value = 18.0
Assert.assertEquals(18.0, bgReading.valueToUnits(Constants.MGDL) * 1, 0.01) Assert.assertEquals(18.0, bgReading.valueToUnits(Constants.MGDL) * 1, 0.01)
Assert.assertEquals(1.0, bgReading.valueToUnits(Constants.MMOL) * 1, 0.01) Assert.assertEquals(1.0, bgReading.valueToUnits(Constants.MMOL) * 1, 0.01)
@ -56,7 +56,7 @@ class BgReadingTest : TestBase() {
@Test @Test
fun directionToSymbol() { fun directionToSymbol() {
val bgReading = BgReading() val bgReading = BgReading(injector)
bgReading.direction = "DoubleDown" bgReading.direction = "DoubleDown"
Assert.assertEquals("\u21ca", bgReading.directionToSymbol()) Assert.assertEquals("\u21ca", bgReading.directionToSymbol())
bgReading.direction = "SingleDown" bgReading.direction = "SingleDown"
@ -76,7 +76,7 @@ class BgReadingTest : TestBase() {
} }
@Test fun dateTest() { @Test fun dateTest() {
val bgReading = BgReading() val bgReading = BgReading(injector)
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
bgReading.date = now bgReading.date = now
val nowDate = Date(now) val nowDate = Date(now)
@ -85,14 +85,17 @@ class BgReadingTest : TestBase() {
} }
@Test fun valueTest() { @Test fun valueTest() {
val bgReading = BgReading() val bgReading = BgReading(injector)
val valueToSet = 81.0 // 4.5 mmol val valueToSet = 81.0 // 4.5 mmol
Assert.assertEquals(81.0, bgReading.value(valueToSet).value, 0.01) Assert.assertEquals(81.0, bgReading.value(valueToSet).value, 0.01)
} }
@Test fun copyFromTest() { @Test fun copyFromTest() {
val bgReading = BgReading() val databaseHelper = Mockito.mock(DatabaseHelper::class.java)
val copy = BgReading() `when`(MainApp.getDbHelper()).thenReturn(databaseHelper)
setReadings(72, 0)
val bgReading = BgReading(injector)
val copy = BgReading(injector)
bgReading.value = 81.0 bgReading.value = 81.0
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
bgReading.date = now bgReading.date = now
@ -105,21 +108,22 @@ class BgReadingTest : TestBase() {
@Test @Test
fun isEqualTest() { fun isEqualTest() {
val bgReading = BgReading() val bgReading = BgReading(injector)
val copy = BgReading() val copy = BgReading(injector)
bgReading.value = 81.0 bgReading.value = 81.0
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
bgReading.date = now bgReading.date = now
copy.date = now copy.date = now
copy.copyFrom(bgReading) copy.copyFrom(bgReading)
Assert.assertTrue(copy.isEqual(bgReading)) Assert.assertTrue(copy.isEqual(bgReading))
Assert.assertFalse(copy.isEqual(BgReading())) Assert.assertFalse(copy.isEqual(BgReading(injector)))
} }
@Test fun calculateDirection() { @Test fun calculateDirection() {
val bgReading = BgReading() val bgReading = BgReading(injector)
val bgReadingsList: List<BgReading>? = null val bgReadingsList: List<BgReading>? = null
AAPSMocker.mockDatabaseHelper() val databaseHelper = Mockito.mock(DatabaseHelper::class.java)
`when`(MainApp.getDbHelper()).thenReturn(databaseHelper)
`when`(MainApp.getDbHelper().getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadingsList) `when`(MainApp.getDbHelper().getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadingsList)
Assert.assertEquals("NONE", bgReading.calculateDirection()) Assert.assertEquals("NONE", bgReading.calculateDirection())
setReadings(72, 0) setReadings(72, 0)
@ -140,19 +144,19 @@ class BgReadingTest : TestBase() {
@Before @Before
fun prepareMock() { fun prepareMock() {
val mainApp = AAPSMocker.mockMainApp() val mainApp = PowerMockito.mockStatic(MainApp::class.java)
AAPSMocker.mockApplicationContext() // AAPSMocker.mockApplicationContext()
AAPSMocker.mockSP() // AAPSMocker.mockSP()
AAPSMocker.mockL() // AAPSMocker.mockL()
AAPSMocker.mockDatabaseHelper() // AAPSMocker.mockDatabaseHelper()
`when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) // `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector())
} }
fun setReadings(current_value: Int, previous_value: Int) { fun setReadings(current_value: Int, previous_value: Int) {
val now = BgReading() val now = BgReading(injector)
now.value = current_value.toDouble() now.value = current_value.toDouble()
now.date = System.currentTimeMillis() now.date = System.currentTimeMillis()
val previous = BgReading() val previous = BgReading(injector)
previous.value = previous_value.toDouble() previous.value = previous_value.toDouble()
previous.date = System.currentTimeMillis() - 6 * 60 * 1000L previous.date = System.currentTimeMillis() - 6 * 60 * 1000L
val bgReadings: MutableList<BgReading> = mutableListOf() val bgReadings: MutableList<BgReading> = mutableListOf()

View file

@ -49,7 +49,7 @@ class APSResultTest : TestBase() {
it.aapsLogger = aapsLogger it.aapsLogger = aapsLogger
it.constraintChecker = constraintChecker it.constraintChecker = constraintChecker
it.sp = sp it.sp = sp
it.activePluginProvider = activePluginProvider it.activePlugin = activePluginProvider
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsPlugin
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
@ -170,7 +170,7 @@ class APSResultTest : TestBase() {
it.aapsLogger = aapsLogger it.aapsLogger = aapsLogger
it.constraintChecker = constraintChecker it.constraintChecker = constraintChecker
it.sp = sp it.sp = sp
it.activePluginProvider = activePluginProvider it.activePlugin = activePluginProvider
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsPlugin
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
@ -187,7 +187,7 @@ class APSResultTest : TestBase() {
it.aapsLogger = aapsLogger it.aapsLogger = aapsLogger
it.constraintChecker = constraintChecker it.constraintChecker = constraintChecker
it.sp = sp it.sp = sp
it.activePluginProvider = activePluginProvider it.activePlugin = activePluginProvider
it.treatmentsPlugin = treatmentsPlugin it.treatmentsPlugin = treatmentsPlugin
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper

View file

@ -8,12 +8,8 @@ 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
import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
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
@ -25,21 +21,17 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(NSProfilePlugin::class)
class ConfigBuilderPluginTest : TestBase() { class ConfigBuilderPluginTest : TestBase() {
@Mock lateinit var insulinOrefRapidActingPlugin: Lazy<InsulinOrefRapidActingPlugin>
@Mock lateinit var localProfilePlugin: Lazy<LocalProfilePlugin>
@Mock lateinit var virtualPumpPlugin: Lazy<VirtualPumpPlugin> @Mock lateinit var virtualPumpPlugin: Lazy<VirtualPumpPlugin>
@Mock lateinit var treatmentsPlugin: Lazy<TreatmentsPlugin> @Mock lateinit var treatmentsPlugin: Lazy<TreatmentsPlugin>
@Mock lateinit var sensitivityOref0Plugin: Lazy<SensitivityOref0Plugin>
@Mock lateinit var sensitivityOref1Plugin: Lazy<SensitivityOref1Plugin>
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@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 activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var profileFunction: ProfileFunction
lateinit var configBuilderPlugin: ConfigBuilderPlugin lateinit var configBuilderPlugin: ConfigBuilderPlugin
@ -56,6 +48,6 @@ class ConfigBuilderPluginTest : TestBase() {
@Before @Before
fun prepareMock() { fun prepareMock() {
configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, commandQueue) configBuilderPlugin = ConfigBuilderPlugin(activePlugin, injector, sp, RxBusWrapper(), aapsLogger, resourceHelper, profileFunction)
} }
} }

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.general.automation.actions package info.nightscout.androidaps.plugins.general.automation.actions
import info.AAPSMocker
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
@ -13,6 +12,7 @@ import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@ -24,7 +24,7 @@ class ActionStartTempTargetTest : ActionsTestBase() {
@Before @Before
fun setup() { fun setup() {
AAPSMocker.mockMainApp() PowerMockito.mockStatic(MainApp::class.java)
`when`(resourceHelper.gs(R.string.starttemptarget)).thenReturn("Start temp target") `when`(resourceHelper.gs(R.string.starttemptarget)).thenReturn("Start temp target")
sut = ActionStartTempTarget(injector) sut = ActionStartTempTarget(injector)

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.general.automation.actions package info.nightscout.androidaps.plugins.general.automation.actions
import info.AAPSMocker
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
@ -21,7 +20,6 @@ class ActionStopTempTargetTest : ActionsTestBase() {
@Before @Before
fun setup() { fun setup() {
AAPSMocker.mockMainApp()
`when`(resourceHelper.gs(R.string.stoptemptarget)).thenReturn("Stop temp target") `when`(resourceHelper.gs(R.string.stoptemptarget)).thenReturn("Stop temp target")
sut = ActionStopTempTarget(injector) sut = ActionStopTempTarget(injector)

View file

@ -1,18 +1,15 @@
package info.nightscout.androidaps.plugins.general.automation.elements package info.nightscout.androidaps.plugins.general.automation.elements
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase
import org.junit.Assert import org.junit.Assert
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class)
class InputBgTest : TriggerTestBase() { class InputBgTest : TriggerTestBase() {
@Test @Test

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
@ -20,7 +19,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class, IobCobCalculatorPlugin::class) @PrepareForTest(DateUtil::class, IobCobCalculatorPlugin::class)
class TriggerAutosensValueTest : TriggerTestBase() { class TriggerAutosensValueTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
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
@ -18,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class, TreatmentsPlugin::class) @PrepareForTest(DateUtil::class, TreatmentsPlugin::class)
class TriggerBolusAgoTest : TriggerTestBase() { class TriggerBolusAgoTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import android.location.Location import android.location.Location
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.InputLocationMode import info.nightscout.androidaps.plugins.general.automation.elements.InputLocationMode
import info.nightscout.androidaps.services.LocationService import info.nightscout.androidaps.services.LocationService
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -19,7 +18,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class, LocationService::class) @PrepareForTest(DateUtil::class, LocationService::class)
class TriggerLocationTest : TriggerTestBase() { class TriggerLocationTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L
@ -30,7 +29,6 @@ class TriggerLocationTest : TriggerTestBase() {
`when`(DateUtil.now()).thenReturn(now) `when`(DateUtil.now()).thenReturn(now)
PowerMockito.spy(LocationService::class.java) PowerMockito.spy(LocationService::class.java)
`when`(locationDataContainer.lastLocation).thenReturn(mockedLocation()) `when`(locationDataContainer.lastLocation).thenReturn(mockedLocation())
// MockitoAnnotations.initMocks(this)
} }
@Test fun copyConstructorTest() { @Test fun copyConstructorTest() {

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONException import org.json.JSONException
@ -17,7 +16,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class) @PrepareForTest(DateUtil::class)
class TriggerProfilePercentTest : TriggerTestBase() { class TriggerProfilePercentTest : TriggerTestBase() {
private val now = 1514766900000L private val now = 1514766900000L

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -17,7 +16,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class, VirtualPumpPlugin::class) @PrepareForTest(DateUtil::class, VirtualPumpPlugin::class)
class TriggerPumpLastConnectionTest : TriggerTestBase() { class TriggerPumpLastConnectionTest : TriggerTestBase() {
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional import com.google.common.base.Optional
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.db.TempTarget
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists
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
@ -18,7 +17,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ProfileFunctions::class, DateUtil::class, TreatmentsPlugin::class) @PrepareForTest(DateUtil::class, TreatmentsPlugin::class)
class TriggerTempTargetTest : TriggerTestBase() { class TriggerTempTargetTest : TriggerTestBase() {
var now = 1514766900000L var now = 1514766900000L

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator
import android.telephony.SmsManager import android.telephony.SmsManager
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.AAPSMocker
import info.TestBase import info.TestBase
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
@ -53,7 +52,6 @@ import java.util.*
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class, SmsManager::class, RxBusWrapper::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class, IobCobCalculatorPlugin::class, MainApp::class) @PrepareForTest(ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class, SmsManager::class, RxBusWrapper::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class, IobCobCalculatorPlugin::class, MainApp::class)
//@PrepareForTest(L::class, SP::class, resourceHelper::class, DateUtil::class, ProfileFunctions::class, TreatmentsPlugin::class, IobCobCalculatorPlugin::class, CommandQueue::class, ConfigBuilderPlugin::class, NSUpload::class, ProfileInterface::class, LocalProfilePlugin::class, VirtualPumpPlugin::class, LoopPlugin::class)
class SmsCommunicatorPluginTest : TestBase() { class SmsCommunicatorPluginTest : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var aapsLogger: AAPSLogger
@ -101,11 +99,8 @@ class SmsCommunicatorPluginTest : TestBase() {
private var hasBeenRun = false private var hasBeenRun = false
@Before fun prepareTests() { @Before fun prepareTests() {
val mainApp = AAPSMocker.mockMainApp()
`when`(mainApp.androidInjector()).thenReturn(injector.androidInjector())
rxBus = RxBusWrapper() rxBus = RxBusWrapper()
val reading = BgReading() val reading = BgReading(injector)
reading.value = 100.0 reading.value = 100.0
val bgList: MutableList<BgReading> = ArrayList() val bgList: MutableList<BgReading> = ArrayList()
bgList.add(reading) bgList.add(reading)

View file

@ -1,19 +1,10 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm package info.nightscout.androidaps.plugins.pump.danaRS.comm
import info.AAPSMocker
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert import org.junit.Assert
import org.junit.Before
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.Mock
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner

View file

@ -7,8 +7,6 @@ import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import info.AAPSMocker;
import info.SPMocker;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus;
@ -29,11 +27,11 @@ public class BasalProfileUTest {
// MainApp mainApp = new MainApp(); // MainApp mainApp = new MainApp();
@Before @Before
public void initMocking() { public void initMocking() {
AAPSMocker.mockMainApp(); // AAPSMocker.mockMainApp();
AAPSMocker.mockStrings(); // AAPSMocker.mockStrings();
AAPSMocker.mockDatabaseHelper(); // AAPSMocker.mockDatabaseHelper();
SPMocker.prepareMock(); // SPMocker.prepareMock();
PowerMockito.mockStatic(DateUtil.class); PowerMockito.mockStatic(DateUtil.class);
when(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()); when(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs());

View file

@ -1,97 +0,0 @@
package info.nightscout.androidaps.utils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Date;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by mike on 20.11.2017.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({MainApp.class})
public class DateUtilTest {
@Test
public void fromISODateStringTest() throws Exception {
assertEquals(1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").getTime());
assertEquals(1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").getTime());
assertEquals(1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").getTime());
assertEquals(1513902750000L, DateUtil.fromISODateString("2017-12-22T00:32:30Z").getTime());
}
@Test
public void toISOStringTest() throws Exception {
assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(new Date(1513902750000L)));
assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(1513902750000L));
}
@Test
public void toDateTest() {
assertTrue(DateUtil.toDate((int) (T.hours(1).secs() + T.mins(1).secs() + 1)).toString().contains("01:01:00"));
}
@Test
public void toSecondsTest() {
Assert.assertEquals(3600, DateUtil.toSeconds("01:00"));
Assert.assertEquals(3600, DateUtil.toSeconds("01:00 a.m."));
Assert.assertEquals(3600, DateUtil.toSeconds("01:00 AM"));
}
@Test
public void dateStringTest() {
assertTrue(DateUtil.dateString(new Date(1513902750000L)).contains("22"));
assertTrue(DateUtil.dateString(1513902750000L).contains("22"));
}
@Test
public void timeStringTest() {
assertTrue(DateUtil.timeString(new Date(1513902750000L)).contains("32"));
assertTrue(DateUtil.timeString(1513902750000L).contains("32"));
}
@Test
public void dateAndTimeStringTest() {
assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("22"));
assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("32"));
assertTrue(DateUtil.dateAndTimeString(new Date(1513902750000L)).contains("22"));
assertTrue(DateUtil.dateAndTimeString(new Date(1513902750000L)).contains("32"));
}
@Test
public void dateAndTimeRangeStringTest() {
assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22"));
assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32"));
assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22"));
assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32"));
}
/*
@Test
public void timeStringFromSecondsTest() {
Assert.assertEquals("1:00 AM", DateUtil.timeStringFromSeconds((int) T.hours(1).secs()));
}
*/
@Test
public void timeFrameStringTest() {
Assert.assertEquals("(1h 1')", DateUtil.timeFrameString((T.hours(1).msecs() + T.mins(1).msecs())));
}
@Before
public void prepareMock() {
AAPSMocker.mockMainApp();
AAPSMocker.mockStrings();
}
}

View file

@ -0,0 +1,77 @@
package info.nightscout.androidaps.utils
import info.TestBase
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
@RunWith(PowerMockRunner::class)
class DateUtilTest : TestBase() {
@Mock lateinit var resourceHelper: ResourceHelper
@Test
fun fromISODateStringTest() {
Assert.assertEquals(1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").time)
Assert.assertEquals(1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").time)
Assert.assertEquals(1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").time)
Assert.assertEquals(1513902750000L, DateUtil.fromISODateString("2017-12-22T00:32:30Z").time)
}
@Test
fun toISOStringTest() {
Assert.assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(Date(1513902750000L)))
Assert.assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(1513902750000L))
}
@Test fun toDateTest() {
Assert.assertTrue(DateUtil.toDate((T.hours(1).secs() + T.mins(1).secs() + 1).toInt()).toString().contains("01:01:00"))
}
@Test fun toSecondsTest() {
Assert.assertEquals(3600, DateUtil.toSeconds("01:00").toLong())
Assert.assertEquals(3600, DateUtil.toSeconds("01:00 a.m.").toLong())
Assert.assertEquals(3600, DateUtil.toSeconds("01:00 AM").toLong())
}
@Test fun dateStringTest() {
Assert.assertTrue(DateUtil.dateString(Date(1513902750000L)).contains("22"))
Assert.assertTrue(DateUtil.dateString(1513902750000L).contains("22"))
}
@Test fun timeStringTest() {
Assert.assertTrue(DateUtil.timeString(Date(1513902750000L)).contains("32"))
Assert.assertTrue(DateUtil.timeString(1513902750000L).contains("32"))
}
@Test fun dateAndTimeStringTest() {
Assert.assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("22"))
Assert.assertTrue(DateUtil.dateAndTimeString(1513902750000L).contains("32"))
Assert.assertTrue(DateUtil.dateAndTimeString(Date(1513902750000L)).contains("22"))
Assert.assertTrue(DateUtil.dateAndTimeString(Date(1513902750000L)).contains("32"))
}
@Test fun dateAndTimeRangeStringTest() {
Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22"))
Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32"))
Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("22"))
Assert.assertTrue(DateUtil.dateAndTimeRangeString(1513902750000L, 1513902750000L).contains("32"))
}
/*
@Test
public void timeStringFromSecondsTest() {
Assert.assertEquals("1:00 AM", DateUtil.timeStringFromSeconds((int) T.hours(1).secs()));
}
*/
@Test fun timeFrameStringTest() {
`when`(resourceHelper.gs(R.string.shorthour)).thenReturn("h")
Assert.assertEquals("(1h 1')", DateUtil.timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), resourceHelper))
}
}

View file

@ -1,17 +1,11 @@
package info.nightscout.androidaps.utils; package info.nightscout.androidaps.utils;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({MainApp.class})
public class DecimalFormatterTest { public class DecimalFormatterTest {
@Test @Test
@ -45,10 +39,4 @@ public class DecimalFormatterTest {
@Test @Test
public void pumpSupportedBolusFormat() { public void pumpSupportedBolusFormat() {
} }
@Before
public void prepareMock() {
AAPSMocker.mockMainApp();
AAPSMocker.mockStrings();
}
} }

View file

@ -2,20 +2,12 @@ package info.nightscout.androidaps.utils;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** /**
* Created by mike on 20.11.2017. * Created by mike on 20.11.2017.
@ -60,6 +52,7 @@ public class MidnightTimeTest {
MidnightTime.resetCache(); MidnightTime.resetCache();
Assert.assertEquals(0, MidnightTime.times.size()); Assert.assertEquals(0, MidnightTime.times.size());
} }
@Test @Test
public void log() { public void log() {
long now = DateUtil.now(); long now = DateUtil.now();