diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index d1906dc828..37152b086f 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -33,6 +33,7 @@ import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; @@ -132,6 +133,7 @@ public class MainApp extends DaggerApplication { private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger) private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger) + @Inject public HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @Inject ActivityMonitor activityMonitor; @Inject FabricPrivacy fabricPrivacy; diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 5ef5d8f6a0..1c603d54aa 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin @@ -60,6 +61,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var sp: SP + @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var danaRPlugin: DanaRPlugin @@ -235,7 +237,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang ) if (listOf(*unitDependent).contains(pref.key)) { val editTextPref = pref as EditTextPreference - val converted = Profile.toCurrentUnitsString(SafeParse.stringToDouble(editTextPref.text)) + val converted = Profile.toCurrentUnitsString(profileFunction, SafeParse.stringToDouble(editTextPref.text)) editTextPref.summary = converted editTextPref.text = converted } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt index 7ccbe7dcf7..2a5e8bcecd 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -30,6 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { @Inject lateinit var tirCalculator: TirCalculator @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activityMonitor: ActivityMonitor + @Inject lateinit var defaultProfile: DefaultProfile override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -61,7 +62,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { ToastUtils.showToastInUiThread(this, R.string.invalidweight) return@setOnClickListener } - val profile = DefaultProfile().profile(age, tdd, weight, profileFunction.getUnits()) + val profile = defaultProfile.profile(age, tdd, weight, profileFunction.getUnits()) val args = Bundle() args.putLong("time", DateUtil.now()) args.putInt("mode", ProfileViewerDialog.Mode.CUSTOM_PROFILE.ordinal) diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index 2e116c4a0e..aeebc9b46e 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -5,31 +5,37 @@ import androidx.collection.LongSparseArray; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.text.DecimalFormat; import java.util.TimeZone; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.MidnightTime; +import info.nightscout.androidaps.utils.resources.ResourceHelper; public class Profile { - private static Logger log = StacktraceLoggerWrapper.getLogger(Profile.class); + @Inject AAPSLogger aapsLogger; + @Inject ActivePluginProvider activePlugin; + @Inject ResourceHelper resourceHelper; + @Inject RxBusWrapper rxBus; + + private HasAndroidInjector injector; private JSONObject json; private String units; @@ -52,8 +58,9 @@ public class Profile { protected boolean isValid; protected boolean isValidated; - // Default constructor for tests - protected Profile() { + protected Profile(HasAndroidInjector injector) { + injector.androidInjector().inject(this); + this.injector = injector; } @Override @@ -65,7 +72,8 @@ public class Profile { } // Constructor from profileStore JSON - public Profile(JSONObject json, String units) { + public Profile(HasAndroidInjector injector, JSONObject json, String units) { + this(injector); init(json, 100, 0); if (this.units == null) { if (units != null) @@ -78,11 +86,13 @@ public class Profile { } // Constructor from profileStore JSON - public Profile(JSONObject json) { + public Profile(HasAndroidInjector injector, JSONObject json) { + this(injector); init(json, 100, 0); } - public Profile(JSONObject json, int percentage, int timeshift) { + public Profile(HasAndroidInjector injector, JSONObject json, int percentage, int timeshift) { + this(injector); init(json, percentage, timeshift); } @@ -115,7 +125,7 @@ public class Profile { targetLow = json.getJSONArray("target_low"); targetHigh = json.getJSONArray("target_high"); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); isValid = false; isValidated = true; } @@ -136,7 +146,7 @@ public class Profile { try { json.put("units", units); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return json; } @@ -181,8 +191,8 @@ public class Profile { double value = o.getDouble("value") * multiplier; sparse.put(tas, value); } catch (Exception e) { - log.error("Unhandled exception", e); - log.error(json.toString()); + aapsLogger.error("Unhandled exception", e); + aapsLogger.error(json.toString()); FabricPrivacy.getInstance().logException(e); } } @@ -229,14 +239,14 @@ public class Profile { if (isValid) { // Check for hours alignment - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePumpPlugin(); + PumpInterface pump = activePlugin.getActivePumpPlugin(); if (pump != null && !pump.getPumpDescription().is30minBasalRatesCapable) { for (int index = 0; index < basal_v.size(); index++) { long secondsFromMidnight = basal_v.keyAt(index); if (notify && secondsFromMidnight % 3600 != 0) { if (Config.APS) { - Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, String.format(MainApp.gs(R.string.basalprofilenotaligned), from), Notification.NORMAL); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification)); + Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, resourceHelper.gs(R.string.basalprofilenotaligned, from), Notification.NORMAL); + rxBus.send(new EventNewNotification(notification)); } } } @@ -268,11 +278,11 @@ public class Profile { } protected void sendBelowMinimumNotification(String from) { - RxBus.Companion.getINSTANCE().send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL))); + rxBus.send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, resourceHelper.gs(R.string.minimalbasalvaluereplaced, from), Notification.NORMAL))); } protected void sendAboveMaximumNotification(String from) { - RxBus.Companion.getINSTANCE().send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL))); + rxBus.send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, resourceHelper.gs(R.string.maximumbasalvaluereplaced, from), Notification.NORMAL))); } private void validate(LongSparseArray array) { @@ -326,7 +336,7 @@ public class Profile { else if (array == basal_v) multiplier = percentage / 100d; else - log.error("Unknown array type"); + aapsLogger.error("Unknown array type"); return multiplier; } @@ -344,7 +354,7 @@ public class Profile { else if (array == targetHigh) multiplier = 1d; else - log.error("Unknown array type"); + aapsLogger.error("Unknown array type"); return multiplier; } @@ -407,7 +417,7 @@ public class Profile { public String getIsfList() { if (isf_v == null) isf_v = convertToSparseArray(isf); - return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + MainApp.gs(R.string.profile_per_unit)); + return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + resourceHelper.gs(R.string.profile_per_unit)); } public ProfileValue[] getIsfsMgdl() { @@ -440,7 +450,7 @@ public class Profile { public String getIcList() { if (ic_v == null) ic_v = convertToSparseArray(ic); - return getValuesList(ic_v, null, new DecimalFormat("0.0"), MainApp.gs(R.string.profile_carbs_per_unit)); + return getValuesList(ic_v, null, new DecimalFormat("0.0"), resourceHelper.gs(R.string.profile_carbs_per_unit)); } public ProfileValue[] getIcs() { @@ -474,7 +484,7 @@ public class Profile { public String getBasalList() { if (basal_v == null) basal_v = convertToSparseArray(basal); - return getValuesList(basal_v, null, new DecimalFormat("0.00"), MainApp.gs(R.string.profile_ins_units_per_hour)); + return getValuesList(basal_v, null, new DecimalFormat("0.00"), resourceHelper.gs(R.string.profile_ins_units_per_hour)); } public class ProfileValue { @@ -643,16 +653,21 @@ public class Profile { else return (valueInMmol > 0 ? "+" : "") + DecimalFormatter.to1Decimal(valueInMmol); } - public static double toCurrentUnits(double anyBg) { - if (anyBg < 32) return fromMmolToUnits(anyBg, ProfileFunctions.getSystemUnits()); - else return fromMgdlToUnits(anyBg, ProfileFunctions.getSystemUnits()); + public static double toCurrentUnits(ProfileFunction profileFunction, double anyBg) { + if (anyBg < 32) return fromMmolToUnits(anyBg, profileFunction.getUnits()); + else return fromMgdlToUnits(anyBg, profileFunction.getUnits()); } - public static String toCurrentUnitsString(double anyBg) { + public static double toCurrentUnits(String units, double anyBg) { + if (anyBg < 32) return fromMmolToUnits(anyBg, units); + else return fromMgdlToUnits(anyBg, units); + } + + public static String toCurrentUnitsString(ProfileFunction profileFunction, double anyBg) { if (anyBg < 32) - return toUnitsString(anyBg * Constants.MMOLL_TO_MGDL, anyBg, ProfileFunctions.getSystemUnits()); + return toUnitsString(anyBg * Constants.MMOLL_TO_MGDL, anyBg, profileFunction.getUnits()); else - return toUnitsString(anyBg, anyBg * Constants.MGDL_TO_MMOLL, ProfileFunctions.getSystemUnits()); + return toUnitsString(anyBg, anyBg * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()); } // targets are stored in mg/dl but profile vary @@ -796,8 +811,8 @@ public class Profile { o.put("target_high", target_high); } catch (JSONException e) { - log.error("Unhandled exception" + e); + aapsLogger.error("Unhandled exception" + e); } - return new Profile(o); + return new Profile(injector, o); } } diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.kt b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.kt index ba890a355e..751067a27a 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.data import androidx.collection.ArrayMap +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONException @@ -8,9 +9,13 @@ import org.json.JSONObject import java.util.* import javax.inject.Inject -class ProfileStore(val data: JSONObject) { +class ProfileStore(val injector: HasAndroidInjector, val data: JSONObject) { @Inject lateinit var aapsLogger: AAPSLogger + init { + injector.androidInjector().inject(this) + } + private val cachedObjects = ArrayMap() private fun getStore(): JSONObject? { @@ -49,7 +54,7 @@ class ProfileStore(val data: JSONObject) { JsonHelper.safeGetJSONObject(store, profileName, null)?.let { profileObject -> // take units from profile and if N/A from store JsonHelper.safeGetStringAllowNull(profileObject, "units", JsonHelper.safeGetString(data, "units"))?.let { units -> - profile = Profile(profileObject, units) + profile = Profile(injector, profileObject, units) cachedObjects[profileName] = profile } } diff --git a/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt index b121dbee02..536c5ed68f 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt +++ b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt @@ -1,13 +1,17 @@ package info.nightscout.androidaps.data.defaultProfile +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.utils.Round import org.json.JSONArray import org.json.JSONObject import java.util.* +import javax.inject.Inject +import javax.inject.Singleton +@Singleton +class DefaultProfile @Inject constructor(val injector: HasAndroidInjector) { -class DefaultProfile { var oneToFive: TreeMap> = TreeMap() var sixToEleven: TreeMap> = TreeMap() var twelveToSeventeen: TreeMap> = TreeMap() @@ -18,24 +22,24 @@ class DefaultProfile { if (age >= 1 && age < 6) { val _tdd = if (tdd == 0.0) 0.6 * weight else tdd closest(oneToFive, _tdd * 0.3)?.let { array -> profile.put("basal", arrayToJson(array)) } - val ic = Round.roundTo(250.0 / _tdd, 1.0) - profile.put("carbratio", singleValueArray(ic, arrayOf( 0.0, -4.0, -1.0, -2.0, -4.0, 0.0, -4.0))) + val ic = Round.roundTo(250.0 / _tdd, 1.0) + profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -4.0, -1.0, -2.0, -4.0, 0.0, -4.0))) val isf = Round.roundTo(200.0 / _tdd, 0.1) - profile.put("sens", singleValueArray(isf, arrayOf( 0.0, -2.0, -0.0, -0.0, -2.0, 0.0, -2.0))) + profile.put("sens", singleValueArray(isf, arrayOf(0.0, -2.0, -0.0, -0.0, -2.0, 0.0, -2.0))) } else if (age >= 6 && age < 12) { val _tdd = if (tdd == 0.0) 0.8 * weight else tdd closest(sixToEleven, _tdd * 0.4)?.let { array -> profile.put("basal", arrayToJson(array)) } - val ic = Round.roundTo(375.0 / _tdd, 1.0) - profile.put("carbratio", singleValueArray(ic, arrayOf( 0.0, -3.0, 0.0, -1.0, -3.0, 0.0, -2.0))) + val ic = Round.roundTo(375.0 / _tdd, 1.0) + profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -3.0, 0.0, -1.0, -3.0, 0.0, -2.0))) val isf = Round.roundTo(170.0 / _tdd, 0.1) - profile.put("sens", singleValueArray(isf, arrayOf( 0.0, -1.0, -0.0, -0.0, -1.0, 0.0, -1.0))) + profile.put("sens", singleValueArray(isf, arrayOf(0.0, -1.0, -0.0, -0.0, -1.0, 0.0, -1.0))) } else if (age >= 12 && age < 17) { val _tdd = if (tdd == 0.0) 1.0 * weight else tdd closest(twelveToSeventeen, _tdd * 0.5)?.let { array -> profile.put("basal", arrayToJson(array)) } - val ic = Round.roundTo(500.0 / _tdd, 1.0) - profile.put("carbratio", singleValueArray(ic, arrayOf( 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, -1.0))) + val ic = Round.roundTo(500.0 / _tdd, 1.0) + profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -1.0, 0.0, 0.0, -1.0, 0.0, -1.0))) val isf = Round.roundTo(100.0 / _tdd, 0.1) - profile.put("sens", singleValueArray(isf, arrayOf( 0.2, 0.0, 0.2, 0.2, 0.0, 0.2, 0.2))) + profile.put("sens", singleValueArray(isf, arrayOf(0.2, 0.0, 0.2, 0.2, 0.0, 0.2, 0.2))) } else if (age >= 18) { } @@ -45,7 +49,7 @@ class DefaultProfile { profile.put("timezone", TimeZone.getDefault().getID()) profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units)))) profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units)))) - return Profile(profile, units) + return Profile(injector, profile, units) } init { diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java index 091ee206b6..24b649df6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -11,6 +11,7 @@ import java.util.Objects; import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -28,10 +29,10 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; @DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS) public class BgReading implements DataPointWithLabelInterface { - @Inject AAPSLogger aapsLogger; - @Inject DefaultValueHelper defaultValueHelper; - @Inject ProfileFunction profileFunction; - @Inject ResourceHelper resourceHelper; + @Inject public AAPSLogger aapsLogger; + @Inject public DefaultValueHelper defaultValueHelper; + @Inject public ProfileFunction profileFunction; + @Inject public ResourceHelper resourceHelper; @DatabaseField(id = true) public long date; @@ -58,7 +59,7 @@ public class BgReading implements DataPointWithLabelInterface { public boolean isZTPrediction = false; // true when drawing predictions as bg points (ZT) public BgReading() { - MainApp.instance().androidInjector().inject(this); // TODO it will be removed by new database + MainApp.instance().androidInjector().inject(this); } public BgReading(NSSgv sgv) { diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java index 8a3c0c0b9c..de9d58b930 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -10,7 +10,6 @@ import com.j256.ormlite.table.DatabaseTable; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; import java.util.Objects; @@ -97,7 +96,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface { public Profile getProfileObject() { if (profile == null) try { - profile = new Profile(new JSONObject(profileJson), percentage, timeshift); + profile = new Profile(MainApp.instance().injector, new JSONObject(profileJson), percentage, timeshift); } catch (Exception e) { log.error("Unhandled exception", e); log.error("Unhandled exception", profileJson); diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index c7ba3ad57c..a1ee8dfca1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,6 +5,7 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.BgReading @@ -22,6 +23,7 @@ import info.nightscout.androidaps.plugins.general.automation.triggers.* import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.treatments.Treatment @@ -146,6 +148,9 @@ interface AppComponent : AndroidInjector { fun injectAuthRequest(authRequest: AuthRequest) + fun injectProfile(profile: Profile) + fun injectGlucoseStatus(glucoseStatus: GlucoseStatus) + @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index fe7b27ce32..ae599916d8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -8,6 +8,7 @@ import dagger.Provides import dagger.android.ContributesAndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.BgReading @@ -32,6 +33,7 @@ import info.nightscout.androidaps.plugins.general.automation.triggers.* import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.treatments.Treatment @@ -89,7 +91,8 @@ open class AppModule { @ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA @ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA - @ContributesAndroidInjector fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS + @ContributesAndroidInjector + fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS @ContributesAndroidInjector fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector fun commandBolusInjector(): CommandBolus @@ -197,6 +200,9 @@ open class AppModule { @ContributesAndroidInjector fun authRequestInjector(): AuthRequest + @ContributesAndroidInjector fun profileInjector(): Profile + @ContributesAndroidInjector fun glucoseStatusInjector(): GlucoseStatus + @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt index 1c87926109..b06f0aba45 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt @@ -5,6 +5,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile @@ -22,6 +23,7 @@ import javax.inject.Inject class CalibrationDialog : DialogFragmentWithDate() { + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @@ -40,7 +42,7 @@ class CalibrationDialog : DialogFragmentWithDate() { super.onViewCreated(view, savedInstanceState) val units = profileFunction.getUnits() - val bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData()?.glucose + val bg = Profile.fromMgdlToUnits(GlucoseStatus(injector).glucoseStatusData?.glucose ?: 0.0, units) if (units == Constants.MMOL) overview_calibration_bg.setParams(savedInstanceState?.getDouble("overview_calibration_bg") @@ -56,7 +58,7 @@ class CalibrationDialog : DialogFragmentWithDate() { val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val actions: LinkedList = LinkedList() val bg = overview_calibration_bg.value - actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(bg) + " " + unitLabel) + actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel) if (bg > 0) { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index bcfa3c859e..8dd9a443ae 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -8,6 +8,7 @@ import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -31,6 +32,7 @@ import java.util.* import javax.inject.Inject class CareDialog : DialogFragmentWithDate() { + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @@ -102,7 +104,7 @@ class CareDialog : DialogFragmentWithDate() { } } - val bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData()?.glucose + val bg = Profile.fromMgdlToUnits(GlucoseStatus(injector).getGlucoseStatusData()?.glucose ?: 0.0, profileFunction.getUnits()) val bgTextWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) {} @@ -141,7 +143,7 @@ class CareDialog : DialogFragmentWithDate() { else -> "Manual" } actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) - actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(actions_care_bg.value) + " " + resourceHelper.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, actions_care_bg.value) + " " + resourceHelper.gs(unitResId)) json.put("glucose", actions_care_bg.value) json.put("glucoseType", type) } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt index b731ad540d..382e6359a5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -6,6 +6,7 @@ import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager +import dagger.android.HasAndroidInjector import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R @@ -19,6 +20,7 @@ import org.json.JSONObject import javax.inject.Inject class ProfileViewerDialog : DaggerDialogFragment() { + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @@ -71,7 +73,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { } Mode.CUSTOM_PROFILE -> { - profile = Profile(JSONObject(customProfileJson), customProfileUnits) + profile = Profile(injector, JSONObject(customProfileJson), customProfileUnits) profileName = customProfileName date = "" profileview_datelayout.visibility = View.GONE diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index fd208bbe58..f2393e8c53 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -123,7 +123,7 @@ class TempTargetDialog : DialogFragmentWithDate() { val duration = overview_temptarget_duration.value.toInt() if (target != 0.0 && duration != 0) { actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) - actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + resourceHelper.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) } else { actions.add(resourceHelper.gs(R.string.stoptemptarget)) diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java b/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java index 6fac33cba4..0d8b5abb49 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.interfaces; +import dagger.android.HasAndroidInjector; + /** * Created by mike on 21.05.2017. */ diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java index 0c91d0723c..348cfc7cab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java @@ -35,6 +35,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; * Created by mike on 09.06.2016. */ public class APSResult { + @Inject HasAndroidInjector injector; @Inject public AAPSLogger aapsLogger; @Inject ConstraintChecker constraintChecker; @Inject SP sp; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index 68548b49a2..69cfbf2efe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -123,7 +123,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(mainApp), getInjector()); - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); PumpInterface pump = activePlugin.getActivePump(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java index 4617f684a3..3d99547c31 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java @@ -122,7 +122,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { DetermineBasalAdapterMAJS determineBasalAdapterMAJS; determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(mainApp), getInjector()); - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); PumpInterface pump = activePlugin.getActivePumpPlugin(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index 64833bb9e3..0b2428282c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -46,7 +46,6 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; @Singleton public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { - private final HasAndroidInjector injector; private final ConstraintChecker constraintChecker; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; @@ -84,7 +83,6 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr .description(R.string.description_smb), aapsLogger, resourceHelper, injector ); - this.injector = injector; this.constraintChecker = constraintChecker; this.resourceHelper = resourceHelper; this.profileFunction = profileFunction; @@ -126,9 +124,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS; - determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(mainApp), injector); + determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(mainApp), getInjector()); - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData(); Profile profile = profileFunction.getProfile(); PumpInterface pump = activePlugin.getActivePump(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt index 0be8e9a510..2766d2e8f1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt @@ -31,7 +31,7 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val glucoseStatus = GlucoseStatus.getGlucoseStatusData() + val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() if (glucoseStatus == null && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt index 61f5bd3ef5..01c64f917f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt @@ -42,7 +42,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val glucoseStatus = GlucoseStatus.getGlucoseStatusData() + val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() ?: return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) true diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java index 31cfb8a800..e498b65f65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java @@ -30,7 +30,6 @@ import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.text.DecimalFormat; import java.util.ArrayList; @@ -40,6 +39,7 @@ import java.util.List; import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import dagger.android.support.DaggerDialogFragment; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -69,6 +69,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { + @Inject HasAndroidInjector injector; @Inject DefaultValueHelper defaultValueHelper; @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; @@ -193,7 +194,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O profileSpinner.setSelection(p); } } - final Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); + final Double bg = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); // temp target final List reasonList = Lists.newArrayList( @@ -278,7 +279,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O } sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { - double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); + double bg1 = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) { editBg.setValue(savedInstanceState.getDouble("editBg")); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index 990bb96e46..d2c552c184 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -125,7 +125,7 @@ class DataBroadcastPlugin @Inject constructor( private fun bgStatus(bundle: Bundle) { val lastBG: BgReading = iobCobCalculatorPlugin.lastBg() ?: return - val glucoseStatus = GlucoseStatus.getGlucoseStatusData() ?: return + val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() ?: return bundle.putDouble("glucoseMgdl", lastBG.value) // last BG in mgdl bundle.putLong("glucoseTimeStamp", lastBG.date) // timestamp diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 332755d6af..4a3c20cdf1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -30,6 +30,7 @@ import java.util.List; import javax.inject.Inject; import dagger.android.DaggerService; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -78,6 +79,7 @@ import io.socket.client.Socket; import io.socket.emitter.Emitter; public class NSClientService extends DaggerService { + @Inject HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @Inject NSSettingsStatus nsSettingsStatus; @Inject NSDeviceStatus nsDeviceStatus; @@ -524,7 +526,7 @@ public class NSClientService extends DaggerService { JSONArray profiles = data.getJSONArray("profiles"); if (profiles.length() > 0) { JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1); - profileStore = new ProfileStore(profile); + profileStore = new ProfileStore(injector, profile); broadcastProfile = true; rxBus.send(new EventNSClientNewLog("PROFILE", "profile received")); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 0a21468800..67ab2d2c89 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -1072,7 +1072,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList arrowView.setText(lastBG.directionToSymbol()); bgView.setTextColor(color); arrowView.setTextColor(color); - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + GlucoseStatus glucoseStatus = new GlucoseStatus(injector).getGlucoseStatusData(); if (glucoseStatus != null) { if (deltaView != null) deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index b33cec1518..a953ac4912 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -138,7 +138,7 @@ class PersistentNotificationPlugin @Inject constructor( var line1_aa: String val units = profileFunction.getUnits() val lastBG = iobCobCalculatorPlugin.lastBg() - val glucoseStatus = GlucoseStatus.getGlucoseStatusData() + val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() if (lastBG != null) { line1_aa = lastBG.valueToUnitsToString(units) line1 = line1_aa diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 2b3b81b78b..54295f9bc7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -70,8 +70,8 @@ class SmsCommunicatorPlugin @Inject constructor( ) { private val disposable = CompositeDisposable() - private var allowedNumbers: MutableList = ArrayList() - private var messageToConfirm: AuthRequest? = null + var allowedNumbers: MutableList = ArrayList() + var messageToConfirm: AuthRequest? = null var lastRemoteBolusTime: Long = 0 var messages = ArrayList() @@ -159,7 +159,7 @@ class SmsCommunicatorPlugin @Inject constructor( } } - private fun isCommand(command: String, number: String): Boolean { + fun isCommand(command: String, number: String): Boolean { var found = false commands.forEach { (k, _) -> if (k == command) found = true @@ -167,7 +167,7 @@ class SmsCommunicatorPlugin @Inject constructor( return found || messageToConfirm?.requester?.phoneNumber == number } - private fun isAllowedNumber(number: String): Boolean { + fun isAllowedNumber(number: String): Boolean { for (num in allowedNumbers) { if (num == number) return true } @@ -184,7 +184,7 @@ class SmsCommunicatorPlugin @Inject constructor( } } - private fun processSms(receivedSms: Sms) { + fun processSms(receivedSms: Sms) { if (!isEnabled(PluginType.GENERAL)) { aapsLogger.debug(LTag.SMS, "Ignoring SMS. Plugin disabled.") return @@ -284,7 +284,7 @@ class SmsCommunicatorPlugin @Inject constructor( val agoMin = (agoMsec / 60.0 / 1000.0).toInt() reply = resourceHelper.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(resourceHelper.gs(R.string.sms_minago), agoMin) + ", " } - val glucoseStatus = GlucoseStatus.getGlucoseStatusData() + val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() @@ -612,7 +612,7 @@ class SmsCommunicatorPlugin @Inject constructor( if (result.success) { var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) if (Config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) - replyText += "\n" + activePlugin.activePump.shortStatus(true) + replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) @@ -784,7 +784,7 @@ class SmsCommunicatorPlugin @Inject constructor( var ttDuration = sp.getInt(keyDuration, defaultTargetDuration) ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration var tt = sp.getDouble(keyTarget, if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL) - tt = Profile.toCurrentUnits(tt) + tt = Profile.toCurrentUnits(profileFunction, tt) tt = if (tt > 0) tt else if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL val tempTarget = TempTarget() .date(System.currentTimeMillis()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index 35d79040fc..7fd609493f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -28,6 +28,7 @@ import java.util.Set; import javax.inject.Inject; import dagger.android.AndroidInjection; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -58,6 +59,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { + @Inject public HasAndroidInjector injector; @Inject public AAPSLogger aapsLogger; @Inject public WearPlugin wearPlugin; @Inject public ResourceHelper resourceHelper; @@ -274,7 +276,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog BgReading lastBG = iobCobCalculatorPlugin.lastBg(); // Log.d(TAG, logPrefix + "LastBg=" + lastBG); if (lastBG != null) { - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + GlucoseStatus glucoseStatus = new GlucoseStatus(injector).getGlucoseStatusData(); if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { googleApiConnect(); @@ -380,7 +382,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog if (last_bg == null) return; List graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true); - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(true); + GlucoseStatus glucoseStatus = new GlucoseStatus(injector).getGlucoseStatusData(true); if (!graph_bgs.isEmpty()) { DataMap entries = dataMapSingleBG(last_bg, glucoseStatus); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java index 334156230e..cfe9c75727 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java @@ -2,15 +2,15 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator; import androidx.annotation.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.List; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.Round; @@ -20,7 +20,11 @@ import info.nightscout.androidaps.utils.Round; */ public class GlucoseStatus { - private static Logger log = StacktraceLoggerWrapper.getLogger(GlucoseStatus.class); + @Inject public AAPSLogger aapsLogger; + @Inject public IobCobCalculatorPlugin iobCobCalculatorPlugin; + + private HasAndroidInjector injector; + public double glucose = 0d; public double delta = 0d; public double avgdelta = 0d; @@ -36,7 +40,9 @@ public class GlucoseStatus { "Long avg. delta: " + DecimalFormatter.to2Decimal(long_avgdelta) + " mg/dl"; } - public GlucoseStatus() { + public GlucoseStatus(HasAndroidInjector injector) { + injector.androidInjector().inject(this); + this.injector = injector; } public GlucoseStatus round() { @@ -50,36 +56,33 @@ public class GlucoseStatus { @Nullable - public static GlucoseStatus getGlucoseStatusData() { + public GlucoseStatus getGlucoseStatusData() { return getGlucoseStatusData(false); } @Nullable - public static GlucoseStatus getGlucoseStatusData(boolean allowOldData) { + public GlucoseStatus getGlucoseStatusData(boolean allowOldData) { // load 45min //long fromtime = DateUtil.now() - 60 * 1000L * 45; //List data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false); - synchronized (IobCobCalculatorPlugin.getPlugin().getDataLock()) { + synchronized (iobCobCalculatorPlugin.getDataLock()) { - List data = IobCobCalculatorPlugin.getPlugin().getBgReadings(); + List data = iobCobCalculatorPlugin.getBgReadings(); if (data == null) { - if (L.isEnabled(L.GLUCOSE)) - log.debug("data=null"); + aapsLogger.debug(LTag.GLUCOSE, "data=null"); return null; } int sizeRecords = data.size(); if (sizeRecords == 0) { - if (L.isEnabled(L.GLUCOSE)) - log.debug("sizeRecords==0"); + aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==0"); return null; } if (data.get(0).date < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) { - if (L.isEnabled(L.GLUCOSE)) - log.debug("olddata"); + aapsLogger.debug(LTag.GLUCOSE, "olddata"); return null; } @@ -88,15 +91,14 @@ public class GlucoseStatus { double change; if (sizeRecords == 1) { - GlucoseStatus status = new GlucoseStatus(); + GlucoseStatus status = new GlucoseStatus(injector); status.glucose = now.value; status.short_avgdelta = 0d; status.delta = 0d; status.long_avgdelta = 0d; status.avgdelta = 0d; // for OpenAPS MA status.date = now_date; - if (L.isEnabled(L.GLUCOSE)) - log.debug("sizeRecords==1"); + aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==1"); return status.round(); } @@ -120,8 +122,7 @@ public class GlucoseStatus { change = now.value - then.value; avgdelta = change / minutesago * 5; - if (L.isEnabled(L.GLUCOSE)) - log.debug(then.toString() + " minutesago=" + minutesago + " avgdelta=" + avgdelta); + aapsLogger.debug(LTag.GLUCOSE, then.toString() + " minutesago=" + minutesago + " avgdelta=" + avgdelta); // use the average of all data points in the last 2.5m for all further "now" calculations if (0 < minutesago && minutesago < 2.5) { @@ -146,7 +147,7 @@ public class GlucoseStatus { } } - GlucoseStatus status = new GlucoseStatus(); + GlucoseStatus status = new GlucoseStatus(injector); status.glucose = now.value; status.date = now_date; @@ -161,8 +162,7 @@ public class GlucoseStatus { status.long_avgdelta = average(long_deltas); status.avgdelta = status.short_avgdelta; // for OpenAPS MA - if (L.isEnabled(L.GLUCOSE)) - log.debug(status.log()); + aapsLogger.debug(LTag.GLUCOSE, status.log()); return status.round(); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index d0bec3b5d9..e060a74c46 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -428,7 +428,7 @@ class LocalProfilePlugin @Inject constructor( aapsLogger.error("Unhandled exception", e) } - return ProfileStore(json) + return ProfileStore(injector, json) } override fun getProfile(): ProfileStore? { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt index 69c3e4dc3d..a93cbaad01 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt @@ -53,7 +53,7 @@ class NSProfilePlugin @Inject constructor( @Suppress("SpellCheckingInspection") val activeProfile = bundles.getString("activeprofile") val profileString = bundles.getString("profile") - profile = ProfileStore(JSONObject(profileString)) + profile = ProfileStore(injector, JSONObject(profileString)) storeNSProfile() if (isEnabled()) { rxBus.send(EventProfileStoreChanged()) @@ -72,7 +72,7 @@ class NSProfilePlugin @Inject constructor( val profileString = sp.getStringOrNull("profile", null) if (profileString != null) { aapsLogger.debug(LTag.PROFILE, "Loaded profile: $profileString") - profile = ProfileStore(JSONObject(profileString)) + profile = ProfileStore(injector, JSONObject(profileString)) } else { aapsLogger.debug(LTag.PROFILE, "Stored profile not found") // force restart of nsclient to fetch profile diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt index ac0732ff44..3f095ea645 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.danaR +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile @@ -20,11 +21,13 @@ import javax.inject.Singleton @Singleton class DanaRPump @Inject constructor( private val aapsLogger: AAPSLogger, - private val sp: SP + private val sp: SP, + private val injector: HasAndroidInjector ) { var lastConnection: Long = 0 var lastSettingsRead: Long = 0 + // Info var serialNumber = "" var shippingDate: Long = 0 @@ -38,6 +41,7 @@ class DanaRPump @Inject constructor( var isConfigUD = false var isExtendedBolusEnabled = false var isEasyModeEnabled = false + // Status var pumpSuspended = false var calculatorEnabled = false @@ -68,6 +72,7 @@ class DanaRPump @Inject constructor( var extendedBolusStart: Long = 0 var extendedBolusRemainingMinutes = 0 var extendedBolusDeliveredSoFar = 0.0 //RS only = 0.0 + // Profile var units = 0 var easyBasalMode = 0 @@ -86,13 +91,17 @@ class DanaRPump @Inject constructor( var nightCIR = 0 var nightCF = 0.0 var activeProfile = 0 + //var pumpProfiles = arrayOf>() - var pumpProfiles : Array>? = null + var pumpProfiles: Array>? = null + //Limits var maxBolus = 0.0 var maxBasal = 0.0 + // DanaRS specific var rsPassword = "" + // User settings var timeDisplayType = 0 var buttonScrollOnOff = 0 @@ -106,6 +115,7 @@ class DanaRPump @Inject constructor( var refillAmount = 0 var userOptionsFrompump: ByteArray? = null var initialBolusAmount = 0.0 + // Bolus settings var bolusCalculationOption = 0 var missedBolusConfig = 0 @@ -166,13 +176,13 @@ class DanaRPump @Inject constructor( } catch (e: Exception) { return null } - return ProfileStore(json) + return ProfileStore(injector, json) } return null } fun buildDanaRProfileRecord(nsProfile: Profile): Array { - val record = Array(24){ 0.0} + val record = Array(24) { 0.0 } for (hour in 0..23) { //Some values get truncated to the next lower one. // -> round them to two decimals and make sure we are a small delta larger (that will get truncated) @@ -199,6 +209,7 @@ class DanaRPump @Inject constructor( const val DELIVERY_BASAL = 0x04 const val DELIVERY_EXT_BOLUS = 0x08 const val PROFILE_PREFIX = "DanaR-" + // v2 history entries const val TEMPSTART = 1 const val TEMPSTOP = 2 diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java index 6816b6fa1f..3023f297d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.java @@ -64,7 +64,7 @@ public class SWEditNumberWithUnits extends SWItem { layout.addView(l); double initValue = SP.getDouble(preferenceId, init); - initValue = Profile.toCurrentUnits(initValue); + initValue = Profile.toCurrentUnits(ProfileFunctions.getSystemUnits(), initValue); NumberPicker numberPicker = new NumberPicker(context); if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/DefaultValueHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/DefaultValueHelper.kt index 1214bda90b..6f7e49c9bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/DefaultValueHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/DefaultValueHelper.kt @@ -52,7 +52,7 @@ open class DefaultValueHelper @Inject constructor( fun determineEatingSoonTT(): Double { val units = profileFunction.getUnits() var value = sp.getDouble(R.string.key_eatingsoon_target, getDefaultEatingSoonTT(units)) - value = Profile.toCurrentUnits(value) + value = Profile.toCurrentUnits(profileFunction, value) return if (value > 0) value else getDefaultEatingSoonTT(units) } @@ -69,7 +69,7 @@ open class DefaultValueHelper @Inject constructor( fun determineActivityTT(): Double { val units = profileFunction.getUnits() var value = sp.getDouble(R.string.key_activity_target, getDefaultActivityTT(units)) - value = Profile.toCurrentUnits(value) + value = Profile.toCurrentUnits(profileFunction, value) return if (value > 0) value else getDefaultActivityTT(units) } @@ -86,7 +86,7 @@ open class DefaultValueHelper @Inject constructor( fun determineHypoTT(): Double { val units = profileFunction.getUnits() var value = sp.getDouble(R.string.key_hypo_target, getDefaultHypoTT(units)) - value = Profile.toCurrentUnits(value) + value = Profile.toCurrentUnits(profileFunction, value) return if (value > 0) value else getDefaultHypoTT(units) } @@ -101,14 +101,14 @@ open class DefaultValueHelper @Inject constructor( fun determineHighLine(): Double { var highLineSetting = sp.getDouble(R.string.key_high_mark, bgTargetHigh) if (highLineSetting < 1) highLineSetting = Constants.HIGHMARK - highLineSetting = Profile.toCurrentUnits(highLineSetting) + highLineSetting = Profile.toCurrentUnits(profileFunction, highLineSetting) return highLineSetting } fun determineLowLine(): Double { var lowLineSetting = sp.getDouble(R.string.key_low_mark, bgTargetLow) if (lowLineSetting < 1) lowLineSetting = Constants.LOWMARK - lowLineSetting = Profile.toCurrentUnits(lowLineSetting) + lowLineSetting = Profile.toCurrentUnits(profileFunction, lowLineSetting) return lowLineSetting } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt index ae8cf652c2..b8d29af3d5 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt @@ -6,6 +6,7 @@ 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.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.MidnightTime @@ -16,7 +17,8 @@ import javax.inject.Singleton @Singleton class TirCalculator @Inject constructor( - private val resourceHelper: ResourceHelper + private val resourceHelper: ResourceHelper, + private val profileFunction: ProfileFunction ){ fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray { if (lowMgdl < 39) throw RuntimeException("Low below 39") @@ -75,10 +77,10 @@ class TirCalculator @Inject constructor( return HtmlHelper.fromHtml( "
" + resourceHelper.gs(R.string.tir) + ":
" + toText(resourceHelper, tir7) + - "
" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(lowTirMgdl) + "-" + Profile.toCurrentUnitsString(highTirMgdl) + "):
" + + "
" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + "):
" + averageTir7.toText(resourceHelper, tir7.size()) + "
" + averageTir30.toText(resourceHelper, tir30.size()) + - "
" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(lowTitMgdl) + "-" + Profile.toCurrentUnitsString(highTitMgdl) + "):
" + + "
" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTitMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTitMgdl) + "):
" + averageTit7.toText(resourceHelper, tit7.size()) + "
" + averageTit30.toText(resourceHelper, tit30.size()) ) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 7550ba0263..9dfdea4acc 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -39,6 +39,7 @@ class BolusWizard @Inject constructor( injector: HasAndroidInjector ) { + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper @@ -170,7 +171,7 @@ class BolusWizard @Inject constructor( } // Insulin from 15 min trend - glucoseStatus = GlucoseStatus.getGlucoseStatusData() + glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() glucoseStatus?.let { if (useTrend) { trend = it.short_avgdelta diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt index d691f20c41..3809573e98 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.utils.wizard +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile @@ -21,6 +22,7 @@ import javax.inject.Inject class QuickWizardEntry @Inject constructor(private val mainApp: MainApp) { + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @@ -107,7 +109,7 @@ class QuickWizardEntry @Inject constructor(private val mainApp: MainApp) { } if (loopPlugin.isEnabled(loopPlugin.getType()) && loopPlugin.isSuperBolus) superBolus = false // Trend - val glucoseStatus = GlucoseStatus.getGlucoseStatusData() + val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() var trend = false if (useTrend() == YES) { trend = true diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java index a775f4ab9d..4c632c4c1e 100644 --- a/app/src/test/java/info/AAPSMocker.java +++ b/app/src/test/java/info/AAPSMocker.java @@ -238,43 +238,43 @@ public class AAPSMocker { } - 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); + /* + public static Profile getValidProfile() { + try { + if (profile == null) + profile = new Profile(new JSONObject(validProfile), Constants.MGDL); + } catch (JSONException ignored) { } - } catch (JSONException ignored) { - Assert.fail("getValidProfileStore() failed"); + return profile; } - return profileStore; - } + public static ProfileStore getValidProfileStore() { + try { + if (profileStore == null) { + JSONObject json = new JSONObject(); + JSONObject store = new JSONObject(); + JSONObject profile = new JSONObject(validProfile); - 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); - } + 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); diff --git a/app/src/test/java/info/TestBase.kt b/app/src/test/java/info/TestBase.kt index 519f12decb..389b034e90 100644 --- a/app/src/test/java/info/TestBase.kt +++ b/app/src/test/java/info/TestBase.kt @@ -1,5 +1,7 @@ package info +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore @@ -11,7 +13,7 @@ import org.mockito.junit.MockitoRule open class TestBase { val validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" - val validProfile: Profile = Profile(JSONObject(validProfileJSON), Constants.MGDL) + val validProfile: Profile = Profile(HasAndroidInjector { AndroidInjector { Unit } }, JSONObject(validProfileJSON), Constants.MGDL) val TESTPROFILENAME = "someProfile" fun getValidProfileStore(): ProfileStore { @@ -20,7 +22,7 @@ open class TestBase { store.put(TESTPROFILENAME, JSONObject(validProfileJSON)) json.put("defaultProfile", TESTPROFILENAME) json.put("store", store) - return ProfileStore(json) + return ProfileStore(HasAndroidInjector { AndroidInjector { Unit } }, json) } // Add a JUnit rule that will setup the @Mock annotated vars and log. diff --git a/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.java b/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.java deleted file mode 100644 index e3714a7545..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package info.nightscout.androidaps.db; - -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.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.logging.Logger; - -import info.AAPSMocker; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; -import info.nightscout.androidaps.utils.SP; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Logger.class, L.class, SP.class, GlucoseStatus.class}) -public class BgReadingTest { - private BgReading bgReading = new BgReading(); - - @Test - public void valueToUnits() { - bgReading.value = 18; - assertEquals(18, bgReading.valueToUnits(Constants.MGDL) * 1, 0.01d); - assertEquals(1, bgReading.valueToUnits(Constants.MMOL) * 1, 0.01d); - } - - @Test - public void directionToSymbol() { - bgReading = new BgReading(); - bgReading.direction = "DoubleDown"; - assertEquals("\u21ca", bgReading.directionToSymbol()); - bgReading.direction = "SingleDown"; - assertEquals("\u2193", bgReading.directionToSymbol()); - bgReading.direction = "FortyFiveDown"; - assertEquals("\u2198", bgReading.directionToSymbol()); - bgReading.direction = "Flat"; - assertEquals("\u2192", bgReading.directionToSymbol()); - bgReading.direction = "FortyFiveUp"; - assertEquals("\u2197", bgReading.directionToSymbol()); - bgReading.direction = "SingleUp"; - assertEquals("\u2191", bgReading.directionToSymbol()); - bgReading.direction = "DoubleUp"; - assertEquals("\u21c8", bgReading.directionToSymbol()); - bgReading.direction = "OUT OF RANGE"; - assertEquals("??", bgReading.directionToSymbol()); - - } - - @Test - public void dateTest() { - bgReading = new BgReading(); - long now = System.currentTimeMillis(); - bgReading.date = now; - Date nowDate = new Date(now); - assertEquals(now, bgReading.date(now).date); - assertEquals(now, bgReading.date(nowDate).date); - } - - @Test - public void valueTest() { - bgReading = new BgReading(); - double valueToSet = 81; // 4.5 mmol - assertEquals(81d, bgReading.value(valueToSet).value, 0.01d); - } - - @Test - public void copyFromTest() { - bgReading = new BgReading(); - BgReading copy = new BgReading(); - bgReading.value = 81; - long now = System.currentTimeMillis(); - bgReading.date = now; - copy.date = now; - - copy.copyFrom(bgReading); - - assertEquals(81, copy.value, 0.1d); - assertEquals(now, copy.date); - assertEquals(bgReading.directionToSymbol(), copy.directionToSymbol()); - } - - @Test - public void isEqualTest() { - bgReading = new BgReading(); - BgReading copy = new BgReading(); - bgReading.value = 81; - long now = System.currentTimeMillis(); - bgReading.date = now; - copy.date = now; - - copy.copyFrom(bgReading); - - assertTrue(copy.isEqual(bgReading)); - assertFalse(copy.isEqual(new BgReading())); - } - - @Test - public void calculateDirection() { - List bgReadingsList = null; - AAPSMocker.mockDatabaseHelper(); - - when(MainApp.getDbHelper().getAllBgreadingsDataFromTime(anyLong(),anyBoolean())).thenReturn(bgReadingsList); - assertEquals("NONE", bgReading.calculateDirection()); - setReadings(72,0); - assertEquals("DoubleUp", bgReading.calculateDirection()); - setReadings(76,60); - assertEquals("SingleUp", bgReading.calculateDirection()); - setReadings(74,65); - assertEquals("FortyFiveUp", bgReading.calculateDirection()); - setReadings(72,72); - assertEquals("Flat", bgReading.calculateDirection()); - setReadings(0,72); - assertEquals("DoubleDown", bgReading.calculateDirection()); - setReadings(60,76); - assertEquals("SingleDown", bgReading.calculateDirection()); - setReadings(65,74); - assertEquals("FortyFiveDown", bgReading.calculateDirection()); - } - - @Before - public void prepareMock() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); - AAPSMocker.mockDatabaseHelper(); - } - - public void setReadings(int current_value, int previous_value){ - BgReading now = new BgReading(); - now.value = current_value; - now.date = System.currentTimeMillis(); - BgReading previous = new BgReading(); - previous.value = previous_value; - previous.date = System.currentTimeMillis() - ( 6 * 60 * 1000L); - List bgReadings = new ArrayList() {{ - add(now); - add(previous); - }}; - when(MainApp.getDbHelper().getAllBgreadingsDataFromTime(anyLong(),anyBoolean())).thenReturn(bgReadings); - } -} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt b/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt new file mode 100644 index 0000000000..5769b15c8f --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/db/BgReadingTest.kt @@ -0,0 +1,163 @@ +package info.nightscout.androidaps.db + +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector +import info.AAPSMocker +import info.TestBase +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus +import info.nightscout.androidaps.utils.DefaultValueHelper +import info.nightscout.androidaps.utils.SP +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.Mockito.`when` +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner +import java.util.* +import java.util.logging.Logger + +@RunWith(PowerMockRunner::class) +@PrepareForTest(MainApp::class, Logger::class, L::class, SP::class, GlucoseStatus::class) +class BgReadingTest : TestBase() { + + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var defaultValueHelper: DefaultValueHelper + @Mock lateinit var profileFunction: ProfileFunction + @Mock lateinit var resourceHelper: ResourceHelper + + var injector: HasAndroidInjector = HasAndroidInjector { + AndroidInjector { + if (it is BgReading) { + it.aapsLogger = aapsLogger + it.resourceHelper = resourceHelper + it.defaultValueHelper = defaultValueHelper + it.profileFunction = profileFunction + } + } + } + + @Test + fun valueToUnits() { + val bgReading = BgReading() + bgReading.value = 18.0 + Assert.assertEquals(18.0, bgReading.valueToUnits(Constants.MGDL) * 1, 0.01) + Assert.assertEquals(1.0, bgReading.valueToUnits(Constants.MMOL) * 1, 0.01) + } + + @Test + fun directionToSymbol() { + val bgReading = BgReading() + bgReading.direction = "DoubleDown" + Assert.assertEquals("\u21ca", bgReading.directionToSymbol()) + bgReading.direction = "SingleDown" + Assert.assertEquals("\u2193", bgReading.directionToSymbol()) + bgReading.direction = "FortyFiveDown" + Assert.assertEquals("\u2198", bgReading.directionToSymbol()) + bgReading.direction = "Flat" + Assert.assertEquals("\u2192", bgReading.directionToSymbol()) + bgReading.direction = "FortyFiveUp" + Assert.assertEquals("\u2197", bgReading.directionToSymbol()) + bgReading.direction = "SingleUp" + Assert.assertEquals("\u2191", bgReading.directionToSymbol()) + bgReading.direction = "DoubleUp" + Assert.assertEquals("\u21c8", bgReading.directionToSymbol()) + bgReading.direction = "OUT OF RANGE" + Assert.assertEquals("??", bgReading.directionToSymbol()) + } + + @Test fun dateTest() { + val bgReading = BgReading() + val now = System.currentTimeMillis() + bgReading.date = now + val nowDate = Date(now) + Assert.assertEquals(now, bgReading.date(now).date) + Assert.assertEquals(now, bgReading.date(nowDate).date) + } + + @Test fun valueTest() { + val bgReading = BgReading() + val valueToSet = 81.0 // 4.5 mmol + Assert.assertEquals(81.0, bgReading.value(valueToSet).value, 0.01) + } + + @Test fun copyFromTest() { + val bgReading = BgReading() + val copy = BgReading() + bgReading.value = 81.0 + val now = System.currentTimeMillis() + bgReading.date = now + copy.date = now + copy.copyFrom(bgReading) + Assert.assertEquals(81.0, copy.value, 0.1) + Assert.assertEquals(now, copy.date) + Assert.assertEquals(bgReading.directionToSymbol(), copy.directionToSymbol()) + } + + @Test + fun isEqualTest() { + val bgReading = BgReading() + val copy = BgReading() + bgReading.value = 81.0 + val now = System.currentTimeMillis() + bgReading.date = now + copy.date = now + copy.copyFrom(bgReading) + Assert.assertTrue(copy.isEqual(bgReading)) + Assert.assertFalse(copy.isEqual(BgReading())) + } + + @Test fun calculateDirection() { + val bgReading = BgReading() + val bgReadingsList: List? = null + AAPSMocker.mockDatabaseHelper() + `when`(MainApp.getDbHelper().getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadingsList) + Assert.assertEquals("NONE", bgReading.calculateDirection()) + setReadings(72, 0) + Assert.assertEquals("DoubleUp", bgReading.calculateDirection()) + setReadings(76, 60) + Assert.assertEquals("SingleUp", bgReading.calculateDirection()) + setReadings(74, 65) + Assert.assertEquals("FortyFiveUp", bgReading.calculateDirection()) + setReadings(72, 72) + Assert.assertEquals("Flat", bgReading.calculateDirection()) + setReadings(0, 72) + Assert.assertEquals("DoubleDown", bgReading.calculateDirection()) + setReadings(60, 76) + Assert.assertEquals("SingleDown", bgReading.calculateDirection()) + setReadings(65, 74) + Assert.assertEquals("FortyFiveDown", bgReading.calculateDirection()) + } + + @Before + fun prepareMock() { + val mainApp = AAPSMocker.mockMainApp() + AAPSMocker.mockApplicationContext() + AAPSMocker.mockSP() + AAPSMocker.mockL() + AAPSMocker.mockDatabaseHelper() + `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) + } + + fun setReadings(current_value: Int, previous_value: Int) { + val now = BgReading() + now.value = current_value.toDouble() + now.date = System.currentTimeMillis() + val previous = BgReading() + previous.value = previous_value.toDouble() + previous.date = System.currentTimeMillis() - 6 * 60 * 1000L + val bgReadings: MutableList = mutableListOf() + bgReadings.add(now) + bgReadings.add(previous) + `when`(MainApp.getDbHelper().getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadings) + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java deleted file mode 100644 index 7ff422d736..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java +++ /dev/null @@ -1,976 +0,0 @@ -package info.nightscout.androidaps.plugins.general.smsCommunicator; - -import android.telephony.SmsManager; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.ArrayList; -import java.util.List; - -import dagger.Lazy; -import info.AAPSMocker; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; -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.insulin.InsulinOrefRapidActingPlugin; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin; -import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.queue.CommandQueue; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.SP; -import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.XdripCalibrations; -import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.powermock.api.mockito.PowerMockito.doAnswer; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ - L.class, SP.class, MainApp.class, DateUtil.class, ProfileFunctions.class, - TreatmentsPlugin.class, SmsManager.class, IobCobCalculatorPlugin.class, - CommandQueue.class, ConfigBuilderPlugin.class, NSUpload.class, ProfileInterface.class, - LocalProfilePlugin.class, XdripCalibrations.class, VirtualPumpPlugin.class, LoopPlugin.class -}) - -public class SmsCommunicatorPluginTest { - - private SmsCommunicatorPlugin smsCommunicatorPlugin; - private LoopPlugin loopPlugin; - - private boolean hasBeenRun = false; - - private VirtualPumpPlugin virtualPumpPlugin; - - @Test - public void processSettingsTest() { - // called from constructor - Assert.assertEquals("1234", smsCommunicatorPlugin.getAllowedNumbers().get(0)); - Assert.assertEquals("5678", smsCommunicatorPlugin.getAllowedNumbers().get(1)); - Assert.assertEquals(2, smsCommunicatorPlugin.getAllowedNumbers().size()); - } - - @Test - public void isCommandTest() { - Assert.assertTrue(smsCommunicatorPlugin.isCommand("BOLUS", "")); - smsCommunicatorPlugin.setMessageToConfirm(null); - Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "")); - smsCommunicatorPlugin.setMessageToConfirm(new AuthRequest(smsCommunicatorPlugin, new Sms("1234", "ddd"), "RequestText", "ccode", new SmsAction() { - @Override - public void run() { - } - })); - Assert.assertTrue(smsCommunicatorPlugin.isCommand("BLB", "1234")); - Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "2345")); - smsCommunicatorPlugin.setMessageToConfirm(null); - } - - @Test - public void isAllowedNumberTest() { - Assert.assertTrue(smsCommunicatorPlugin.isAllowedNumber("5678")); - Assert.assertFalse(smsCommunicatorPlugin.isAllowedNumber("56")); - } - - @Test - public void processSmsTest() { - Sms sms; - - // SMS from not allowed number should be ignored - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("12", "aText"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertTrue(sms.getIgnored()); - Assert.assertEquals("aText", smsCommunicatorPlugin.getMessages().get(0).getText()); - - //UNKNOWN - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "UNKNOWN"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("UNKNOWN", smsCommunicatorPlugin.getMessages().get(0).getText()); - - //BG - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BG"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BG", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("IOB:")); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Last BG: 100")); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("COB: 10(2)g")); - - // LOOP : test remote control disabled - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP STATUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Remote command is not allowed")); - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //LOOP STATUS : disabled - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP STATUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP STATUS : suspended - when(loopPlugin.minutesToEndOfSuspend()).thenReturn(10); - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(true); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP STATUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Suspended (10 m)", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP STATUS : enabled - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP STATUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP : wrong format - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP DISABLE : already disabled - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP DISABLE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP DISABLE : from enabled - hasBeenRun = false; - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - doAnswer((Answer) invocation -> { - hasBeenRun = true; - return null; - }).when(loopPlugin).setPluginEnabled(PluginType.LOOP, false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP DISABLE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop has been disabled Temp basal canceled", smsCommunicatorPlugin.getMessages().get(1).getText()); - Assert.assertTrue(hasBeenRun); - - //LOOP ENABLE : already enabled - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP ENABLE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP ENABLE : from disabled - hasBeenRun = false; - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false); - doAnswer((Answer) invocation -> { - hasBeenRun = true; - return null; - }).when(loopPlugin).setPluginEnabled(PluginType.LOOP, true); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP ENABLE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop has been enabled", smsCommunicatorPlugin.getMessages().get(1).getText()); - Assert.assertTrue(hasBeenRun); - - //LOOP RESUME : already enabled - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP RESUME"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP RESUME", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Loop resumed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP SUSPEND 1 2: wrong format - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP SUSPEND 1 2"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP SUSPEND 1 2", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP SUSPEND 0 : wrong duration - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP SUSPEND 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP SUSPEND 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong duration", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //LOOP SUSPEND 100 : suspend for 100 min + correct answer - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP SUSPEND 100"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP SUSPEND 100", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To suspend loop for 100 minutes reply with code ")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Loop suspended Temp basal canceled", smsCommunicatorPlugin.getMessages().get(3).getText()); - - //LOOP SUSPEND 200 : limit to 180 min + wrong answer - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP SUSPEND 200"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP SUSPEND 200", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To suspend loop for 180 minutes reply with code ")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - // ignore from other number - smsCommunicatorPlugin.processSms(new Sms("5678", passCode)); - smsCommunicatorPlugin.processSms(new Sms("1234", "XXXX")); - Assert.assertEquals("XXXX", smsCommunicatorPlugin.getMessages().get(3).getText()); - Assert.assertEquals("Wrong code. Command cancelled.", smsCommunicatorPlugin.getMessages().get(4).getText()); - //then correct code should not work - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(5).getText()); - Assert.assertEquals(6, smsCommunicatorPlugin.getMessages().size()); // processed as common message - - //LOOP BLABLA - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "LOOP BLABLA"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("LOOP BLABLA", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //TREATMENTS REFRESH - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "TREATMENTS REFRESH"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("TREATMENTS REFRESH", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("TREATMENTS REFRESH")); - - //TREATMENTS BLA BLA - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "TREATMENTS BLA BLA"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("TREATMENTS BLA BLA", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //TREATMENTS BLABLA - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "TREATMENTS BLABLA"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("TREATMENTS BLABLA", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //NSCLIENT RESTART - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "NSCLIENT RESTART"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("NSCLIENT RESTART", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("NSCLIENT RESTART")); - - //NSCLIENT BLA BLA - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "NSCLIENT BLA BLA"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("NSCLIENT BLA BLA", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //NSCLIENT BLABLA - when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true); - when(loopPlugin.isSuspended()).thenReturn(false); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "NSCLIENT BLABLA"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("NSCLIENT BLABLA", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PUMP - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PUMP"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PUMP", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Virtual Pump", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //HELP - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "HELP"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("HELP", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("PUMP")); - - //HELP PUMP - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "HELP PUMP"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("HELP PUMP", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("PUMP")); - - //SMS : wrong format - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "SMS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("SMS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //SMS STOP - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "SMS DISABLE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("SMS DISABLE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To disable the SMS Remote Service reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.")); - - //TARGET : wrong format - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "TARGET"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertFalse(sms.getIgnored()); - Assert.assertEquals("TARGET", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //TARGET MEAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "TARGET MEAL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("TARGET MEAL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To set the Temp Target")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("set successfully")); - - //TARGET STOP/CANCEL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "TARGET STOP"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("TARGET STOP", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To cancel Temp Target reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Temp Target canceled successfully")); - } - - @Test - public void processProfileTest() { - Sms sms; - - //PROFILE - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //PROFILE - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PROFILE LIST (no profile interface) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE LIST"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Not configured", smsCommunicatorPlugin.getMessages().get(1).getText()); - - ProfileInterface profileInterface = mock(LocalProfilePlugin.class); - when(ConfigBuilderPlugin.getPlugin().getActiveProfileInterface()).thenReturn(profileInterface); - - //PROFILE LIST (no profile defined) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE LIST"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Not configured", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(profileInterface.getProfile()).thenReturn(AAPSMocker.getValidProfileStore()); - - //PROFILE STATUS - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE STATUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE STATUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals(AAPSMocker.TESTPROFILENAME, smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PROFILE LIST - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE LIST"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("1. " + AAPSMocker.TESTPROFILENAME, smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PROFILE 2 (non existing) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE 2"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE 2", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PROFILE 1 0(wrong percentage) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE 1 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE 1 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PROFILE 0(wrong index) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //PROFILE 1(OK) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE 1"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE 1", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To switch profile to someProfile 100% reply with code")); - - //PROFILE 1 90(OK) - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "PROFILE 1 90"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("PROFILE 1 90", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To switch profile to someProfile 90% reply with code")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Profile switch created", smsCommunicatorPlugin.getMessages().get(3).getText()); - } - - @Test - public void processBasalTest() { - Sms sms; - - //BASAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //BASAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //BASAL CANCEL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL CANCEL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL CANCEL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To stop temp basal reply with code")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Temp basal canceled")); - - //BASAL a% - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL a%"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL a%", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //BASAL 10% 0 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL 10% 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyBasalPercentConstraints(any(), any())).thenReturn(new Constraint<>(20)); - - //BASAL 20% 20 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL 20% 20"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To start basal 20% for 20 min reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Temp basal 20% for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.getMessages().get(3).getText()); - - //BASAL a - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL a"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL a", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //BASAL 1 0 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL 1 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL 1 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyBasalConstraints(any(), any())).thenReturn(new Constraint<>(1d)); - - //BASAL 1 20 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BASAL 1 20"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BASAL 1 20", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To start basal 1.00U/h for 20 min reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Temp basal 1.00U/h for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.getMessages().get(3).getText()); - - } - - @Test - public void processExtendedTest() { - Sms sms; - - //EXTENDED - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "EXTENDED"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //EXTENDED - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "EXTENDED"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //EXTENDED CANCEL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "EXTENDED CANCEL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("EXTENDED CANCEL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To stop extended bolus reply with code")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Extended bolus canceled")); - - //EXTENDED a% - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "EXTENDED a%"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("EXTENDED a%", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); - - //EXTENDED 1 0 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "EXTENDED 1 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("EXTENDED 1 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //EXTENDED 1 20 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "EXTENDED 1 20"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("EXTENDED 1 20", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To start extended bolus 1.00U for 20 min reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Extended bolus 1.00U for 20 min started successfully\nnull\nVirtual Pump", smsCommunicatorPlugin.getMessages().get(3).getText()); - } - - @Test - public void processBolusTest() { - Sms sms; - - //BOLUS - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //BOLUS - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); - - when(DateUtil.now()).thenReturn(1000L); - when(SP.getLong(R.string.key_smscommunicator_remotebolusmindistance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L); - //BOLUS 1 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS 1"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(0d)); - - when(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L); - - //BOLUS 0 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //BOLUS a - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS a"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS a", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); - - when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); - - //BOLUS 1 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS 1"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To deliver bolus 1.00U reply with code")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Bolus 1.00U delivered successfully")); - - //BOLUS 1 (Suspended pump) - smsCommunicatorPlugin.setLastRemoteBolusTime(0); - when(virtualPumpPlugin.isSuspended()).thenReturn(true); - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS 1"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Pump suspended", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(virtualPumpPlugin.isSuspended()).thenReturn(false); - - //BOLUS 1 a - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS 1 a"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS 1 a", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //BOLUS 1 MEAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "BOLUS 1 MEAL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("BOLUS 1 MEAL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To deliver meal bolus 1.00U reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Meal Bolus 1.00U delivered successfully\nVirtual Pump\nTarget 5.0 for 45 minutes", smsCommunicatorPlugin.getMessages().get(3).getText()); - } - - @Test - public void processCalTest() { - Sms sms; - - //CAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CAL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CAL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //CAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CAL"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CAL", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - //CAL 0 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CAL 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CAL 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(XdripCalibrations.sendIntent(any())).thenReturn(true); - //CAL 1 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CAL 1"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CAL 1", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To send calibration 1.00 reply with code")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertEquals("Calibration sent. Receiving must be enabled in xDrip.", smsCommunicatorPlugin.getMessages().get(3).getText()); - } - - @Test - public void processCarbsTest() { - Sms sms; - - when(DateUtil.now()).thenReturn(1000000L); - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false); - //CAL - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true); - - //CARBS - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(new Constraint<>(0)); - - //CARBS 0 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS 0"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - - when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(new Constraint<>(1)); - - //CARBS 1 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS 1"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS 1", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To enter 1g at")); - String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().startsWith("Carbs 1g entered successfully")); - - //CARBS 1 a - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS 1 a"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS 1 a", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Wrong format")); - - //CARBS 1 00 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS 1 00"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS 1 00", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Wrong format")); - - //CARBS 1 12:01 - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS 1 12:01"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS 1 12:01", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To enter 1g at 12:01PM reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().startsWith("Carbs 1g entered successfully")); - - //CARBS 1 3:01AM - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - sms = new Sms("1234", "CARBS 1 3:01AM"); - smsCommunicatorPlugin.processSms(sms); - Assert.assertEquals("CARBS 1 3:01AM", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To enter 1g at 03:01AM reply with code")); - passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode(); - smsCommunicatorPlugin.processSms(new Sms("1234", passCode)); - Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText()); - Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().startsWith("Carbs 1g entered successfully")); - } - - @Test - public void sendNotificationToAllNumbers() { - smsCommunicatorPlugin.setMessages(new ArrayList<>()); - smsCommunicatorPlugin.sendNotificationToAllNumbers("abc"); - Assert.assertEquals("abc", smsCommunicatorPlugin.getMessages().get(0).getText()); - Assert.assertEquals("abc", smsCommunicatorPlugin.getMessages().get(1).getText()); - } - - @Before - public void prepareTests() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); - AAPSMocker.mockStrings(); - AAPSMocker.mockProfileFunctions(); - AAPSMocker.mockTreatmentPlugin(); - AAPSMocker.mockTreatmentService(); - AAPSMocker.mockIobCobCalculatorPlugin(); - AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockCommandQueue(); - AAPSMocker.mockNSUpload(); - ConstraintChecker constraintChecker = AAPSMocker.mockConstraintsChecker(); - - BgReading reading = new BgReading(); - reading.value = 100; - List bgList = new ArrayList<>(); - bgList.add(reading); - PowerMockito.when(IobCobCalculatorPlugin.getPlugin().getBgReadings()).thenReturn(bgList); - PowerMockito.when(IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB")).thenReturn(new CobInfo(10d, 2d)); - - mockStatic(XdripCalibrations.class); - spy(DateUtil.class); - mockStatic(SmsManager.class); - SmsManager smsManager = mock(SmsManager.class); - when(SmsManager.getDefault()).thenReturn(smsManager); - - when(SP.getString(R.string.key_smscommunicator_allowednumbers, "")).thenReturn("1234;5678"); - Lazy insulinOrefRapidActingPlugin = InsulinOrefRapidActingPlugin::new; - ConfigBuilderPlugin configBuilderPlugin = new ConfigBuilderPlugin(insulinOrefRapidActingPlugin); - ResourceHelperImplementation resourceHelperImplementation = mock(ResourceHelperImplementation.class); - smsCommunicatorPlugin = new SmsCommunicatorPlugin(configBuilderPlugin, resourceHelperImplementation, constraintChecker); - smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true); - - mockStatic(LoopPlugin.class); - loopPlugin = mock(LoopPlugin.class); - when(LoopPlugin.getPlugin()).thenReturn(loopPlugin); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(1); - callback.result = new PumpEnactResult().success(true); - callback.run(); - return null; - }).when(AAPSMocker.queue).cancelTempBasal(anyBoolean(), any(Callback.class)); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(0); - callback.result = new PumpEnactResult().success(true); - callback.run(); - return null; - }).when(AAPSMocker.queue).cancelExtended(any(Callback.class)); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(1); - callback.result = new PumpEnactResult().success(true); - callback.run(); - return null; - }).when(AAPSMocker.queue).readStatus(anyString(), any(Callback.class)); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(1); - callback.result = new PumpEnactResult().success(true).bolusDelivered(1); - callback.run(); - return null; - }).when(AAPSMocker.queue).bolus(any(DetailedBolusInfo.class), any(Callback.class)); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(4); - callback.result = new PumpEnactResult().success(true).isPercent(true).percent(invocation.getArgument(0)).duration(invocation.getArgument(1)); - callback.run(); - return null; - }).when(AAPSMocker.queue).tempBasalPercent(anyInt(), anyInt(), anyBoolean(), any(), any(Callback.class)); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(4); - callback.result = new PumpEnactResult().success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1)); - callback.run(); - return null; - }).when(AAPSMocker.queue).tempBasalAbsolute(anyDouble(), anyInt(), anyBoolean(), any(), any(Callback.class)); - - Mockito.doAnswer(invocation -> { - Callback callback = invocation.getArgument(2); - callback.result = new PumpEnactResult().success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1)); - callback.run(); - return null; - }).when(AAPSMocker.queue).extendedBolus(anyDouble(), anyInt(), any(Callback.class)); - - virtualPumpPlugin = mock(VirtualPumpPlugin.class); - when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(virtualPumpPlugin); - when(virtualPumpPlugin.shortStatus(anyBoolean())).thenReturn("Virtual Pump"); - when(virtualPumpPlugin.isSuspended()).thenReturn(false); - } - -} diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt new file mode 100644 index 0000000000..5180688868 --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -0,0 +1,1006 @@ +package info.nightscout.androidaps.plugins.general.smsCommunicator + +import android.telephony.SmsManager +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector +import info.AAPSMocker +import info.TestBase +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.PumpEnactResult +import info.nightscout.androidaps.db.BgReading +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin +import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin +import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin +import info.nightscout.androidaps.plugins.treatments.TreatmentService +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.DefaultValueHelper +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.XdripCalibrations +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.Mockito.`when` +import org.mockito.invocation.InvocationOnMock +import org.mockito.stubbing.Answer +import org.powermock.api.mockito.PowerMockito +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner +import java.util.* + +@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(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() { + + @Mock lateinit var aapsLogger: AAPSLogger + @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var sp: SP + @Mock lateinit var constraintChecker: ConstraintChecker + lateinit var rxBus: RxBusWrapper + @Mock lateinit var profileFunction: ProfileFunction + @Mock lateinit var fabricPrivacy: FabricPrivacy + @Mock lateinit var activePlugin: ActivePluginProvider + @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var loopPlugin: LoopPlugin + @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin + @Mock lateinit var defaultValueHelper: DefaultValueHelper + @Mock lateinit var localProfilePlugin: LocalProfilePlugin + @Mock lateinit var treatmentsPlugin: TreatmentsPlugin + @Mock lateinit var treatmentService: TreatmentService + + var injector: HasAndroidInjector = HasAndroidInjector { + AndroidInjector { + if (it is PumpEnactResult) { + it.aapsLogger = aapsLogger + it.resourceHelper = resourceHelper + } + if (it is BgReading) { + it.aapsLogger = aapsLogger + it.defaultValueHelper = defaultValueHelper + it.resourceHelper = resourceHelper + it.profileFunction = profileFunction + } + if (it is AuthRequest) { + it.aapsLogger = aapsLogger + it.smsCommunicatorPlugin = smsCommunicatorPlugin + it.resourceHelper = resourceHelper + } + if (it is GlucoseStatus) { + it.aapsLogger = aapsLogger + it.iobCobCalculatorPlugin = iobCobCalculatorPlugin + } + } + } + + private lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin + private var hasBeenRun = false + + @Before fun prepareTests() { + val mainApp = AAPSMocker.mockMainApp() + `when`(mainApp.androidInjector()).thenReturn(injector.androidInjector()) + + Locale.setDefault(Locale.ENGLISH) + rxBus = RxBusWrapper() + val reading = BgReading() + reading.value = 100.0 + val bgList: MutableList = ArrayList() + bgList.add(reading) + + `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit) + `when`(iobCobCalculatorPlugin.bgReadings).thenReturn(bgList) + `when`(iobCobCalculatorPlugin.getCobInfo(false, "SMS COB")).thenReturn(CobInfo(10.0, 2.0)) + `when`(iobCobCalculatorPlugin.lastBg()).thenReturn(reading) + + PowerMockito.mockStatic(XdripCalibrations::class.java) + PowerMockito.spy(DateUtil::class.java) + PowerMockito.mockStatic(SmsManager::class.java) + val smsManager = PowerMockito.mock(SmsManager::class.java) + `when`(SmsManager.getDefault()).thenReturn(smsManager) + `when`(sp.getString(R.string.key_smscommunicator_allowednumbers, "")).thenReturn("1234;5678") + + smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculatorPlugin) + smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(1) + callback.result = PumpEnactResult(injector).success(true) + callback.run() + null + }.`when`(commandQueue).cancelTempBasal(ArgumentMatchers.anyBoolean(), ArgumentMatchers.any(Callback::class.java)) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(0) + callback.result = PumpEnactResult(injector).success(true) + callback.run() + null + }.`when`(commandQueue).cancelExtended(ArgumentMatchers.any(Callback::class.java)) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(1) + callback.result = PumpEnactResult(injector).success(true) + callback.run() + null + }.`when`(commandQueue).readStatus(ArgumentMatchers.anyString(), ArgumentMatchers.any(Callback::class.java)) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(1) + callback.result = PumpEnactResult(injector).success(true).bolusDelivered(1.0) + callback.run() + null + }.`when`(commandQueue).bolus(anyObject(), ArgumentMatchers.any(Callback::class.java)) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(4) + callback.result = PumpEnactResult(injector).success(true).isPercent(true).percent(invocation.getArgument(0)).duration(invocation.getArgument(1)) + callback.run() + null + }.`when`(commandQueue).tempBasalPercent(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(Callback::class.java)) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(4) + callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1)) + callback.run() + null + }.`when`(commandQueue).tempBasalAbsolute(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(Callback::class.java)) + Mockito.doAnswer { invocation: InvocationOnMock -> + val callback = invocation.getArgument(2) + callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1)) + callback.run() + null + }.`when`(commandQueue).extendedBolus(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Callback::class.java)) + + `when`(activePlugin.activePumpPlugin).thenReturn(virtualPumpPlugin) + `when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) + + `when`(virtualPumpPlugin.shortStatus(ArgumentMatchers.anyBoolean())).thenReturn("Virtual Pump") + `when`(virtualPumpPlugin.isSuspended).thenReturn(false) + + `when`(treatmentsPlugin.lastCalculationTreatments).thenReturn(IobTotal(0)) + `when`(treatmentsPlugin.lastCalculationTempBasals).thenReturn(IobTotal(0)) + `when`(treatmentsPlugin.service).thenReturn(treatmentService) + + `when`(activePlugin.activeProfileInterface).thenReturn(localProfilePlugin) + + `when`(profileFunction.getUnits()).thenReturn(Constants.MGDL) + + `when`(resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed") + `when`(resourceHelper.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.") + `when`(resourceHelper.gs(R.string.sms_iob)).thenReturn("IOB:") + `when`(resourceHelper.gs(R.string.sms_lastbg)).thenReturn("Last BG:") + `when`(resourceHelper.gs(R.string.sms_minago)).thenReturn("%1\$dmin ago") + `when`(resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed") + `when`(resourceHelper.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`(resourceHelper.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2\$s.") + `when`(resourceHelper.gs(R.string.smscommunicator_temptargetwithcode)).thenReturn("To set the Temp Target %1\$s reply with code %2\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_temptargetcancel)).thenReturn("To cancel Temp Target reply with code %1\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.") + `when`(resourceHelper.gs(R.string.smscommunicator_tt_set)).thenReturn("Target %1\$s for %2\$d minutes set successfully") + `when`(resourceHelper.gs(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully") + `when`(resourceHelper.gs(R.string.loopsuspendedfor)).thenReturn("Suspended (%1\$d m)") + `when`(resourceHelper.gs(R.string.smscommunicator_loopisdisabled)).thenReturn("Loop is disabled") + `when`(resourceHelper.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled") + `when`(resourceHelper.gs(R.string.wrongformat)).thenReturn("Wrong format") + `when`(resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled") + `when`(resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled") + `when`(resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled") + `when`(resourceHelper.gs(R.string.smscommunicator_loopresumed)).thenReturn("Loop resumed") + `when`(resourceHelper.gs(R.string.smscommunicator_wrongduration)).thenReturn("Wrong duration") + `when`(resourceHelper.gs(R.string.smscommunicator_suspendreplywithcode)).thenReturn("To suspend loop for %1\$d minutes reply with code %2\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_loopsuspended)).thenReturn("Loop suspended") + `when`(resourceHelper.gs(R.string.smscommunicator_unknowncommand)).thenReturn("Unknown command or wrong reply") + `when`(resourceHelper.gs(R.string.notconfigured)).thenReturn("Not configured") + `when`(resourceHelper.gs(R.string.smscommunicator_profilereplywithcode)).thenReturn("To switch profile to %1\$s %2\$d%% reply with code %3\$s") + `when`(resourceHelper.gs(R.string.profileswitchcreated)).thenReturn("Profile switch created") + `when`(resourceHelper.gs(R.string.smscommunicator_basalstopreplywithcode)).thenReturn("To stop temp basal reply with code %1\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode)).thenReturn("To start basal %1\$d%% for %2\$d min reply with code %3\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent)).thenReturn("Temp basal %1\$d%% for %2\$d min started successfully") + `when`(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode)).thenReturn("To start basal %1$.2fU/h for %2\$d min reply with code %3\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_tempbasalset)).thenReturn("Temp basal %1$.2fU/h for %2\$d min started successfully") + `when`(resourceHelper.gs(R.string.smscommunicator_extendedstopreplywithcode)).thenReturn("To stop extended bolus reply with code %1\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_extendedcanceled)).thenReturn("Extended bolus canceled") + `when`(resourceHelper.gs(R.string.smscommunicator_extendedreplywithcode)).thenReturn("To start extended bolus %1$.2fU for %2\$d min reply with code %3\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_extendedset)).thenReturn("Extended bolus %1$.2fU for %2\$d min started successfully") + `when`(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode)).thenReturn("To deliver bolus %1$.2fU reply with code %2\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_bolusdelivered)).thenReturn("Bolus %1$.2fU delivered successfully") + `when`(resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed)).thenReturn("Remote bolus not available. Try again later.") + `when`(resourceHelper.gs(R.string.smscommunicator_calibrationreplywithcode)).thenReturn("To send calibration %1$.2f reply with code %2\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip.") + `when`(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode)).thenReturn("To enter %1\$dg at %2\$s reply with code %3\$s") + `when`(resourceHelper.gs(R.string.smscommunicator_carbsset)).thenReturn("Carbs %1\$dg entered successfully") + `when`(resourceHelper.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet") + `when`(resourceHelper.gs(R.string.pumpsuspended)).thenReturn("Pump suspended") + `when`(resourceHelper.gs(R.string.sms_delta)).thenReturn("Delta:") + `when`(resourceHelper.gs(R.string.sms_bolus)).thenReturn("Bolus:") + `when`(resourceHelper.gs(R.string.sms_basal)).thenReturn("Basal:") + `when`(resourceHelper.gs(R.string.cob)).thenReturn("COB") + `when`(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered)).thenReturn("Meal Bolus %1\$.2fU delivered successfully") + `when`(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered_tt)).thenReturn("Target %1\$s for %2\$d minutes") + `when`(resourceHelper.gs(R.string.sms_actualbg)).thenReturn("BG:") + `when`(resourceHelper.gs(R.string.sms_lastbg)).thenReturn("Last BG:") + } + + @Test + fun processSettingsTest() { + // called from constructor + Assert.assertEquals("1234", smsCommunicatorPlugin.allowedNumbers.get(0)) + Assert.assertEquals("5678", smsCommunicatorPlugin.allowedNumbers.get(1)) + Assert.assertEquals(2, smsCommunicatorPlugin.allowedNumbers.size) + } + + @Test + fun isCommandTest() { + Assert.assertTrue(smsCommunicatorPlugin.isCommand("BOLUS", "")) + smsCommunicatorPlugin.messageToConfirm = null + Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "")) + smsCommunicatorPlugin.messageToConfirm = AuthRequest(injector, Sms("1234", "ddd"), "RequestText", "ccode", object : SmsAction() { + override fun run() {} + }) + Assert.assertTrue(smsCommunicatorPlugin.isCommand("BLB", "1234")) + Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "2345")) + smsCommunicatorPlugin.messageToConfirm = null + } + + @Test fun _isAllowedNumberTest() { + Assert.assertTrue(smsCommunicatorPlugin.isAllowedNumber("5678")) + Assert.assertFalse(smsCommunicatorPlugin.isAllowedNumber("56")) + } + + @Test fun processSmsTest() { + var sms: Sms + + // SMS from not allowed number should be ignored + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("12", "aText") + smsCommunicatorPlugin.processSms(sms) + Assert.assertTrue(sms.ignored) + Assert.assertEquals("aText", smsCommunicatorPlugin.messages[0].text) + + //UNKNOWN + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "UNKNOWN") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("UNKNOWN", smsCommunicatorPlugin.messages[0].text) + + //BG + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BG") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BG", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("IOB:")) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Last BG: 100")) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("COB: 10(2)g")) + + // LOOP : test remote control disabled + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP STATUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Remote command is not allowed")) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //LOOP STATUS : disabled + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP STATUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.messages[1].text) + + //LOOP STATUS : suspended + PowerMockito.`when`(loopPlugin.minutesToEndOfSuspend()).thenReturn(10) + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(true) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP STATUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Suspended (10 m)", smsCommunicatorPlugin.messages[1].text) + + //LOOP STATUS : enabled + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP STATUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.messages[1].text) + + //LOOP : wrong format + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //LOOP DISABLE : already disabled + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP DISABLE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.messages[1].text) + + //LOOP DISABLE : from enabled + hasBeenRun = false + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.doAnswer(Answer { invocation: InvocationOnMock? -> + hasBeenRun = true + null + } as Answer<*>).`when`(loopPlugin).setPluginEnabled(PluginType.LOOP, false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP DISABLE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop has been disabled Temp basal canceled", smsCommunicatorPlugin.messages[1].text) + Assert.assertTrue(hasBeenRun) + + //LOOP ENABLE : already enabled + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP ENABLE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.messages[1].text) + + //LOOP ENABLE : from disabled + hasBeenRun = false + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false) + PowerMockito.doAnswer(Answer { invocation: InvocationOnMock? -> + hasBeenRun = true + null + } as Answer<*>).`when`(loopPlugin).setPluginEnabled(PluginType.LOOP, true) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP ENABLE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop has been enabled", smsCommunicatorPlugin.messages[1].text) + Assert.assertTrue(hasBeenRun) + + //LOOP RESUME : already enabled + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP RESUME") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP RESUME", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Loop resumed", smsCommunicatorPlugin.messages[1].text) + + //LOOP SUSPEND 1 2: wrong format + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP SUSPEND 1 2") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP SUSPEND 1 2", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //LOOP SUSPEND 0 : wrong duration + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP SUSPEND 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP SUSPEND 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong duration", smsCommunicatorPlugin.messages[1].text) + + //LOOP SUSPEND 100 : suspend for 100 min + correct answer + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP SUSPEND 100") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP SUSPEND 100", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To suspend loop for 100 minutes reply with code ")) + var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Loop suspended Temp basal canceled", smsCommunicatorPlugin.messages[3].text) + + //LOOP SUSPEND 200 : limit to 180 min + wrong answer + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP SUSPEND 200") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP SUSPEND 200", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To suspend loop for 180 minutes reply with code ")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + // ignore from other number + smsCommunicatorPlugin.processSms(Sms("5678", passCode)) + smsCommunicatorPlugin.processSms(Sms("1234", "XXXX")) + Assert.assertEquals("XXXX", smsCommunicatorPlugin.messages[3].text) + Assert.assertEquals("Wrong code. Command cancelled.", smsCommunicatorPlugin.messages[4].text) + //then correct code should not work + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[5].text) + Assert.assertEquals(6, smsCommunicatorPlugin.messages.size.toLong()) // processed as common message + + //LOOP BLABLA + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "LOOP BLABLA") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("LOOP BLABLA", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //TREATMENTS REFRESH + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "TREATMENTS REFRESH") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("TREATMENTS REFRESH", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("TREATMENTS REFRESH")) + + //TREATMENTS BLA BLA + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "TREATMENTS BLA BLA") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("TREATMENTS BLA BLA", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //TREATMENTS BLABLA + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "TREATMENTS BLABLA") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("TREATMENTS BLABLA", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //NSCLIENT RESTART + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "NSCLIENT RESTART") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("NSCLIENT RESTART", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("NSCLIENT RESTART")) + + //NSCLIENT BLA BLA + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "NSCLIENT BLA BLA") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("NSCLIENT BLA BLA", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //NSCLIENT BLABLA + PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "NSCLIENT BLABLA") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("NSCLIENT BLABLA", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //PUMP + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PUMP") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PUMP", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Virtual Pump", smsCommunicatorPlugin.messages[1].text) + + //HELP + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "HELP") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("HELP", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("PUMP")) + + //HELP PUMP + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "HELP PUMP") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("HELP PUMP", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("PUMP")) + + //SMS : wrong format + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "SMS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("SMS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //SMS STOP + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "SMS DISABLE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("SMS DISABLE", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To disable the SMS Remote Service reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.")) + + //TARGET : wrong format + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "TARGET") + smsCommunicatorPlugin.processSms(sms) + Assert.assertFalse(sms.ignored) + Assert.assertEquals("TARGET", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //TARGET MEAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "TARGET MEAL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("TARGET MEAL", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To set the Temp Target")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("set successfully")) + + //TARGET STOP/CANCEL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "TARGET STOP") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("TARGET STOP", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To cancel Temp Target reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Temp Target canceled successfully")) + } + + @Test fun processProfileTest() { + var sms: Sms + + //PROFILE + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //PROFILE + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //PROFILE LIST (no profile defined) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE LIST") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Not configured", smsCommunicatorPlugin.messages[1].text) + + `when`(localProfilePlugin.profile).thenReturn(getValidProfileStore()) + `when`(profileFunction.getProfileName()).thenReturn(TESTPROFILENAME) + + //PROFILE STATUS + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE STATUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE STATUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals(TESTPROFILENAME, smsCommunicatorPlugin.messages[1].text) + + //PROFILE LIST + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE LIST") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("1. " + TESTPROFILENAME, smsCommunicatorPlugin.messages[1].text) + + //PROFILE 2 (non existing) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE 2") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE 2", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //PROFILE 1 0(wrong percentage) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE 1 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE 1 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //PROFILE 0(wrong index) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //PROFILE 1(OK) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE 1") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE 1", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To switch profile to someProfile 100% reply with code")) + + //PROFILE 1 90(OK) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "PROFILE 1 90") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("PROFILE 1 90", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To switch profile to someProfile 90% reply with code")) + val passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Profile switch created", smsCommunicatorPlugin.messages[3].text) + } + + @Test fun processBasalTest() { + var sms: Sms + + //BASAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //BASAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //BASAL CANCEL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL CANCEL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL CANCEL", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To stop temp basal reply with code")) + var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Temp basal canceled")) + + `when`(profileFunction.getProfile()).thenReturn(validProfile) + //BASAL a% + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL a%") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL a%", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //BASAL 10% 0 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL 10% 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20)) + + //BASAL 20% 20 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL 20% 20") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To start basal 20% for 20 min reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Temp basal 20% for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages[3].text) + + //BASAL a + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL a") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL a", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //BASAL 1 0 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL 1 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL 1 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(Constraint(1.0)) + + //BASAL 1 20 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BASAL 1 20") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BASAL 1 20", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To start basal 1.00U/h for 20 min reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Temp basal 1.00U/h for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages[3].text) + } + + @Test fun processExtendedTest() { + var sms: Sms + + //EXTENDED + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "EXTENDED") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //EXTENDED + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "EXTENDED") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //EXTENDED CANCEL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "EXTENDED CANCEL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("EXTENDED CANCEL", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To stop extended bolus reply with code")) + var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Extended bolus canceled")) + + //EXTENDED a% + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "EXTENDED a%") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("EXTENDED a%", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + + //EXTENDED 1 0 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "EXTENDED 1 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("EXTENDED 1 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //EXTENDED 1 20 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "EXTENDED 1 20") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("EXTENDED 1 20", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To start extended bolus 1.00U for 20 min reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Extended bolus 1.00U for 20 min started successfully\nnull\nVirtual Pump", smsCommunicatorPlugin.messages[3].text) + } + + @Test fun processBolusTest() { + var sms: Sms + + //BOLUS + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //BOLUS + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + PowerMockito.`when`(DateUtil.now()).thenReturn(1000L) + `when`(sp.getLong(R.string.key_smscommunicator_remotebolusmindistance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L) + //BOLUS 1 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS 1") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + PowerMockito.`when`(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L) + + //BOLUS 0 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //BOLUS a + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS a") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS a", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + + //BOLUS 1 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS 1") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To deliver bolus 1.00U reply with code")) + var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.contains("Bolus 1.00U delivered successfully")) + + //BOLUS 1 (Suspended pump) + smsCommunicatorPlugin.lastRemoteBolusTime = 0 + PowerMockito.`when`(virtualPumpPlugin.isSuspended).thenReturn(true) + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS 1") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Pump suspended", smsCommunicatorPlugin.messages[1].text) + PowerMockito.`when`(virtualPumpPlugin.isSuspended).thenReturn(false) + + //BOLUS 1 a + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS 1 a") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS 1 a", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + `when`(profileFunction.getProfile()).thenReturn(validProfile) + //BOLUS 1 MEAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "BOLUS 1 MEAL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("BOLUS 1 MEAL", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To deliver meal bolus 1.00U reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Meal Bolus 1.00U delivered successfully\nVirtual Pump\nTarget 5.0 for 45 minutes", smsCommunicatorPlugin.messages[3].text) + } + + @Test fun processCalTest() { + var sms: Sms + + //CAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CAL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CAL", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //CAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CAL") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CAL", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + + //CAL 0 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CAL 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CAL 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + PowerMockito.`when`(XdripCalibrations.sendIntent(anyObject())).thenReturn(true) + //CAL 1 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CAL 1") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CAL 1", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To send calibration 1.00 reply with code")) + val passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertEquals("Calibration sent. Receiving must be enabled in xDrip.", smsCommunicatorPlugin.messages[3].text) + } + + @Test fun processCarbsTest() { + var sms: Sms + PowerMockito.`when`(DateUtil.now()).thenReturn(1000000L) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false) + //CAL + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages[1].text) + `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true) + + //CARBS + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0)) + + //CARBS 0 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS 0") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) + `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1)) + + //CARBS 1 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS 1") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS 1", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enter 1g at")) + var passCode: String = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) + + //CARBS 1 a + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS 1 a") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS 1 a", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format")) + + //CARBS 1 00 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS 1 00") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS 1 00", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format")) + + //CARBS 1 12:01 + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS 1 12:01") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS 1 12:01", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enter 1g at 12:01PM reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) + + //CARBS 1 3:01AM + smsCommunicatorPlugin.messages = ArrayList() + sms = Sms("1234", "CARBS 1 3:01AM") + smsCommunicatorPlugin.processSms(sms) + Assert.assertEquals("CARBS 1 3:01AM", smsCommunicatorPlugin.messages[0].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To enter 1g at 03:01AM reply with code")) + passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!! + smsCommunicatorPlugin.processSms(Sms("1234", passCode)) + Assert.assertEquals(passCode, smsCommunicatorPlugin.messages[2].text) + Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) + } + + @Test fun sendNotificationToAllNumbers() { + smsCommunicatorPlugin.messages = ArrayList() + smsCommunicatorPlugin.sendNotificationToAllNumbers("abc") + Assert.assertEquals("abc", smsCommunicatorPlugin.messages[0].text) + Assert.assertEquals("abc", smsCommunicatorPlugin.messages[1].text) + } +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt index 3974fb86d8..48a9444094 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt @@ -47,7 +47,7 @@ class DanaRSPluginTest : DanaRSTestBase() { danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPump.maxBasal = 0.8 val c = Constraint(Constants.REALLYHIGHBASALRATE) - danaRSPlugin.applyBasalConstraints(c, AAPSMocker.getValidProfile()) + danaRSPlugin.applyBasalConstraints(c, validProfile) Assert.assertEquals(java.lang.Double.valueOf(0.8), c.value(), 0.0001) Assert.assertEquals("DanaRS: limitingbasalratio", c.getReasons(aapsLogger)) Assert.assertEquals("DanaRS: limitingbasalratio", c.getMostLimitedReasons(aapsLogger)) @@ -59,7 +59,7 @@ class DanaRSPluginTest : DanaRSTestBase() { danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPump.maxBasal = 0.8 val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) - danaRSPlugin.applyBasalPercentConstraints(c, AAPSMocker.getValidProfile()) + danaRSPlugin.applyBasalPercentConstraints(c, validProfile) Assert.assertEquals(200, c.value()) Assert.assertEquals("DanaRS: limitingpercentrate", c.getReasons(aapsLogger)) Assert.assertEquals("DanaRS: limitingpercentrate", c.getMostLimitedReasons(aapsLogger)) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt index 98625f55ea..72bce89cc1 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.danaRS.comm +import dagger.android.HasAndroidInjector import info.TestBase import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump @@ -11,6 +12,7 @@ open class DanaRSTestBase : TestBase() { @Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var sp: SP + @Mock lateinit var injector: HasAndroidInjector lateinit var danaRPump: DanaRPump @@ -43,6 +45,6 @@ open class DanaRSTestBase : TestBase() { @Before fun setup() { - danaRPump = DanaRPump(aapsLogger, sp) + danaRPump = DanaRPump(aapsLogger, sp, injector) } } \ No newline at end of file