SmsCommunicatorPluginTest

This commit is contained in:
Milos Kozak 2020-03-10 18:58:27 +01:00
parent 5d745a2d9b
commit 005d8e89ce
45 changed files with 1411 additions and 1301 deletions

View file

@ -33,6 +33,7 @@ import javax.inject.Inject;
import dagger.android.AndroidInjector; import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication; import dagger.android.DaggerApplication;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
@ -132,6 +133,7 @@ public class MainApp extends DaggerApplication {
private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger) private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger)
private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger) private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger)
@Inject public HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject ActivityMonitor activityMonitor; @Inject ActivityMonitor activityMonitor;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;

View file

@ -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.openAPSMA.OpenAPSMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin
@ -60,6 +61,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var danaRPlugin: DanaRPlugin @Inject lateinit var danaRPlugin: DanaRPlugin
@ -235,7 +237,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
) )
if (listOf(*unitDependent).contains(pref.key)) { if (listOf(*unitDependent).contains(pref.key)) {
val editTextPref = pref as EditTextPreference 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.summary = converted
editTextPref.text = converted editTextPref.text = converted
} }

View file

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

View file

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

View file

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

View file

@ -1,13 +1,17 @@
package info.nightscout.androidaps.data.defaultProfile package info.nightscout.androidaps.data.defaultProfile
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.Round
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.util.* import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DefaultProfile @Inject constructor(val injector: HasAndroidInjector) {
class DefaultProfile {
var oneToFive: TreeMap<Double, Array<Double>> = TreeMap() var oneToFive: TreeMap<Double, Array<Double>> = TreeMap()
var sixToEleven: TreeMap<Double, Array<Double>> = TreeMap() var sixToEleven: TreeMap<Double, Array<Double>> = TreeMap()
var twelveToSeventeen: TreeMap<Double, Array<Double>> = TreeMap() var twelveToSeventeen: TreeMap<Double, Array<Double>> = TreeMap()
@ -18,24 +22,24 @@ class DefaultProfile {
if (age >= 1 && age < 6) { if (age >= 1 && age < 6) {
val _tdd = if (tdd == 0.0) 0.6 * weight else tdd val _tdd = if (tdd == 0.0) 0.6 * weight else tdd
closest(oneToFive, _tdd * 0.3)?.let { array -> profile.put("basal", arrayToJson(array)) } closest(oneToFive, _tdd * 0.3)?.let { array -> profile.put("basal", arrayToJson(array)) }
val ic = Round.roundTo(250.0 / _tdd, 1.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))) 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) 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) { } else if (age >= 6 && age < 12) {
val _tdd = if (tdd == 0.0) 0.8 * weight else tdd val _tdd = if (tdd == 0.0) 0.8 * weight else tdd
closest(sixToEleven, _tdd * 0.4)?.let { array -> profile.put("basal", arrayToJson(array)) } closest(sixToEleven, _tdd * 0.4)?.let { array -> profile.put("basal", arrayToJson(array)) }
val ic = Round.roundTo(375.0 / _tdd, 1.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))) 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) 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) { } else if (age >= 12 && age < 17) {
val _tdd = if (tdd == 0.0) 1.0 * weight else tdd val _tdd = if (tdd == 0.0) 1.0 * weight else tdd
closest(twelveToSeventeen, _tdd * 0.5)?.let { array -> profile.put("basal", arrayToJson(array)) } closest(twelveToSeventeen, _tdd * 0.5)?.let { array -> profile.put("basal", arrayToJson(array)) }
val ic = Round.roundTo(500.0 / _tdd, 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))) 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) 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) { } else if (age >= 18) {
} }
@ -45,7 +49,7 @@ class DefaultProfile {
profile.put("timezone", TimeZone.getDefault().getID()) 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_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)))) 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 { init {

View file

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

View file

@ -10,7 +10,6 @@ import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@ -97,7 +96,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
public Profile getProfileObject() { public Profile getProfileObject() {
if (profile == null) if (profile == null)
try { try {
profile = new Profile(new JSONObject(profileJson), percentage, timeshift); profile = new Profile(MainApp.instance().injector, new JSONObject(profileJson), percentage, timeshift);
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
log.error("Unhandled exception", profileJson); log.error("Unhandled exception", profileJson);

View file

@ -5,6 +5,7 @@ import dagger.Component
import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading 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.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData 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.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.plugins.treatments.Treatment
@ -146,6 +148,9 @@ interface AppComponent : AndroidInjector<MainApp> {
fun injectAuthRequest(authRequest: AuthRequest) fun injectAuthRequest(authRequest: AuthRequest)
fun injectProfile(profile: Profile)
fun injectGlucoseStatus(glucoseStatus: GlucoseStatus)
@Component.Builder @Component.Builder
interface Builder { interface Builder {

View file

@ -8,6 +8,7 @@ import dagger.Provides
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.ProfileStore
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading 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.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData 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.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.plugins.treatments.Treatment
@ -89,7 +91,8 @@ open class AppModule {
@ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB
@ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA @ContributesAndroidInjector fun determineBasalResultMAInjector(): DetermineBasalResultMA
@ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA @ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA
@ContributesAndroidInjector fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS @ContributesAndroidInjector
fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS
@ContributesAndroidInjector fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector fun commandQueueInjector(): CommandQueue
@ContributesAndroidInjector fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector fun commandBolusInjector(): CommandBolus
@ -197,6 +200,9 @@ open class AppModule {
@ContributesAndroidInjector fun authRequestInjector(): AuthRequest @ContributesAndroidInjector fun authRequestInjector(): AuthRequest
@ContributesAndroidInjector fun profileInjector(): Profile
@ContributesAndroidInjector fun glucoseStatusInjector(): GlucoseStatus
@Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector

View file

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

View file

@ -8,6 +8,7 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.annotation.StringRes import androidx.annotation.StringRes
import com.google.common.base.Joiner import com.google.common.base.Joiner
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
@ -31,6 +32,7 @@ import java.util.*
import javax.inject.Inject import javax.inject.Inject
class CareDialog : DialogFragmentWithDate() { class CareDialog : DialogFragmentWithDate() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var mainApp: MainApp @Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @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()) ?: 0.0, profileFunction.getUnits())
val bgTextWatcher: TextWatcher = object : TextWatcher { val bgTextWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {} override fun afterTextChanged(s: Editable) {}
@ -141,7 +143,7 @@ class CareDialog : DialogFragmentWithDate() {
else -> "Manual" else -> "Manual"
} }
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) 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("glucose", actions_care_bg.value)
json.put("glucoseType", type) json.put("glucoseType", type)
} }

View file

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

View file

@ -123,7 +123,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
val duration = overview_temptarget_duration.value.toInt() val duration = overview_temptarget_duration.value.toInt()
if (target != 0.0 && duration != 0) { if (target != 0.0 && duration != 0) {
actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) 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)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration))
} else { } else {
actions.add(resourceHelper.gs(R.string.stoptemptarget)) actions.add(resourceHelper.gs(R.string.stoptemptarget))

View file

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

View file

@ -35,6 +35,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
* Created by mike on 09.06.2016. * Created by mike on 09.06.2016.
*/ */
public class APSResult { public class APSResult {
@Inject HasAndroidInjector injector;
@Inject public AAPSLogger aapsLogger; @Inject public AAPSLogger aapsLogger;
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
@Inject SP sp; @Inject SP sp;

View file

@ -123,7 +123,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS;
determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(mainApp), getInjector()); determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(mainApp), getInjector());
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePump(); PumpInterface pump = activePlugin.getActivePump();

View file

@ -122,7 +122,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
DetermineBasalAdapterMAJS determineBasalAdapterMAJS; DetermineBasalAdapterMAJS determineBasalAdapterMAJS;
determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(mainApp), getInjector()); determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(mainApp), getInjector());
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(getInjector()).getGlucoseStatusData();
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePumpPlugin(); PumpInterface pump = activePlugin.getActivePumpPlugin();

View file

@ -46,7 +46,6 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
@Singleton @Singleton
public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface {
private final HasAndroidInjector injector;
private final ConstraintChecker constraintChecker; private final ConstraintChecker constraintChecker;
private final ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
@ -84,7 +83,6 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
.description(R.string.description_smb), .description(R.string.description_smb),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
); );
this.injector = injector;
this.constraintChecker = constraintChecker; this.constraintChecker = constraintChecker;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
@ -126,9 +124,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); getAapsLogger().debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS; 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(); Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePump(); PumpInterface pump = activePlugin.getActivePump();

View file

@ -31,7 +31,7 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val glucoseStatus = GlucoseStatus.getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
if (glucoseStatus == null && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { if (glucoseStatus == null && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true return true

View file

@ -42,7 +42,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val glucoseStatus = GlucoseStatus.getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
?: return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { ?: return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
true true

View file

@ -30,7 +30,6 @@ import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
@ -40,6 +39,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import dagger.android.support.DaggerDialogFragment; import dagger.android.support.DaggerDialogFragment;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -69,6 +69,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
@Inject HasAndroidInjector injector;
@Inject DefaultValueHelper defaultValueHelper; @Inject DefaultValueHelper defaultValueHelper;
@Inject ProfileFunction profileFunction; @Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@ -193,7 +194,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O
profileSpinner.setSelection(p); 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 // temp target
final List<String> reasonList = Lists.newArrayList( final List<String> reasonList = Lists.newArrayList(
@ -278,7 +279,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O
} }
sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { 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) { if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) {
editBg.setValue(savedInstanceState.getDouble("editBg")); editBg.setValue(savedInstanceState.getDouble("editBg"));
} else { } else {

View file

@ -125,7 +125,7 @@ class DataBroadcastPlugin @Inject constructor(
private fun bgStatus(bundle: Bundle) { private fun bgStatus(bundle: Bundle) {
val lastBG: BgReading = iobCobCalculatorPlugin.lastBg() ?: return 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.putDouble("glucoseMgdl", lastBG.value) // last BG in mgdl
bundle.putLong("glucoseTimeStamp", lastBG.date) // timestamp bundle.putLong("glucoseTimeStamp", lastBG.date) // timestamp

View file

@ -30,6 +30,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.DaggerService; import dagger.android.DaggerService;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -78,6 +79,7 @@ import io.socket.client.Socket;
import io.socket.emitter.Emitter; import io.socket.emitter.Emitter;
public class NSClientService extends DaggerService { public class NSClientService extends DaggerService {
@Inject HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject NSSettingsStatus nsSettingsStatus; @Inject NSSettingsStatus nsSettingsStatus;
@Inject NSDeviceStatus nsDeviceStatus; @Inject NSDeviceStatus nsDeviceStatus;
@ -524,7 +526,7 @@ public class NSClientService extends DaggerService {
JSONArray profiles = data.getJSONArray("profiles"); JSONArray profiles = data.getJSONArray("profiles");
if (profiles.length() > 0) { if (profiles.length() > 0) {
JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1); JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1);
profileStore = new ProfileStore(profile); profileStore = new ProfileStore(injector, profile);
broadcastProfile = true; broadcastProfile = true;
rxBus.send(new EventNSClientNewLog("PROFILE", "profile received")); rxBus.send(new EventNSClientNewLog("PROFILE", "profile received"));
} }

View file

@ -1072,7 +1072,7 @@ public class OverviewFragment extends DaggerFragment implements View.OnClickList
arrowView.setText(lastBG.directionToSymbol()); arrowView.setText(lastBG.directionToSymbol());
bgView.setTextColor(color); bgView.setTextColor(color);
arrowView.setTextColor(color); arrowView.setTextColor(color);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(injector).getGlucoseStatusData();
if (glucoseStatus != null) { if (glucoseStatus != null) {
if (deltaView != null) if (deltaView != null)
deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units); deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);

View file

@ -138,7 +138,7 @@ class PersistentNotificationPlugin @Inject constructor(
var line1_aa: String var line1_aa: String
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
val lastBG = iobCobCalculatorPlugin.lastBg() val lastBG = iobCobCalculatorPlugin.lastBg()
val glucoseStatus = GlucoseStatus.getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
if (lastBG != null) { if (lastBG != null) {
line1_aa = lastBG.valueToUnitsToString(units) line1_aa = lastBG.valueToUnitsToString(units)
line1 = line1_aa line1 = line1_aa

View file

@ -70,8 +70,8 @@ class SmsCommunicatorPlugin @Inject constructor(
) { ) {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
private var allowedNumbers: MutableList<String> = ArrayList() var allowedNumbers: MutableList<String> = ArrayList()
private var messageToConfirm: AuthRequest? = null var messageToConfirm: AuthRequest? = null
var lastRemoteBolusTime: Long = 0 var lastRemoteBolusTime: Long = 0
var messages = ArrayList<Sms>() var messages = ArrayList<Sms>()
@ -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 var found = false
commands.forEach { (k, _) -> commands.forEach { (k, _) ->
if (k == command) found = true if (k == command) found = true
@ -167,7 +167,7 @@ class SmsCommunicatorPlugin @Inject constructor(
return found || messageToConfirm?.requester?.phoneNumber == number return found || messageToConfirm?.requester?.phoneNumber == number
} }
private fun isAllowedNumber(number: String): Boolean { fun isAllowedNumber(number: String): Boolean {
for (num in allowedNumbers) { for (num in allowedNumbers) {
if (num == number) return true 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)) { if (!isEnabled(PluginType.GENERAL)) {
aapsLogger.debug(LTag.SMS, "Ignoring SMS. Plugin disabled.") aapsLogger.debug(LTag.SMS, "Ignoring SMS. Plugin disabled.")
return return
@ -284,7 +284,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val agoMin = (agoMsec / 60.0 / 1000.0).toInt() 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) + ", " 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 + ", " 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() activePlugin.activeTreatments.updateTotalIOBTreatments()
val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round()
@ -612,7 +612,7 @@ class SmsCommunicatorPlugin @Inject constructor(
if (result.success) { if (result.success) {
var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration)
if (Config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) if (Config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePumpPlugin?.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed)
@ -784,7 +784,7 @@ class SmsCommunicatorPlugin @Inject constructor(
var ttDuration = sp.getInt(keyDuration, defaultTargetDuration) var ttDuration = sp.getInt(keyDuration, defaultTargetDuration)
ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration
var tt = sp.getDouble(keyTarget, if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL) 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 tt = if (tt > 0) tt else if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL
val tempTarget = TempTarget() val tempTarget = TempTarget()
.date(System.currentTimeMillis()) .date(System.currentTimeMillis())

View file

@ -28,6 +28,7 @@ import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import dagger.android.AndroidInjection; import dagger.android.AndroidInjection;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -58,6 +59,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
@Inject public HasAndroidInjector injector;
@Inject public AAPSLogger aapsLogger; @Inject public AAPSLogger aapsLogger;
@Inject public WearPlugin wearPlugin; @Inject public WearPlugin wearPlugin;
@Inject public ResourceHelper resourceHelper; @Inject public ResourceHelper resourceHelper;
@ -274,7 +276,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
BgReading lastBG = iobCobCalculatorPlugin.lastBg(); BgReading lastBG = iobCobCalculatorPlugin.lastBg();
// Log.d(TAG, logPrefix + "LastBg=" + lastBG); // Log.d(TAG, logPrefix + "LastBg=" + lastBG);
if (lastBG != null) { if (lastBG != null) {
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = new GlucoseStatus(injector).getGlucoseStatusData();
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect(); googleApiConnect();
@ -380,7 +382,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
if (last_bg == null) return; if (last_bg == null) return;
List<BgReading> graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true); List<BgReading> graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(true); GlucoseStatus glucoseStatus = new GlucoseStatus(injector).getGlucoseStatusData(true);
if (!graph_bgs.isEmpty()) { if (!graph_bgs.isEmpty()) {
DataMap entries = dataMapSingleBG(last_bg, glucoseStatus); DataMap entries = dataMapSingleBG(last_bg, glucoseStatus);

View file

@ -2,15 +2,15 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.Round;
@ -20,7 +20,11 @@ import info.nightscout.androidaps.utils.Round;
*/ */
public class GlucoseStatus { 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 glucose = 0d;
public double delta = 0d; public double delta = 0d;
public double avgdelta = 0d; public double avgdelta = 0d;
@ -36,7 +40,9 @@ public class GlucoseStatus {
"Long avg. delta: " + DecimalFormatter.to2Decimal(long_avgdelta) + " mg/dl"; "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() { public GlucoseStatus round() {
@ -50,36 +56,33 @@ public class GlucoseStatus {
@Nullable @Nullable
public static GlucoseStatus getGlucoseStatusData() { public GlucoseStatus getGlucoseStatusData() {
return getGlucoseStatusData(false); return getGlucoseStatusData(false);
} }
@Nullable @Nullable
public static GlucoseStatus getGlucoseStatusData(boolean allowOldData) { public GlucoseStatus getGlucoseStatusData(boolean allowOldData) {
// load 45min // load 45min
//long fromtime = DateUtil.now() - 60 * 1000L * 45; //long fromtime = DateUtil.now() - 60 * 1000L * 45;
//List<BgReading> data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false); //List<BgReading> data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false);
synchronized (IobCobCalculatorPlugin.getPlugin().getDataLock()) { synchronized (iobCobCalculatorPlugin.getDataLock()) {
List<BgReading> data = IobCobCalculatorPlugin.getPlugin().getBgReadings(); List<BgReading> data = iobCobCalculatorPlugin.getBgReadings();
if (data == null) { if (data == null) {
if (L.isEnabled(L.GLUCOSE)) aapsLogger.debug(LTag.GLUCOSE, "data=null");
log.debug("data=null");
return null; return null;
} }
int sizeRecords = data.size(); int sizeRecords = data.size();
if (sizeRecords == 0) { if (sizeRecords == 0) {
if (L.isEnabled(L.GLUCOSE)) aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==0");
log.debug("sizeRecords==0");
return null; return null;
} }
if (data.get(0).date < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) { if (data.get(0).date < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) {
if (L.isEnabled(L.GLUCOSE)) aapsLogger.debug(LTag.GLUCOSE, "olddata");
log.debug("olddata");
return null; return null;
} }
@ -88,15 +91,14 @@ public class GlucoseStatus {
double change; double change;
if (sizeRecords == 1) { if (sizeRecords == 1) {
GlucoseStatus status = new GlucoseStatus(); GlucoseStatus status = new GlucoseStatus(injector);
status.glucose = now.value; status.glucose = now.value;
status.short_avgdelta = 0d; status.short_avgdelta = 0d;
status.delta = 0d; status.delta = 0d;
status.long_avgdelta = 0d; status.long_avgdelta = 0d;
status.avgdelta = 0d; // for OpenAPS MA status.avgdelta = 0d; // for OpenAPS MA
status.date = now_date; status.date = now_date;
if (L.isEnabled(L.GLUCOSE)) aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==1");
log.debug("sizeRecords==1");
return status.round(); return status.round();
} }
@ -120,8 +122,7 @@ public class GlucoseStatus {
change = now.value - then.value; change = now.value - then.value;
avgdelta = change / minutesago * 5; avgdelta = change / minutesago * 5;
if (L.isEnabled(L.GLUCOSE)) aapsLogger.debug(LTag.GLUCOSE, then.toString() + " minutesago=" + minutesago + " avgdelta=" + avgdelta);
log.debug(then.toString() + " minutesago=" + minutesago + " avgdelta=" + avgdelta);
// use the average of all data points in the last 2.5m for all further "now" calculations // use the average of all data points in the last 2.5m for all further "now" calculations
if (0 < minutesago && minutesago < 2.5) { 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.glucose = now.value;
status.date = now_date; status.date = now_date;
@ -161,8 +162,7 @@ public class GlucoseStatus {
status.long_avgdelta = average(long_deltas); status.long_avgdelta = average(long_deltas);
status.avgdelta = status.short_avgdelta; // for OpenAPS MA status.avgdelta = status.short_avgdelta; // for OpenAPS MA
if (L.isEnabled(L.GLUCOSE)) aapsLogger.debug(LTag.GLUCOSE, status.log());
log.debug(status.log());
return status.round(); return status.round();
} }
} }

View file

@ -428,7 +428,7 @@ class LocalProfilePlugin @Inject constructor(
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)
} }
return ProfileStore(json) return ProfileStore(injector, json)
} }
override fun getProfile(): ProfileStore? { override fun getProfile(): ProfileStore? {

View file

@ -53,7 +53,7 @@ class NSProfilePlugin @Inject constructor(
@Suppress("SpellCheckingInspection") @Suppress("SpellCheckingInspection")
val activeProfile = bundles.getString("activeprofile") val activeProfile = bundles.getString("activeprofile")
val profileString = bundles.getString("profile") val profileString = bundles.getString("profile")
profile = ProfileStore(JSONObject(profileString)) profile = ProfileStore(injector, JSONObject(profileString))
storeNSProfile() storeNSProfile()
if (isEnabled()) { if (isEnabled()) {
rxBus.send(EventProfileStoreChanged()) rxBus.send(EventProfileStoreChanged())
@ -72,7 +72,7 @@ class NSProfilePlugin @Inject constructor(
val profileString = sp.getStringOrNull("profile", null) val profileString = sp.getStringOrNull("profile", null)
if (profileString != null) { if (profileString != null) {
aapsLogger.debug(LTag.PROFILE, "Loaded profile: $profileString") aapsLogger.debug(LTag.PROFILE, "Loaded profile: $profileString")
profile = ProfileStore(JSONObject(profileString)) profile = ProfileStore(injector, JSONObject(profileString))
} else { } else {
aapsLogger.debug(LTag.PROFILE, "Stored profile not found") aapsLogger.debug(LTag.PROFILE, "Stored profile not found")
// force restart of nsclient to fetch profile // force restart of nsclient to fetch profile

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaR package info.nightscout.androidaps.plugins.pump.danaR
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
@ -20,11 +21,13 @@ import javax.inject.Singleton
@Singleton @Singleton
class DanaRPump @Inject constructor( class DanaRPump @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP private val sp: SP,
private val injector: HasAndroidInjector
) { ) {
var lastConnection: Long = 0 var lastConnection: Long = 0
var lastSettingsRead: Long = 0 var lastSettingsRead: Long = 0
// Info // Info
var serialNumber = "" var serialNumber = ""
var shippingDate: Long = 0 var shippingDate: Long = 0
@ -38,6 +41,7 @@ class DanaRPump @Inject constructor(
var isConfigUD = false var isConfigUD = false
var isExtendedBolusEnabled = false var isExtendedBolusEnabled = false
var isEasyModeEnabled = false var isEasyModeEnabled = false
// Status // Status
var pumpSuspended = false var pumpSuspended = false
var calculatorEnabled = false var calculatorEnabled = false
@ -68,6 +72,7 @@ class DanaRPump @Inject constructor(
var extendedBolusStart: Long = 0 var extendedBolusStart: Long = 0
var extendedBolusRemainingMinutes = 0 var extendedBolusRemainingMinutes = 0
var extendedBolusDeliveredSoFar = 0.0 //RS only = 0.0 var extendedBolusDeliveredSoFar = 0.0 //RS only = 0.0
// Profile // Profile
var units = 0 var units = 0
var easyBasalMode = 0 var easyBasalMode = 0
@ -86,13 +91,17 @@ class DanaRPump @Inject constructor(
var nightCIR = 0 var nightCIR = 0
var nightCF = 0.0 var nightCF = 0.0
var activeProfile = 0 var activeProfile = 0
//var pumpProfiles = arrayOf<Array<Double>>() //var pumpProfiles = arrayOf<Array<Double>>()
var pumpProfiles : Array<Array<Double>>? = null var pumpProfiles: Array<Array<Double>>? = null
//Limits //Limits
var maxBolus = 0.0 var maxBolus = 0.0
var maxBasal = 0.0 var maxBasal = 0.0
// DanaRS specific // DanaRS specific
var rsPassword = "" var rsPassword = ""
// User settings // User settings
var timeDisplayType = 0 var timeDisplayType = 0
var buttonScrollOnOff = 0 var buttonScrollOnOff = 0
@ -106,6 +115,7 @@ class DanaRPump @Inject constructor(
var refillAmount = 0 var refillAmount = 0
var userOptionsFrompump: ByteArray? = null var userOptionsFrompump: ByteArray? = null
var initialBolusAmount = 0.0 var initialBolusAmount = 0.0
// Bolus settings // Bolus settings
var bolusCalculationOption = 0 var bolusCalculationOption = 0
var missedBolusConfig = 0 var missedBolusConfig = 0
@ -166,13 +176,13 @@ class DanaRPump @Inject constructor(
} catch (e: Exception) { } catch (e: Exception) {
return null return null
} }
return ProfileStore(json) return ProfileStore(injector, json)
} }
return null return null
} }
fun buildDanaRProfileRecord(nsProfile: Profile): Array<Double> { fun buildDanaRProfileRecord(nsProfile: Profile): Array<Double> {
val record = Array(24){ 0.0} val record = Array(24) { 0.0 }
for (hour in 0..23) { for (hour in 0..23) {
//Some values get truncated to the next lower one. //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) // -> 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_BASAL = 0x04
const val DELIVERY_EXT_BOLUS = 0x08 const val DELIVERY_EXT_BOLUS = 0x08
const val PROFILE_PREFIX = "DanaR-" const val PROFILE_PREFIX = "DanaR-"
// v2 history entries // v2 history entries
const val TEMPSTART = 1 const val TEMPSTART = 1
const val TEMPSTOP = 2 const val TEMPSTOP = 2

View file

@ -64,7 +64,7 @@ public class SWEditNumberWithUnits extends SWItem {
layout.addView(l); layout.addView(l);
double initValue = SP.getDouble(preferenceId, init); double initValue = SP.getDouble(preferenceId, init);
initValue = Profile.toCurrentUnits(initValue); initValue = Profile.toCurrentUnits(ProfileFunctions.getSystemUnits(), initValue);
NumberPicker numberPicker = new NumberPicker(context); NumberPicker numberPicker = new NumberPicker(context);
if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL)) if (ProfileFunctions.getSystemUnits().equals(Constants.MMOL))

View file

@ -52,7 +52,7 @@ open class DefaultValueHelper @Inject constructor(
fun determineEatingSoonTT(): Double { fun determineEatingSoonTT(): Double {
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
var value = sp.getDouble(R.string.key_eatingsoon_target, getDefaultEatingSoonTT(units)) 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) return if (value > 0) value else getDefaultEatingSoonTT(units)
} }
@ -69,7 +69,7 @@ open class DefaultValueHelper @Inject constructor(
fun determineActivityTT(): Double { fun determineActivityTT(): Double {
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
var value = sp.getDouble(R.string.key_activity_target, getDefaultActivityTT(units)) 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) return if (value > 0) value else getDefaultActivityTT(units)
} }
@ -86,7 +86,7 @@ open class DefaultValueHelper @Inject constructor(
fun determineHypoTT(): Double { fun determineHypoTT(): Double {
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
var value = sp.getDouble(R.string.key_hypo_target, getDefaultHypoTT(units)) 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) return if (value > 0) value else getDefaultHypoTT(units)
} }
@ -101,14 +101,14 @@ open class DefaultValueHelper @Inject constructor(
fun determineHighLine(): Double { fun determineHighLine(): Double {
var highLineSetting = sp.getDouble(R.string.key_high_mark, bgTargetHigh) var highLineSetting = sp.getDouble(R.string.key_high_mark, bgTargetHigh)
if (highLineSetting < 1) highLineSetting = Constants.HIGHMARK if (highLineSetting < 1) highLineSetting = Constants.HIGHMARK
highLineSetting = Profile.toCurrentUnits(highLineSetting) highLineSetting = Profile.toCurrentUnits(profileFunction, highLineSetting)
return highLineSetting return highLineSetting
} }
fun determineLowLine(): Double { fun determineLowLine(): Double {
var lowLineSetting = sp.getDouble(R.string.key_low_mark, bgTargetLow) var lowLineSetting = sp.getDouble(R.string.key_low_mark, bgTargetLow)
if (lowLineSetting < 1) lowLineSetting = Constants.LOWMARK if (lowLineSetting < 1) lowLineSetting = Constants.LOWMARK
lowLineSetting = Profile.toCurrentUnits(lowLineSetting) lowLineSetting = Profile.toCurrentUnits(profileFunction, lowLineSetting)
return lowLineSetting return lowLineSetting
} }
} }

View file

@ -6,6 +6,7 @@ import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.MidnightTime
@ -16,7 +17,8 @@ import javax.inject.Singleton
@Singleton @Singleton
class TirCalculator @Inject constructor( 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<TIR> { fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray<TIR> {
if (lowMgdl < 39) throw RuntimeException("Low below 39") if (lowMgdl < 39) throw RuntimeException("Low below 39")
@ -75,10 +77,10 @@ class TirCalculator @Inject constructor(
return HtmlHelper.fromHtml( return HtmlHelper.fromHtml(
"<br><b>" + resourceHelper.gs(R.string.tir) + ":</b><br>" + "<br><b>" + resourceHelper.gs(R.string.tir) + ":</b><br>" +
toText(resourceHelper, tir7) + toText(resourceHelper, tir7) +
"<br><b>" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(lowTirMgdl) + "-" + Profile.toCurrentUnitsString(highTirMgdl) + "):</b><br>" + "<br><b>" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + "):</b><br>" +
averageTir7.toText(resourceHelper, tir7.size()) + "<br>" + averageTir7.toText(resourceHelper, tir7.size()) + "<br>" +
averageTir30.toText(resourceHelper, tir30.size()) + averageTir30.toText(resourceHelper, tir30.size()) +
"<br><b>" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(lowTitMgdl) + "-" + Profile.toCurrentUnitsString(highTitMgdl) + "):</b><br>" + "<br><b>" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTitMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTitMgdl) + "):</b><br>" +
averageTit7.toText(resourceHelper, tit7.size()) + "<br>" + averageTit7.toText(resourceHelper, tit7.size()) + "<br>" +
averageTit30.toText(resourceHelper, tit30.size()) averageTit30.toText(resourceHelper, tit30.size())
) )

View file

@ -39,6 +39,7 @@ class BolusWizard @Inject constructor(
injector: HasAndroidInjector injector: HasAndroidInjector
) { ) {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@ -170,7 +171,7 @@ class BolusWizard @Inject constructor(
} }
// Insulin from 15 min trend // Insulin from 15 min trend
glucoseStatus = GlucoseStatus.getGlucoseStatusData() glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
glucoseStatus?.let { glucoseStatus?.let {
if (useTrend) { if (useTrend) {
trend = it.short_avgdelta trend = it.short_avgdelta

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.utils.wizard package info.nightscout.androidaps.utils.wizard
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
@ -21,6 +22,7 @@ import javax.inject.Inject
class QuickWizardEntry @Inject constructor(private val mainApp: MainApp) { class QuickWizardEntry @Inject constructor(private val mainApp: MainApp) {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction @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 if (loopPlugin.isEnabled(loopPlugin.getType()) && loopPlugin.isSuperBolus) superBolus = false
// Trend // Trend
val glucoseStatus = GlucoseStatus.getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
var trend = false var trend = false
if (useTrend() == YES) { if (useTrend() == YES) {
trend = true trend = true

View file

@ -238,43 +238,43 @@ public class AAPSMocker {
} }
public static Profile getValidProfile() { /*
try { public static Profile getValidProfile() {
if (profile == null) try {
profile = new Profile(new JSONObject(validProfile), Constants.MGDL); if (profile == null)
} catch (JSONException ignored) { profile = new Profile(new JSONObject(validProfile), Constants.MGDL);
} } catch (JSONException ignored) {
return profile;
}
public static ProfileStore getValidProfileStore() {
try {
if (profileStore == null) {
JSONObject json = new JSONObject();
JSONObject store = new JSONObject();
JSONObject profile = new JSONObject(validProfile);
json.put("defaultProfile", TESTPROFILENAME);
json.put("store", store);
store.put(TESTPROFILENAME, profile);
profileStore = new ProfileStore(json);
} }
} catch (JSONException ignored) { return profile;
Assert.fail("getValidProfileStore() failed");
} }
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() { json.put("defaultProfile", TESTPROFILENAME);
PowerMockito.mockStatic(ProfileFunctions.class); json.put("store", store);
profileFunctions = PowerMockito.mock(ProfileFunctions.class); store.put(TESTPROFILENAME, profile);
PowerMockito.when(ProfileFunctions.getSystemUnits()).thenReturn(Constants.MGDL); profileStore = new ProfileStore(json);
PowerMockito.when(ProfileFunctions.getInstance()).thenReturn(profileFunctions); }
profile = getValidProfile(); } catch (JSONException ignored) {
PowerMockito.when(ProfileFunctions.getInstance().getProfile()).thenReturn(profile); Assert.fail("getValidProfileStore() failed");
PowerMockito.when(ProfileFunctions.getInstance().getProfileName()).thenReturn(TESTPROFILENAME); }
} 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() { public static IobCobCalculatorPlugin mockIobCobCalculatorPlugin() {
PowerMockito.mockStatic(IobCobCalculatorPlugin.class); PowerMockito.mockStatic(IobCobCalculatorPlugin.class);
IobCobCalculatorPlugin iobCobCalculatorPlugin = PowerMockito.mock(IobCobCalculatorPlugin.class); IobCobCalculatorPlugin iobCobCalculatorPlugin = PowerMockito.mock(IobCobCalculatorPlugin.class);

View file

@ -1,5 +1,7 @@
package info package info
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.data.ProfileStore
@ -11,7 +13,7 @@ import org.mockito.junit.MockitoRule
open class TestBase { 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 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" val TESTPROFILENAME = "someProfile"
fun getValidProfileStore(): ProfileStore { fun getValidProfileStore(): ProfileStore {
@ -20,7 +22,7 @@ open class TestBase {
store.put(TESTPROFILENAME, JSONObject(validProfileJSON)) store.put(TESTPROFILENAME, JSONObject(validProfileJSON))
json.put("defaultProfile", TESTPROFILENAME) json.put("defaultProfile", TESTPROFILENAME)
json.put("store", store) 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. // Add a JUnit rule that will setup the @Mock annotated vars and log.

View file

@ -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<BgReading> 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<BgReading> bgReadings = new ArrayList() {{
add(now);
add(previous);
}};
when(MainApp.getDbHelper().getAllBgreadingsDataFromTime(anyLong(),anyBoolean())).thenReturn(bgReadings);
}
}

View file

@ -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<BgReading>? = 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<BgReading> = mutableListOf()
bgReadings.add(now)
bgReadings.add(previous)
`when`(MainApp.getDbHelper().getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadings)
}
}

View file

@ -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<BgReading> 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 = 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);
}
}

View file

@ -47,7 +47,7 @@ class DanaRSPluginTest : DanaRSTestBase() {
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRPump.maxBasal = 0.8 danaRPump.maxBasal = 0.8
val c = Constraint(Constants.REALLYHIGHBASALRATE) 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(java.lang.Double.valueOf(0.8), c.value(), 0.0001)
Assert.assertEquals("DanaRS: limitingbasalratio", c.getReasons(aapsLogger)) Assert.assertEquals("DanaRS: limitingbasalratio", c.getReasons(aapsLogger))
Assert.assertEquals("DanaRS: limitingbasalratio", c.getMostLimitedReasons(aapsLogger)) Assert.assertEquals("DanaRS: limitingbasalratio", c.getMostLimitedReasons(aapsLogger))
@ -59,7 +59,7 @@ class DanaRSPluginTest : DanaRSTestBase() {
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRPump.maxBasal = 0.8 danaRPump.maxBasal = 0.8
val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE)
danaRSPlugin.applyBasalPercentConstraints(c, AAPSMocker.getValidProfile()) danaRSPlugin.applyBasalPercentConstraints(c, validProfile)
Assert.assertEquals(200, c.value()) Assert.assertEquals(200, c.value())
Assert.assertEquals("DanaRS: limitingpercentrate", c.getReasons(aapsLogger)) Assert.assertEquals("DanaRS: limitingpercentrate", c.getReasons(aapsLogger))
Assert.assertEquals("DanaRS: limitingpercentrate", c.getMostLimitedReasons(aapsLogger)) Assert.assertEquals("DanaRS: limitingpercentrate", c.getMostLimitedReasons(aapsLogger))

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.HasAndroidInjector
import info.TestBase import info.TestBase
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
@ -11,6 +12,7 @@ open class DanaRSTestBase : TestBase() {
@Mock lateinit var aapsLogger: AAPSLogger @Mock lateinit var aapsLogger: AAPSLogger
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var injector: HasAndroidInjector
lateinit var danaRPump: DanaRPump lateinit var danaRPump: DanaRPump
@ -43,6 +45,6 @@ open class DanaRSTestBase : TestBase() {
@Before @Before
fun setup() { fun setup() {
danaRPump = DanaRPump(aapsLogger, sp) danaRPump = DanaRPump(aapsLogger, sp, injector)
} }
} }