eliminate BgReading::class in favor of GlucoseValue::class

This commit is contained in:
Milos Kozak 2021-02-08 10:05:21 +01:00
parent d93865997c
commit 887819edf4
45 changed files with 967 additions and 1475 deletions

Binary file not shown.

View file

@ -217,7 +217,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.dropTable(connectionSource, OmnipodHistoryRecord.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
//TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
@ -315,10 +315,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(TempTarget.class);
}
private Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
private Dao<DanaRHistoryRecord, String> getDaoDanaRHistory() throws SQLException {
return getDao(DanaRHistoryRecord.class);
}
@ -373,14 +369,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
aapsLogger.debug(LTag.DATABASE, "Rounding " + date + " to " + rounded);
return rounded;
}
public List<BgReading> getAllBgReadings() {
try {
return getDaoBgReadings().queryForAll();
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return Collections.emptyList();
}
// ------------------- TDD handling -----------------------
public void createOrUpdateTDD(TDD tdd) {
@ -1531,6 +1519,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
return Collections.emptyList();
}
@Nullable
private ProfileSwitch getLastProfileSwitchWithoutDuration() {
try {
@ -1969,8 +1958,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public long getCountOfAllRows() {
try {
return getDaoBgReadings().countOf()
+ getDaoCareportalEvents().countOf()
return getDaoCareportalEvents().countOf()
+ getDaoExtendedBolus().countOf()
+ getDaoCareportalEvents().countOf()
+ getDaoProfileSwitch().countOf()

View file

@ -2,11 +2,9 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.*
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.db.DatabaseHelper
import info.nightscout.androidaps.plugins.general.food.FoodService
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.utils.wizard.BolusWizard
import info.nightscout.androidaps.utils.wizard.QuickWizardEntry

View file

@ -20,7 +20,6 @@ import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.databinding.DialogWizardBinding
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ProfileFunction
@ -236,6 +235,10 @@ class WizardDialog : DaggerDialogFragment() {
binding.cobcheckbox.isChecked = sp.getBoolean(R.string.key_wizard_include_cob, false)
}
private fun valueToUnitsToString(value: Double, units: String): String =
if (units == Constants.MGDL) DecimalFormatter.to0Decimal(value)
else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL)
private fun initDialog() {
val profile = profileFunction.getProfile()
val profileStore = activePlugin.activeProfileInterface.profile
@ -246,8 +249,7 @@ class WizardDialog : DaggerDialogFragment() {
return
}
val profileList: ArrayList<CharSequence>
profileList = profileStore.getProfileList()
val profileList: ArrayList<CharSequence> = profileStore.getProfileList()
profileList.add(0, resourceHelper.gs(R.string.active))
context?.let { context ->
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
@ -335,7 +337,7 @@ class WizardDialog : DaggerDialogFragment() {
binding.notes.text.toString(), carbTime)
wizard?.let { wizard ->
binding.bg.text = String.format(resourceHelper.gs(R.string.format_bg_isf), BgReading(injector).value(Profile.toMgdl(bg, profileFunction.getUnits())).valueToUnitsToString(profileFunction.getUnits()), wizard.sens)
binding.bg.text = String.format(resourceHelper.gs(R.string.format_bg_isf), valueToUnitsToString(Profile.toMgdl(bg, profileFunction.getUnits()), profileFunction.getUnits()), wizard.sens)
binding.bginsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBG)
binding.carbs.text = String.format(resourceHelper.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic)

View file

@ -392,30 +392,30 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
// Prepare for pumps using % basals
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT && allowPercentage()) {
result.usePercent = true;
result.setUsePercent(true);
}
result.percent = (int) (result.rate / profile.getBasal() * 100);
result.setPercent((int) (result.getRate() / profile.getBasal() * 100));
// check rate for constraints
final APSResult resultAfterConstraints = result.newAndClone(injector);
resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate);
resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
resultAfterConstraints.setRateConstraint(new Constraint<>(resultAfterConstraints.getRate()));
resultAfterConstraints.setRate(constraintChecker.applyBasalConstraints(resultAfterConstraints.getRateConstraint(), profile).value());
resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent);
resultAfterConstraints.percent = constraintChecker.applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value();
resultAfterConstraints.setPercentConstraint(new Constraint<>(resultAfterConstraints.getPercent()));
resultAfterConstraints.setPercent(constraintChecker.applyBasalPercentConstraints(resultAfterConstraints.getPercentConstraint(), profile).value());
resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb);
resultAfterConstraints.smb = constraintChecker.applyBolusConstraints(resultAfterConstraints.smbConstraint).value();
resultAfterConstraints.setSmbConstraint(new Constraint<>(resultAfterConstraints.getSmb()));
resultAfterConstraints.setSmb(constraintChecker.applyBolusConstraints(resultAfterConstraints.getSmbConstraint()).value());
// safety check for multiple SMBs
long lastBolusTime = treatmentsPlugin.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > System.currentTimeMillis()) {
getAapsLogger().debug(LTag.APS, "SMB requested but still in 3 min interval");
resultAfterConstraints.smb = 0;
resultAfterConstraints.setSmb(0);
}
if (lastRun != null && lastRun.getConstraintsProcessed() != null) {
prevCarbsreq = lastRun.getConstraintsProcessed().carbsReq;
prevCarbsreq = lastRun.getConstraintsProcessed().getCarbsReq();
}
if (lastRun == null) lastRun = new LastRun();
@ -449,7 +449,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
if (closedLoopEnabled.value()) {
if (allowNotification) {
if (resultAfterConstraints.isCarbsRequired()
&& resultAfterConstraints.carbsReq >= sp.getInt(R.string.key_smb_enable_carbs_suggestions_threshold, 0)
&& resultAfterConstraints.getCarbsReq() >= sp.getInt(R.string.key_smb_enable_carbs_suggestions_threshold, 0)
&& carbsSuggestionsSuspendedUntil < System.currentTimeMillis() && !treatmentTimethreshold(-15)) {
if (sp.getBoolean(R.string.key_enable_carbs_required_alert_local, true) && !sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, true)) {
@ -519,9 +519,9 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
&& !commandQueue.isRunning(Command.CommandType.BOLUS)) {
final PumpEnactResult waiting = new PumpEnactResult(getInjector());
waiting.queued = true;
if (resultAfterConstraints.tempBasalRequested)
if (resultAfterConstraints.getTempBasalRequested())
lastRun.setTbrSetByPump(waiting);
if (resultAfterConstraints.bolusRequested)
if (resultAfterConstraints.getBolusRequested())
lastRun.setSmbSetByPump(waiting);
rxBus.send(new EventLoopUpdateGui());
fabricPrivacy.logCustom("APSRequest");
@ -653,7 +653,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
private void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
if (!request.tempBasalRequested) {
if (!request.getTempBasalRequested()) {
if (callback != null) {
callback.result(new PumpEnactResult(getInjector()).enacted(false).success(true).comment(resourceHelper.gs(R.string.nochangerequested))).run();
}
@ -682,48 +682,48 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now);
if (request.usePercent && allowPercentage()) {
if (request.percent == 100 && request.duration == 0) {
if (request.getUsePercent() && allowPercentage()) {
if (request.getPercent() == 100 && request.getDuration() == 0) {
if (activeTemp != null) {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: cancelTempBasal()");
commandQueue.cancelTempBasal(false, callback);
} else {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult(getInjector()).percent(request.percent).duration(0)
callback.result(new PumpEnactResult(getInjector()).percent(request.getPercent()).duration(0)
.enacted(false).success(true).comment(resourceHelper.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& request.percent == activeTemp.percentRate) {
&& request.getDuration() - activeTemp.getPlannedRemainingMinutes() < 30
&& request.getPercent() == activeTemp.percentRate) {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult(getInjector()).percent(request.percent)
callback.result(new PumpEnactResult(getInjector()).percent(request.getPercent())
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(resourceHelper.gs(R.string.let_temp_basal_run))).run();
}
} else {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: tempBasalPercent()");
commandQueue.tempBasalPercent(request.percent, request.duration, false, profile, callback);
commandQueue.tempBasalPercent(request.getPercent(), request.getDuration(), false, profile, callback);
}
} else {
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if ((request.getRate() == 0 && request.getDuration() == 0) || Math.abs(request.getRate() - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: cancelTempBasal()");
commandQueue.cancelTempBasal(false, callback);
} else {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult(getInjector()).absolute(request.rate).duration(0)
callback.result(new PumpEnactResult(getInjector()).absolute(request.getRate()).duration(0)
.enacted(false).success(true).comment(resourceHelper.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
&& request.getDuration() - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.getRate() - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult(getInjector()).absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
@ -732,13 +732,13 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
}
} else {
getAapsLogger().debug(LTag.APS, "applyAPSRequest: setTempBasalAbsolute()");
commandQueue.tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
commandQueue.tempBasalAbsolute(request.getRate(), request.getDuration(), false, profile, callback);
}
}
}
private void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
if (!request.getBolusRequested()) {
return;
}
@ -777,10 +777,10 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = treatmentsPlugin.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.insulin = request.getSmb();
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
detailedBolusInfo.deliverAt = request.getDeliverAt();
getAapsLogger().debug(LTag.APS, "applyAPSRequest: bolus()");
commandQueue.bolus(detailedBolusInfo, callback);
}

View file

@ -1,77 +0,0 @@
package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.javascript.NativeObject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultAMA extends APSResult {
private AAPSLogger aapsLogger;
private double eventualBG;
private double snoozeBG;
DetermineBasalResultAMA(HasAndroidInjector injector, NativeObject result, JSONObject j) {
this(injector);
date = DateUtil.now();
json = j;
if (result.containsKey("error")) {
reason = result.get("error").toString();
tempBasalRequested = false;
rate = -1;
duration = -1;
} else {
reason = result.get("reason").toString();
if (result.containsKey("eventualBG")) eventualBG = (Double) result.get("eventualBG");
if (result.containsKey("snoozeBG")) snoozeBG = (Double) result.get("snoozeBG");
if (result.containsKey("rate")) {
rate = (Double) result.get("rate");
if (rate < 0d) rate = 0d;
tempBasalRequested = true;
} else {
rate = -1;
tempBasalRequested = false;
}
if (result.containsKey("duration")) {
duration = ((Double) result.get("duration")).intValue();
//changeRequested as above
} else {
duration = -1;
tempBasalRequested = false;
}
}
bolusRequested = false;
}
private DetermineBasalResultAMA(HasAndroidInjector injector) {
super(injector);
hasPredictions = true;
}
@Override
public DetermineBasalResultAMA newAndClone(HasAndroidInjector injector) {
DetermineBasalResultAMA newResult = new DetermineBasalResultAMA(injector);
doClone(newResult);
newResult.eventualBG = eventualBG;
newResult.snoozeBG = snoozeBG;
return newResult;
}
@Override
public JSONObject json() {
try {
JSONObject ret = new JSONObject(this.json.toString());
return ret;
} catch (JSONException e) {
aapsLogger.error(LTag.APS, "Unhandled exception", e);
}
return null;
}
}

View file

@ -0,0 +1,67 @@
package info.nightscout.androidaps.plugins.aps.openAPSAMA
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONException
import org.json.JSONObject
import org.mozilla.javascript.NativeObject
class DetermineBasalResultAMA private constructor(injector: HasAndroidInjector) : APSResult(injector) {
private var eventualBG = 0.0
private var snoozeBG = 0.0
internal constructor(injector: HasAndroidInjector, result: NativeObject, j: JSONObject) : this(injector) {
date = DateUtil.now()
json = j
if (result.containsKey("error")) {
reason = result["error"].toString()
tempBasalRequested = false
rate = (-1).toDouble()
duration = -1
} else {
reason = result["reason"].toString()
if (result.containsKey("eventualBG")) eventualBG = result["eventualBG"] as Double
if (result.containsKey("snoozeBG")) snoozeBG = result["snoozeBG"] as Double
if (result.containsKey("rate")) {
rate = result["rate"] as Double
if (rate < 0.0) rate = 0.0
tempBasalRequested = true
} else {
rate = (-1).toDouble()
tempBasalRequested = false
}
if (result.containsKey("duration")) {
duration = (result["duration"] as Double).toInt()
//changeRequested as above
} else {
duration = -1
tempBasalRequested = false
}
}
bolusRequested = false
}
override fun newAndClone(injector: HasAndroidInjector): DetermineBasalResultAMA {
val newResult = DetermineBasalResultAMA(injector)
doClone(newResult)
newResult.eventualBG = eventualBG
newResult.snoozeBG = snoozeBG
return newResult
}
override fun json(): JSONObject? {
try {
return JSONObject(json.toString())
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e)
}
return null
}
init {
hasPredictions = true
}
}

View file

@ -18,20 +18,20 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
@ -238,15 +238,15 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
lastAPSResult = null;
lastAPSRun = 0;
} else {
if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !treatmentsPlugin.isTempBasalInProgress())
determineBasalResultAMA.tempBasalRequested = false;
if (determineBasalResultAMA.getRate() == 0d && determineBasalResultAMA.getDuration() == 0 && !treatmentsPlugin.isTempBasalInProgress())
determineBasalResultAMA.setTempBasalRequested(false);
determineBasalResultAMA.iob = iobArray[0];
determineBasalResultAMA.setIob(iobArray[0]);
long now = System.currentTimeMillis();
try {
determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));
determineBasalResultAMA.getJson().put("timestamp", DateUtil.toISOString(now));
} catch (JSONException e) {
aapsLogger.error(LTag.APS, "Unhandled exception", e);
}

View file

@ -1,97 +0,0 @@
package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException;
import org.json.JSONObject;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class DetermineBasalResultSMB extends APSResult {
@Inject SP sp;
private double eventualBG;
private double snoozeBG;
private DetermineBasalResultSMB(HasAndroidInjector injector) {
super(injector);
hasPredictions = true;
}
DetermineBasalResultSMB(HasAndroidInjector injector, JSONObject result) {
this(injector);
date = DateUtil.now();
json = result;
try {
if (result.has("error")) {
reason = result.getString("error");
return;
}
reason = result.getString("reason");
if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG");
if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG");
//if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq");
if (result.has("carbsReq")) carbsReq = result.getInt("carbsReq");
if (result.has("carbsReqWithin")) carbsReqWithin = result.getInt("carbsReqWithin");
if (result.has("rate") && result.has("duration")) {
tempBasalRequested = true;
rate = result.getDouble("rate");
if (rate < 0d) rate = 0d;
duration = result.getInt("duration");
} else {
rate = -1;
duration = -1;
}
if (result.has("units")) {
bolusRequested = true;
smb = result.getDouble("units");
} else {
smb = 0d;
}
if (result.has("targetBG")) {
targetBG = result.getDouble("targetBG");
}
if (result.has("deliverAt")) {
String date = result.getString("deliverAt");
try {
deliverAt = DateUtil.fromISODateString(date).getTime();
} catch (Exception e) {
aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: " + date, e);
}
}
} catch (JSONException e) {
aapsLogger.error(LTag.APS, "Error parsing determine-basal result JSON", e);
}
}
@Override
public DetermineBasalResultSMB newAndClone(HasAndroidInjector injector) {
DetermineBasalResultSMB newResult = new DetermineBasalResultSMB(injector);
doClone(newResult);
newResult.eventualBG = eventualBG;
newResult.snoozeBG = snoozeBG;
return newResult;
}
@Override
public JSONObject json() {
try {
return new JSONObject(this.json.toString());
} catch (JSONException e) {
aapsLogger.error(LTag.APS, "Error converting determine-basal result to JSON", e);
}
return null;
}
}

View file

@ -0,0 +1,80 @@
package info.nightscout.androidaps.plugins.aps.openAPSSMB
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONException
import org.json.JSONObject
class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector) : APSResult(injector) {
private var eventualBG = 0.0
private var snoozeBG = 0.0
internal constructor(injector: HasAndroidInjector, result: JSONObject) : this(injector) {
date = DateUtil.now()
json = result
try {
if (result.has("error")) {
reason = result.getString("error")
return
}
reason = result.getString("reason")
if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG")
if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG")
//if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq");
if (result.has("carbsReq")) carbsReq = result.getInt("carbsReq")
if (result.has("carbsReqWithin")) carbsReqWithin = result.getInt("carbsReqWithin")
if (result.has("rate") && result.has("duration")) {
tempBasalRequested = true
rate = result.getDouble("rate")
if (rate < 0.0) rate = 0.0
duration = result.getInt("duration")
} else {
rate = (-1).toDouble()
duration = -1
}
if (result.has("units")) {
bolusRequested = true
smb = result.getDouble("units")
} else {
smb = 0.0
}
if (result.has("targetBG")) {
targetBG = result.getDouble("targetBG")
}
if (result.has("deliverAt")) {
val date = result.getString("deliverAt")
try {
deliverAt = DateUtil.fromISODateString(date).time
} catch (e: Exception) {
aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: $date", e)
}
}
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Error parsing determine-basal result JSON", e)
}
}
override fun newAndClone(injector: HasAndroidInjector): DetermineBasalResultSMB {
val newResult = DetermineBasalResultSMB(injector)
doClone(newResult)
newResult.eventualBG = eventualBG
newResult.snoozeBG = snoozeBG
return newResult
}
override fun json(): JSONObject? {
try {
return JSONObject(json.toString())
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Error converting determine-basal result to JSON", e)
}
return null
}
init {
hasPredictions = true
}
}

View file

@ -24,20 +24,20 @@ import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
@ -291,18 +291,18 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
} else {
// TODO still needed with oref1?
// Fix bug determine basal
if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !treatmentsPlugin.isTempBasalInProgress())
determineBasalResultSMB.tempBasalRequested = false;
if (determineBasalResultSMB.getRate() == 0d && determineBasalResultSMB.getDuration() == 0 && !treatmentsPlugin.isTempBasalInProgress())
determineBasalResultSMB.setTempBasalRequested(false);
determineBasalResultSMB.iob = iobArray[0];
determineBasalResultSMB.setIob(iobArray[0]);
try {
determineBasalResultSMB.json.put("timestamp", DateUtil.toISOString(now));
determineBasalResultSMB.getJson().put("timestamp", DateUtil.toISOString(now));
} catch (JSONException e) {
getAapsLogger().error(LTag.APS, "Unhandled exception", e);
}
determineBasalResultSMB.inputConstraints = inputConstraints;
determineBasalResultSMB.setInputConstraints(inputConstraints);
lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS;
lastAPSResult = determineBasalResultSMB;

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.general.nsclient.data;
import android.text.Html;
import android.text.Spanned;
import org.json.JSONArray;
@ -15,7 +14,6 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConfigInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
@ -475,8 +473,8 @@ public class NSDeviceStatus {
public static APSResult getAPSResult(HasAndroidInjector injector) {
APSResult result = new APSResult(injector);
result.json = deviceStatusOpenAPSData.suggested;
result.date = deviceStatusOpenAPSData.clockSuggested;
result.setJson(deviceStatusOpenAPSData.suggested);
result.setDate(deviceStatusOpenAPSData.clockSuggested);
return result;
}

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.db.*
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.PluginBase
@ -163,15 +164,15 @@ class OpenHumansUploader @Inject constructor(
super.onStop()
}
fun enqueueBGReading(bgReading: BgReading?) = bgReading?.let {
fun enqueueBGReading(glucoseValue: GlucoseValue?) = glucoseValue?.let {
insertQueueItem("BgReadings") {
put("date", bgReading.data.dateCreated)
put("isValid", bgReading.data.isValid)
put("value", bgReading.data.value)
put("direction", bgReading.data.trendArrow)
put("raw", bgReading.data.raw)
put("source", bgReading.data.sourceSensor)
put("nsId", bgReading.data.interfaceIDs.nightscoutId)
put("date", glucoseValue.timestamp)
put("isValid", glucoseValue.isValid)
put("value", glucoseValue.value)
put("direction", glucoseValue.trendArrow)
put("raw", glucoseValue.raw)
put("source", glucoseValue.sourceSensor)
put("nsId", glucoseValue.interfaceIDs.nightscoutId)
}
}
@ -365,7 +366,7 @@ class OpenHumansUploader @Inject constructor(
.flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.treatmentData) } }
.map { enqueueTreatment(it); increaseCounter() }
.ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allBgReadings) })
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) })
.map { enqueueBGReading(it); increaseCounter() }
.ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allCareportalEvents) })

View file

@ -12,9 +12,10 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.GlucoseValueDataPoint
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.LoopInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
@ -27,7 +28,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.convertToBGReadings
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.*
import javax.inject.Inject
@ -51,7 +51,7 @@ class GraphData(
var maxY = Double.MIN_VALUE
private var minY = Double.MAX_VALUE
private var bgReadingsArray: List<BgReading>? = null
private var bgReadingsArray: List<GlucoseValue>? = null
private val units: String
private val series: MutableList<Series<*>> = ArrayList()
@ -61,9 +61,9 @@ class GraphData(
}
@Suppress("UNUSED_PARAMETER")
fun addBgReadings(fromTime: Long, toTime: Long, lowLine: Double, highLine: Double, predictions: MutableList<BgReading>?) {
fun addBgReadings(fromTime: Long, toTime: Long, lowLine: Double, highLine: Double, predictions: MutableList<GlucoseValueDataPoint>?) {
var maxBgValue = Double.MIN_VALUE
bgReadingsArray = iobCobCalculatorPlugin.bgReadings?.convertToBGReadings(injector)
bgReadingsArray = iobCobCalculatorPlugin.bgReadings
if (bgReadingsArray?.isEmpty() != false) {
aapsLogger.debug("No BG data.")
maxY = 10.0
@ -72,12 +72,12 @@ class GraphData(
}
val bgListArray: MutableList<DataPointWithLabelInterface> = ArrayList()
for (bg in bgReadingsArray!!) {
if (bg.data.timestamp < fromTime || bg.data.timestamp > toTime) continue
if (bg.data.value > maxBgValue) maxBgValue = bg.data.value
bgListArray.add(bg)
if (bg.timestamp < fromTime || bg.timestamp > toTime) continue
if (bg.value > maxBgValue) maxBgValue = bg.value
bgListArray.add(GlucoseValueDataPoint(injector, bg))
}
if (predictions != null) {
predictions.sortWith(Comparator { o1: BgReading, o2: BgReading -> o1.x.compareTo(o2.x) })
predictions.sortWith(Comparator { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) })
for (prediction in predictions) if (prediction.data.value >= 40) bgListArray.add(prediction)
}
maxBgValue = Profile.fromMgdlToUnits(maxBgValue, units)
@ -213,8 +213,7 @@ class GraphData(
var time = fromTime
while (time < toTime) {
val tt = treatmentsPlugin.getTempTargetFromHistory(time)
var value: Double
value = if (tt == null) {
val value: Double = if (tt == null) {
Profile.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2, units)
} else {
Profile.fromMgdlToUnits(tt.target(), units)
@ -283,10 +282,10 @@ class GraphData(
bgReadingsArray?.let { bgReadingsArray ->
for (r in bgReadingsArray.indices) {
val reading = bgReadingsArray[r]
if (reading.data.timestamp > date) continue
return Profile.fromMgdlToUnits(reading.data.value, units)
if (reading.timestamp > date) continue
return Profile.fromMgdlToUnits(reading.value, units)
}
return if (bgReadingsArray.isNotEmpty()) Profile.fromMgdlToUnits(bgReadingsArray[0].data.value, units) else Profile.fromMgdlToUnits(100.0, units)
return if (bgReadingsArray.isNotEmpty()) Profile.fromMgdlToUnits(bgReadingsArray[0].value, units) else Profile.fromMgdlToUnits(100.0, units)
} ?: return Profile.fromMgdlToUnits(100.0, units)
}

View file

@ -8,17 +8,16 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.tidepool.elements.*
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus
import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.convertToBGReadings
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
@ -109,9 +108,8 @@ class UploadChunk @Inject constructor(
val bgReadingList = repository.compatGetBgReadingsDataFromTime(start, end, true)
.blockingGet()
.convertToBGReadings(injector)
return if (bgReadingList.isNotEmpty())
bgReadingList[0].data.timestamp
bgReadingList[0].timestamp
else -1
}
@ -140,7 +138,6 @@ class UploadChunk @Inject constructor(
private fun getBgReadings(start: Long, end: Long): List<SensorGlucoseElement> {
val readings = repository.compatGetBgReadingsDataFromTime(start, end, true)
.blockingGet()
.convertToBGReadings(injector)
val selection = SensorGlucoseElement.fromBgReadings(readings)
if (selection.isNotEmpty())
rxBus.send(EventTidepoolStatus("${selection.size} CGMs selected for upload"))

View file

@ -1,24 +1,26 @@
package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.database.entities.GlucoseValue
import java.util.*
class SensorGlucoseElement(bgReading: BgReading)
: BaseElement(bgReading.data.timestamp, UUID.nameUUIDFromBytes(("AAPS-cgm" + bgReading.data.timestamp).toByteArray()).toString()) {
class SensorGlucoseElement(bgReading: GlucoseValue)
: BaseElement(bgReading.timestamp, UUID.nameUUIDFromBytes(("AAPS-cgm" + bgReading.timestamp).toByteArray()).toString()) {
@Expose
internal var units: String = "mg/dL"
@Expose
internal var value: Int = 0
init {
this.type = "cbg"
value = bgReading.data.value.toInt()
value = bgReading.value.toInt()
}
companion object {
internal fun fromBgReadings(bgReadingList: List<BgReading>): List<SensorGlucoseElement> {
internal fun fromBgReadings(bgReadingList: List<GlucoseValue>): List<SensorGlucoseElement> {
val results = LinkedList<SensorGlucoseElement>()
for (bgReading in bgReadingList) {
results.add(SensorGlucoseElement(bgReading))

View file

@ -32,11 +32,11 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseValueDataPoint;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.GlucoseValue;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
@ -537,14 +537,14 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
}
final LoopPlugin.LastRun finalLastRun = loopPlugin.getLastRun();
if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().hasPredictions && finalLastRun.getConstraintsProcessed() != null) {
List<BgReading> predArray = finalLastRun.getConstraintsProcessed().getPredictions();
if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) {
List<GlucoseValueDataPoint> predArray = finalLastRun.getConstraintsProcessed().getPredictions();
if (!predArray.isEmpty()) {
final String units = profileFunction.getUnits();
for (BgReading bg : predArray) {
if (bg.getValue() < 40) continue;
predictions.add(predictionMap(bg.getDate(), bg.getValue(), bg.getPredictionColor()));
for (GlucoseValueDataPoint bg : predArray) {
if (bg.getData().getValue() < 40) continue;
predictions.add(predictionMap(bg.getData().getTimestamp(), bg.getData().getValue(), bg.getPredictionColor()));
}
}
}

View file

@ -9,7 +9,6 @@ import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.database.entities.GlucoseValue;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.utils.DateUtil;

View file

@ -17,14 +17,12 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.GlucoseValue;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.Event;
@ -385,7 +383,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat
if (older.getTimestamp() == newer.getTimestamp()) { // direct hit
bucketed_data.add(new InMemoryGlucoseValue(newer));
} else {
double bgDelta = newer.getTimestamp() - older.getTimestamp();
double bgDelta = newer.getValue() - older.getValue();
long timeDiffToNew = newer.getTimestamp() - currentTime;
double currentBg = newer.getValue() - (double) timeDiffToNew / (newer.getTimestamp() - older.getTimestamp()) * bgDelta;

View file

@ -18,15 +18,14 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
@ -35,7 +34,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutos
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;

View file

@ -16,15 +16,14 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
@ -33,7 +32,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutos
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;

View file

@ -13,7 +13,6 @@ import info.nightscout.androidaps.activities.RequestDexcomPermissionActivity
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -138,9 +137,9 @@ class DexcomPlugin @Inject constructor(
broadcastToXDrip(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
if (it.interfaceIDs.nightscoutId != null)
nsUpload.updateBg(BgReading(injector, it), sourceSensor.text)
nsUpload.updateBg(it, sourceSensor.text)
else
nsUpload.uploadBg(BgReading(injector, it), sourceSensor.text)
nsUpload.uploadBg(it, sourceSensor.text)
}
}
}, {

View file

@ -10,7 +10,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
@ -122,7 +121,7 @@ class EversensePlugin @Inject constructor(
savedValues.forEach {
broadcastToXDrip(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(BgReading(injector, it), GlucoseValue.SourceSensor.EVERSENSE.text)
nsUpload.uploadBg(it, GlucoseValue.SourceSensor.EVERSENSE.text)
}
}, {
aapsLogger.error(LTag.BGSOURCE, "Error while saving values from Eversense App", it)

View file

@ -8,7 +8,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -80,7 +79,7 @@ class GlimpPlugin @Inject constructor(
savedValues.forEach {
broadcastToXDrip(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(BgReading(injector, it), GlucoseValue.SourceSensor.GLIMP.text)
nsUpload.uploadBg(it, GlucoseValue.SourceSensor.GLIMP.text)
}
}, {
aapsLogger.error(LTag.BGSOURCE, "Error while saving values from Glimp App", it)

View file

@ -8,7 +8,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -98,7 +97,7 @@ class MM640gPlugin @Inject constructor(
savedValues.forEach {
broadcastToXDrip(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(BgReading(injector, it), GlucoseValue.SourceSensor.MM_600_SERIES.text)
nsUpload.uploadBg(it, GlucoseValue.SourceSensor.MM_600_SERIES.text)
}
}, {
aapsLogger.error(LTag.BGSOURCE, "Error while saving values from Eversense App", it)

View file

@ -94,12 +94,13 @@ class NSClientSourcePlugin @Inject constructor(
@Inject lateinit var bundleStore: BundleStore
@Inject lateinit var repository: AppRepository
@Inject lateinit var broadcastToXDrip: XDripBroadcast
@Inject lateinit var dexcomPlugin: DexcomPlugin
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
fun toGv(jsonObject: JSONObject): CgmSourceTransaction.TransactionGlucoseValue {
private fun toGv(jsonObject: JSONObject): CgmSourceTransaction.TransactionGlucoseValue {
val sgv = NSSgv(jsonObject)
return CgmSourceTransaction.TransactionGlucoseValue(
timestamp = sgv.mills,
@ -113,7 +114,7 @@ class NSClientSourcePlugin @Inject constructor(
}
override fun doWork(): Result {
if (!nsClientSourcePlugin.isEnabled(PluginType.BGSOURCE) && !sp.getBoolean(R.string.key_ns_autobackfill, true)) return Result.failure()
if (!nsClientSourcePlugin.isEnabled() && !sp.getBoolean(R.string.key_ns_autobackfill, true) && !dexcomPlugin.isEnabled()) return Result.failure()
try {
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
inputData.getString("sgv")?.let { sgvString ->

View file

@ -9,7 +9,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -91,7 +90,7 @@ class PoctechPlugin @Inject constructor(
savedValues.forEach {
broadcastToXDrip(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(BgReading(injector, it), GlucoseValue.SourceSensor.POCTECH_NATIVE.text)
nsUpload.uploadBg(it, GlucoseValue.SourceSensor.POCTECH_NATIVE.text)
}
}, {
aapsLogger.error(LTag.BGSOURCE, "Error while saving values from Poctech App", it)

View file

@ -7,7 +7,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -112,7 +111,7 @@ class RandomBgPlugin @Inject constructor(
savedValues.forEach {
xDripBroadcast(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(BgReading(injector, it), GlucoseValue.SourceSensor.RANDOM.text)
nsUpload.uploadBg(it, GlucoseValue.SourceSensor.RANDOM.text)
}
}, {
aapsLogger.error(LTag.BGSOURCE, "Error while saving values from Random plugin", it)

View file

@ -8,7 +8,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -80,7 +79,7 @@ class TomatoPlugin @Inject constructor(
savedValues.forEach {
broadcastToXDrip(it)
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(BgReading(injector, it), GlucoseValue.SourceSensor.LIBRE_1_TOMATO.text)
nsUpload.uploadBg(it, GlucoseValue.SourceSensor.LIBRE_1_TOMATO.text)
}
}, {
aapsLogger.error(LTag.BGSOURCE, "Error while saving values from Tomato App", it)

View file

@ -1,9 +1,7 @@
package info.nightscout.androidaps.utils
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.db.BgReading
fun GlucoseValue.valueToUnits(units: String): Double =
if (units == Constants.MGDL) value
@ -12,7 +10,3 @@ fun GlucoseValue.valueToUnits(units: String): Double =
fun GlucoseValue.valueToUnitsString(units: String): String =
if (units == Constants.MGDL) DecimalFormatter.to0Decimal(value)
else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL)
fun GlucoseValue.convertToBGReading(injector: HasAndroidInjector): BgReading = BgReading(injector, this)
fun List<GlucoseValue>.convertToBGReadings(injector: HasAndroidInjector): List<BgReading> = map { it.convertToBGReading(injector) }

View file

@ -1,185 +0,0 @@
package info.nightscout.androidaps.db
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper
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.api.mockito.PowerMockito
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, GlucoseStatus::class)
class BgReadingTest : TestBase() {
@Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var databaseHelper: DatabaseHelperInterface
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(injector)
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(injector)
bgReading.direction = "DoubleDown"
Assert.assertEquals("\u21ca", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "SingleDown"
Assert.assertEquals("\u2193", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "FortyFiveDown"
Assert.assertEquals("\u2198", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "Flat"
Assert.assertEquals("\u2192", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "FortyFiveUp"
Assert.assertEquals("\u2197", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "SingleUp"
Assert.assertEquals("\u2191", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "DoubleUp"
Assert.assertEquals("\u21c8", bgReading.directionToSymbol(databaseHelper))
bgReading.direction = "OUT OF RANGE"
Assert.assertEquals("??", bgReading.directionToSymbol(databaseHelper))
}
@Test
fun directionToIcon() {
val bgReading = BgReading(injector)
bgReading.direction = "DoubleDown"
Assert.assertEquals(R.drawable.ic_doubledown, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "SingleDown"
Assert.assertEquals(R.drawable.ic_singledown, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "FortyFiveDown"
Assert.assertEquals(R.drawable.ic_fortyfivedown, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "Flat"
Assert.assertEquals(R.drawable.ic_flat, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "FortyFiveUp"
Assert.assertEquals(R.drawable.ic_fortyfiveup, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "SingleUp"
Assert.assertEquals(R.drawable.ic_singleup, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "DoubleUp"
Assert.assertEquals(R.drawable.ic_doubleup, bgReading.directionToIcon(databaseHelper))
bgReading.direction = "OUT OF RANGE"
Assert.assertEquals(R.drawable.ic_invalid, bgReading.directionToIcon(databaseHelper))
}
@Test fun dateTest() {
val bgReading = BgReading(injector)
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(injector)
val valueToSet = 81.0 // 4.5 mmol
Assert.assertEquals(81.0, bgReading.value(valueToSet).value, 0.01)
}
@Test fun copyFromTest() {
// val databaseHelper = Mockito.mock(DatabaseHelper::class.java)
// `when`(MainApp.getDbHelper()).thenReturn(databaseHelper)
setReadings(72, 0)
val bgReading = BgReading(injector)
val copy = BgReading(injector)
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(databaseHelper), copy.directionToSymbol(databaseHelper))
}
@Test
fun isEqualTest() {
val bgReading = BgReading(injector)
val copy = BgReading(injector)
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(injector)))
}
@Test fun calculateDirection() {
val bgReading = BgReading(injector)
val bgReadingsList: List<BgReading>? = null
// val databaseHelper = Mockito.mock(DatabaseHelper::class.java)
// `when`(MainApp.getDbHelper()).thenReturn(databaseHelper)
`when`(databaseHelper.getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadingsList)
Assert.assertEquals("NONE", bgReading.calculateDirection(databaseHelper))
setReadings(72, 0)
Assert.assertEquals("DoubleUp", bgReading.calculateDirection(databaseHelper))
setReadings(76, 60)
Assert.assertEquals("SingleUp", bgReading.calculateDirection(databaseHelper))
setReadings(74, 65)
Assert.assertEquals("FortyFiveUp", bgReading.calculateDirection(databaseHelper))
setReadings(72, 72)
Assert.assertEquals("Flat", bgReading.calculateDirection(databaseHelper))
setReadings(0, 72)
Assert.assertEquals("DoubleDown", bgReading.calculateDirection(databaseHelper))
setReadings(60, 76)
Assert.assertEquals("SingleDown", bgReading.calculateDirection(databaseHelper))
setReadings(65, 74)
Assert.assertEquals("FortyFiveDown", bgReading.calculateDirection(databaseHelper))
}
@Before
fun prepareMock() {
}
fun setReadings(current_value: Int, previous_value: Int) {
val now = BgReading(injector)
now.value = current_value.toDouble()
now.date = System.currentTimeMillis()
val previous = BgReading(injector)
previous.value = previous_value.toDouble()
previous.date = System.currentTimeMillis() - 6 * 60 * 1000L
val bgReadings: MutableList<BgReading> = mutableListOf()
bgReadings.add(now)
bgReadings.add(previous)
`when`(databaseHelper.getAllBgreadingsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(bgReadings)
}
}

View file

@ -188,7 +188,7 @@ class APSResultTest : TestBaseWithProfile() {
apsResult.rate(20.0).tempBasalRequested(true)
Assert.assertEquals(20.0, safeGetDouble(apsResult.json(), "rate"), 0.0)
apsResult.rate(20.0).tempBasalRequested(false)
Assert.assertEquals(false, apsResult.json().has("rate"))
Assert.assertEquals(false, apsResult.json()?.has("rate"))
}
@Before

View file

@ -3,10 +3,9 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONObject
@ -93,9 +92,16 @@ class TriggerBgTest : TriggerTestBase() {
Assert.assertEquals(Optional.of(R.drawable.ic_cp_bgcheck), TriggerBg(injector).icon())
}
private fun generateOneCurrentRecordBgData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":214,\"mills\":" + (now - 1) + ",\"direction\":\"Flat\"}"))))
private fun generateOneCurrentRecordBgData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
list.add(GlucoseValue(
raw = 0.0,
noise = 0.0,
value = 214.0,
timestamp = now - 1,
sourceSensor = GlucoseValue.SourceSensor.UNKNOWN,
trendArrow = GlucoseValue.TrendArrow.FLAT
))
return list
}
}

View file

@ -3,11 +3,10 @@ package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.general.automation.elements.InputDelta.DeltaType
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONObject
@ -101,16 +100,16 @@ class TriggerDeltaTest : TriggerTestBase() {
Assert.assertTrue(t.units == Constants.MGDL)
}
private fun generateValidBgData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":214,\"mills\":1514766900000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":216,\"mills\":1514766600000,\"direction\":\"Flat\"}")))) // +2
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":219,\"mills\":1514766300000,\"direction\":\"Flat\"}")))) // +3
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":223,\"mills\":1514766000000,\"direction\":\"Flat\"}")))) // +4
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":222,\"mills\":1514765700000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":224,\"mills\":1514765400000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":226,\"mills\":1514765100000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":228,\"mills\":1514764800000,\"direction\":\"Flat\"}"))))
private fun generateValidBgData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 214.0, timestamp = 1514766900000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 216.0, timestamp = 1514766600000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 219.0, timestamp = 1514766300000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 223.0, timestamp = 1514766000000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 222.0, timestamp = 1514765700000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 224.0, timestamp = 1514765400000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 226.0, timestamp = 1514765100000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 228.0, timestamp = 1514764800000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
return list
}
}

View file

@ -4,9 +4,7 @@ import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.elements.InputBg
@ -73,7 +71,7 @@ open class TriggerTestBase : TestBaseWithProfile() {
if (it is InputBg) {
it.profileFunction = profileFunction
}
if (it is InputTempTarget) {
if (it is InputTempTarget) {
it.profileFunction = profileFunction
}
if (it is GlucoseStatus) {
@ -83,9 +81,6 @@ open class TriggerTestBase : TestBaseWithProfile() {
if (it is StaticLabel) {
it.resourceHelper = resourceHelper
}
if (it is BgReading) {
it.dateUtil = dateUtil
}
}
}

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint
@ -39,9 +39,6 @@ import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyString
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
@ -75,12 +72,6 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
it.aapsLogger = aapsLogger
it.resourceHelper = resourceHelper
}
if (it is BgReading) {
it.aapsLogger = aapsLogger
it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper
it.profileFunction = profileFunction
}
if (it is AuthRequest) {
it.aapsLogger = aapsLogger
it.smsCommunicatorPlugin = smsCommunicatorPlugin
@ -98,9 +89,8 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
private var hasBeenRun = false
@Before fun prepareTests() {
val reading = BgReading(injector)
reading.value = 100.0
val bgList: MutableList<BgReading> = ArrayList()
val reading = GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = 1514766900000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)
val bgList: MutableList<GlucoseValue> = ArrayList()
bgList.add(reading)
`when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit)
@ -176,7 +166,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
`when`(profileFunction.getUnits()).thenReturn(Constants.MGDL)
`when`(otp.name()).thenReturn("User")
`when`(otp.checkOTP(anyString())).thenReturn(OneTimePasswordValidationResult.OK)
`when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.OK)
`when`(resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed")
`when`(resourceHelper.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.")
@ -195,7 +185,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
`when`(resourceHelper.gs(R.string.smscommunicator_loopisdisabled)).thenReturn("Loop is disabled")
`when`(resourceHelper.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled")
`when`(resourceHelper.gs(R.string.wrongformat)).thenReturn("Wrong format")
`when`(resourceHelper.gs(eq(R.string.wrongTbrDuration), any())).thenAnswer({ i: InvocationOnMock -> "TBR duration must be a multiple of " + i.getArguments()[1] + " minutes and greater than 0."})
`when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.wrongTbrDuration), ArgumentMatchers.any())).thenAnswer({ i: InvocationOnMock -> "TBR duration must be a multiple of " + i.getArguments()[1] + " minutes and greater than 0." })
`when`(resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled")
`when`(resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled")
`when`(resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled")
@ -450,9 +440,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
passCode = smsCommunicatorPlugin.messageToConfirm?.confirmCode!!
// ignore from other number
smsCommunicatorPlugin.processSms(Sms("5678", passCode))
`when`(otp.checkOTP(anyString())).thenReturn(OneTimePasswordValidationResult.ERROR_WRONG_OTP)
`when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.ERROR_WRONG_OTP)
smsCommunicatorPlugin.processSms(Sms("1234", "XXXX"))
`when`(otp.checkOTP(anyString())).thenReturn(OneTimePasswordValidationResult.OK)
`when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.OK)
Assert.assertEquals("XXXX", smsCommunicatorPlugin.messages[3].text)
Assert.assertEquals("Wrong code. Command cancelled.", smsCommunicatorPlugin.messages[4].text)
//then correct code should not work

View file

@ -3,12 +3,9 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import org.json.JSONException
import org.json.JSONObject
import org.junit.Assert
import org.junit.Before
import org.junit.Test
@ -36,9 +33,6 @@ class GlucoseStatusTest : TestBase() {
it.aapsLogger = aapsLogger
it.iobCobCalculatorPlugin = iobCobCalculatorPlugin
}
if (it is BgReading) {
it.dateUtil = dateUtil
}
}
}
@ -127,78 +121,57 @@ class GlucoseStatusTest : TestBase() {
}
// [{"mgdl":214,"mills":1521895773113,"device":"xDrip-DexcomG5","direction":"Flat","filtered":191040,"unfiltered":205024,"noise":1,"rssi":100},{"mgdl":219,"mills":1521896073352,"device":"xDrip-DexcomG5","direction":"Flat","filtered":200160,"unfiltered":209760,"noise":1,"rssi":100},{"mgdl":222,"mills":1521896372890,"device":"xDrip-DexcomG5","direction":"Flat","filtered":207360,"unfiltered":212512,"noise":1,"rssi":100},{"mgdl":220,"mills":1521896673062,"device":"xDrip-DexcomG5","direction":"Flat","filtered":211488,"unfiltered":210688,"noise":1,"rssi":100},{"mgdl":193,"mills":1521896972933,"device":"xDrip-DexcomG5","direction":"Flat","filtered":212384,"unfiltered":208960,"noise":1,"rssi":100},{"mgdl":181,"mills":1521897273336,"device":"xDrip-DexcomG5","direction":"SingleDown","filtered":210592,"unfiltered":204320,"noise":1,"rssi":100},{"mgdl":176,"mills":1521897572875,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":206720,"unfiltered":197440,"noise":1,"rssi":100},{"mgdl":168,"mills":1521897872929,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":201024,"unfiltered":187904,"noise":1,"rssi":100},{"mgdl":161,"mills":1521898172814,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":193376,"unfiltered":178144,"noise":1,"rssi":100},{"mgdl":148,"mills":1521898472879,"device":"xDrip-DexcomG5","direction":"SingleDown","filtered":183264,"unfiltered":161216,"noise":1,"rssi":100},{"mgdl":139,"mills":1521898772862,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":170784,"unfiltered":148928,"noise":1,"rssi":100},{"mgdl":132,"mills":1521899072896,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":157248,"unfiltered":139552,"noise":1,"rssi":100},{"mgdl":125,"mills":1521899372834,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":144416,"unfiltered":129616.00000000001,"noise":1,"rssi":100},{"mgdl":128,"mills":1521899973456,"device":"xDrip-DexcomG5","direction":"Flat","filtered":130240.00000000001,"unfiltered":133536,"noise":1,"rssi":100},{"mgdl":132,"mills":1521900573287,"device":"xDrip-DexcomG5","direction":"Flat","filtered":133504,"unfiltered":138720,"noise":1,"rssi":100},{"mgdl":127,"mills":1521900873711,"device":"xDrip-DexcomG5","direction":"Flat","filtered":136480,"unfiltered":132992,"noise":1,"rssi":100},{"mgdl":127,"mills":1521901180151,"device":"xDrip-DexcomG5","direction":"Flat","filtered":136896,"unfiltered":132128,"noise":1,"rssi":100},{"mgdl":125,"mills":1521901473582,"device":"xDrip-DexcomG5","direction":"Flat","filtered":134624,"unfiltered":129696,"noise":1,"rssi":100},{"mgdl":120,"mills":1521901773597,"device":"xDrip-DexcomG5","direction":"Flat","filtered":130704.00000000001,"unfiltered":123376,"noise":1,"rssi":100},{"mgdl":116,"mills":1521902075855,"device":"xDrip-DexcomG5","direction":"Flat","filtered":126272,"unfiltered":118448,"noise":1,"rssi":100}]
private fun generateValidBgData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
try {
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":214,\"mills\":1514766900000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":216,\"mills\":1514766600000,\"direction\":\"Flat\"}")))) // +2
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":219,\"mills\":1514766300000,\"direction\":\"Flat\"}")))) // +3
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":223,\"mills\":1514766000000,\"direction\":\"Flat\"}")))) // +4
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":222,\"mills\":1514765700000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":224,\"mills\":1514765400000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":226,\"mills\":1514765100000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":228,\"mills\":1514764800000,\"direction\":\"Flat\"}"))))
} catch (e: JSONException) {
throw RuntimeException(e)
}
private fun generateValidBgData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 214.0, timestamp = 1514766900000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 216.0, timestamp = 1514766600000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 219.0, timestamp = 1514766300000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 223.0, timestamp = 1514766000000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 222.0, timestamp = 1514765700000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 224.0, timestamp = 1514765400000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 226.0, timestamp = 1514765100000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 228.0, timestamp = 1514764800000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
return list
}
private fun generateMostRecentBgData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
try {
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":214,\"mills\":1514766900000,\"direction\":\"Flat\"}"))))
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":216,\"mills\":1514766800000,\"direction\":\"Flat\"}")))) // +2
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":216,\"mills\":1514766600000,\"direction\":\"Flat\"}"))))
} catch (e: JSONException) {
throw RuntimeException(e)
}
private fun generateMostRecentBgData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 214.0, timestamp = 1514766900000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 216.0, timestamp = 1514766800000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 216.0, timestamp = 1514766600000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
return list
}
private fun generateInsufficientBgData(): List<BgReading> {
private fun generateInsufficientBgData(): List<GlucoseValue> {
return ArrayList()
}
private fun generateOldBgData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
try {
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":228,\"mills\":1514764800000,\"direction\":\"Flat\"}"))))
} catch (e: JSONException) {
throw RuntimeException(e)
}
private fun generateOldBgData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 228.0, timestamp = 1514764800000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
return list
}
private fun generateOneCurrentRecordBgData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
try {
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":214,\"mills\":1514766900000,\"direction\":\"Flat\"}"))))
} catch (e: JSONException) {
throw RuntimeException(e)
}
private fun generateOneCurrentRecordBgData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 214.0, timestamp = 1514766900000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
return list
}
private fun generateLibreTestData(): List<BgReading> {
val list: MutableList<BgReading> = ArrayList()
try {
val endTime = 1514766900000L
val latestReading = 100.0
// Now
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":$latestReading,\"mills\":$endTime,\"direction\":\"Flat\"}"))))
// One minute ago
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":" + latestReading + ",\"mills\":" + (endTime - 1000 * 60 * 1) + ",\"direction\":\"Flat\"}"))))
// Two minutes ago
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":" + latestReading + ",\"mills\":" + (endTime - 1000 * 60 * 2) + ",\"direction\":\"Flat\"}"))))
private fun generateLibreTestData(): List<GlucoseValue> {
val list: MutableList<GlucoseValue> = ArrayList()
val endTime = 1514766900000L
val latestReading = 100.0
// Now
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = latestReading, timestamp = endTime, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
// One minute ago
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = latestReading, timestamp = endTime - 1000 * 60 * 1, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
// Two minutes ago
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = latestReading, timestamp = endTime - 1000 * 60 * 2, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
// Three minutes and beyond at constant rate
for (i in 3..49) {
list.add(BgReading(injector, NSSgv(JSONObject("{\"mgdl\":" + (latestReading + i * 2) + ",\"mills\":" + (endTime - 1000 * 60 * i) + ",\"direction\":\"Flat\"}"))))
}
} catch (e: JSONException) {
throw RuntimeException(e)
}
// Three minutes and beyond at constant rate
for (i in 3..49)
list.add(GlucoseValue(raw = 0.0, noise = 0.0, value = latestReading + i * 2, timestamp = endTime - 1000 * 60 * i, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
return list
}
}

View file

@ -3,10 +3,11 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
@ -27,7 +28,7 @@ import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
@RunWith(PowerMockRunner::class)
@PrepareForTest(FabricPrivacy::class)
@PrepareForTest(FabricPrivacy::class, AppRepository::class)
class IobCobCalculatorPluginTest : TestBase() {
@Mock lateinit var sp: SP
@ -42,129 +43,123 @@ class IobCobCalculatorPluginTest : TestBase() {
@Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var repository: AppRepository
lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
val injector = HasAndroidInjector {
AndroidInjector {
if (it is BgReading) {
it.aapsLogger = aapsLogger
it.defaultValueHelper = defaultValueHelper
it.resourceHelper = resourceHelper
it.profileFunction = profileFunction
it.dateUtil = dateUtil
}
}
}
@Before
fun mock() {
iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil)
iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository)
}
@Test
fun isAbout5minDataTest() {
val bgReadingList: MutableList<BgReading> = ArrayList()
val bgReadingList: MutableList<GlucoseValue> = ArrayList()
// Super data should not be touched
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
// too much shifted data should return false
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(9).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(9).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
// too much shifted and missing data should return false
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(9).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(9).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
// too much shifted and missing data should return false
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(83).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(78).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(73).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(68).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(63).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(58).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(53).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(48).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(43).plus(T.secs(40)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(38).plus(T.secs(33)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(33).plus(T.secs(1)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(28).plus(T.secs(0)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(23).plus(T.secs(0)).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(16).plus(T.secs(36)).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(83).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(78).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(73).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(68).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(63).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(58).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(53).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(48).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(43).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(38).plus(T.secs(40)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(33).plus(T.secs(1)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(28).plus(T.secs(0)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(23).plus(T.secs(0)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(16).plus(T.secs(36)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
// slightly shifted data should return true
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs() - T.secs(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).plus(T.secs(10)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
// slightly shifted and missing data should return true
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs() - T.secs(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).plus(T.secs(10)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
}
@Test
fun createBucketedData5minTest() {
val bgReadingList: MutableList<BgReading> = ArrayList()
val bgReadingList: MutableList<GlucoseValue> = ArrayList()
// Super data should not be touched
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
Assert.assertEquals(bgReadingList[0].date, iobCobCalculatorPlugin.bucketedData[0].timestamp)
Assert.assertEquals(bgReadingList[3].date, iobCobCalculatorPlugin.bucketedData[3].timestamp)
Assert.assertEquals(bgReadingList[0].timestamp, iobCobCalculatorPlugin.bucketedData[0].timestamp)
Assert.assertEquals(bgReadingList[3].timestamp, iobCobCalculatorPlugin.bucketedData[3].timestamp)
Assert.assertEquals(bgReadingList.size.toLong(), iobCobCalculatorPlugin.bucketedData.size.toLong())
// Missing value should be replaced
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).plus(T.secs(10)).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
Assert.assertEquals(bgReadingList[0].date, iobCobCalculatorPlugin.bucketedData[0].timestamp)
Assert.assertEquals(bgReadingList[2].date, iobCobCalculatorPlugin.bucketedData[3].timestamp)
Assert.assertEquals(bgReadingList[0].timestamp, iobCobCalculatorPlugin.bucketedData[0].timestamp)
Assert.assertEquals(bgReadingList[2].timestamp, iobCobCalculatorPlugin.bucketedData[3].timestamp)
Assert.assertEquals(bgReadingList.size + 1.toLong(), iobCobCalculatorPlugin.bucketedData.size.toLong())
// drift should be cleared
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs() + T.secs(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs() + T.secs(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs() - T.secs(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(0).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs() + T.secs(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs() + T.secs(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs() + T.secs(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(0).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
@ -176,8 +171,8 @@ class IobCobCalculatorPluginTest : TestBase() {
// bucketed data should return null if not enough bg data
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(30).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(30).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
@ -185,9 +180,9 @@ class IobCobCalculatorPluginTest : TestBase() {
// data should be reconstructed
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(50).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(45).msecs()).value(90.0))
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(40.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(50).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 90.0, timestamp = T.mins(45).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 40.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
@ -201,9 +196,9 @@ class IobCobCalculatorPluginTest : TestBase() {
// non 5min data should be reconstructed
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(50).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(48).msecs()).value(96.0))
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(40.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(50).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 96.0, timestamp = T.mins(48).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 40.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
@ -222,122 +217,34 @@ class IobCobCalculatorPluginTest : TestBase() {
// real data gap test
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T13:34:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T13:14:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T13:09:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T13:04:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:59:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:54:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:49:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:44:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:39:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:34:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:29:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:24:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:09:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T12:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:59:55Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:34:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:29:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:24:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:09:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T11:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:34:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:29:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:24:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:09:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T10:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:35:05Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:30:17Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:24:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:09:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T09:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:40:02Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:34:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:29:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:24:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:09:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T08:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:34:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:30:03Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:25:17Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:14:58Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:09:58Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T07:04:58Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:59:58Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:54:58Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:34:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:29:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:24:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:10:03Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T06:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:49:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:34:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:29:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:24:57Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:19:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:14:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:09:57Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T05:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:50:03Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:44:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:39:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:34:57Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:29:57Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:24:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:19:57Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:14:57Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:10:03Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T04:04:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T03:59:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T03:54:56Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T03:50:03Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-09-05T03:44:57Z")).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:34:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:14:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:09:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:04:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:59:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:54:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:49:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:44:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:39:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:34:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:29:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:24:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:19:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:14:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:09:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:04:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T11:59:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:29:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:24:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:19:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:14:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:10:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:04:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:59:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:54:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:50:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:44:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
iobCobCalculatorPlugin.referenceTime = null
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
@ -347,34 +254,34 @@ class IobCobCalculatorPluginTest : TestBase() {
// 5min 4sec data
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:33:40Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:28:36Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:23:32Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:18:28Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:13:24Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:08:19Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T06:03:16Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:58:11Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:53:07Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:48:03Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:42:58Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:37:54Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:32:51Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:27:46Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:22:42Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:17:38Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:12:33Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:07:29Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T05:02:26Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T04:57:21Z")).value(100.0))
bgReadingList.add(BgReading(injector).date(DateUtil.fromISODateString("2018-10-05T04:52:17Z")).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:33:40Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:28:36Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:23:32Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:18:28Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:13:24Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:08:19Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:03:16Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:58:11Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:53:07Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:48:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:42:58Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:37:54Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:32:51Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:27:46Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:22:42Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:17:38Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:12:33Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:07:29Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:02:26Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T04:57:21Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T04:52:17Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
}
@Test
fun bgReadingsTest() {
val bgReadingList: List<BgReading> = ArrayList()
val bgReadingList: List<GlucoseValue> = ArrayList()
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(bgReadingList, iobCobCalculatorPlugin.bgReadings)
}
@ -386,47 +293,47 @@ class IobCobCalculatorPluginTest : TestBase() {
@Test
fun findNewerTest() {
val bgReadingList: MutableList<BgReading> = ArrayList()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
val bgReadingList: MutableList<GlucoseValue> = ArrayList()
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(T.mins(10).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(8).msecs())!!.date)
Assert.assertEquals(T.mins(5).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(5).msecs())!!.date)
Assert.assertEquals(T.mins(10).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(10).msecs())!!.date)
Assert.assertEquals(T.mins(20).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(20).msecs())!!.date)
Assert.assertEquals(T.mins(10).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(8).msecs())!!.timestamp)
Assert.assertEquals(T.mins(5).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(5).msecs())!!.timestamp)
Assert.assertEquals(T.mins(10).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(10).msecs())!!.timestamp)
Assert.assertEquals(T.mins(20).msecs(), iobCobCalculatorPlugin.findNewer(T.mins(20).msecs())!!.timestamp)
Assert.assertEquals(null, iobCobCalculatorPlugin.findNewer(T.mins(22).msecs()))
}
@Test
fun findOlderTest() {
val bgReadingList: MutableList<BgReading> = ArrayList()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
val bgReadingList: MutableList<GlucoseValue> = ArrayList()
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(T.mins(5).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(8).msecs())!!.date)
Assert.assertEquals(T.mins(5).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(5).msecs())!!.date)
Assert.assertEquals(T.mins(10).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(10).msecs())!!.date)
Assert.assertEquals(T.mins(20).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(20).msecs())!!.date)
Assert.assertEquals(T.mins(5).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(8).msecs())!!.timestamp)
Assert.assertEquals(T.mins(5).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(5).msecs())!!.timestamp)
Assert.assertEquals(T.mins(10).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(10).msecs())!!.timestamp)
Assert.assertEquals(T.mins(20).msecs(), iobCobCalculatorPlugin.findOlder(T.mins(20).msecs())!!.timestamp)
Assert.assertEquals(null, iobCobCalculatorPlugin.findOlder(T.mins(4).msecs()))
}
@Test
fun findPreviousTimeFromBucketedDataTest() {
val bgReadingList: MutableList<BgReading> = ArrayList()
val bgReadingList: MutableList<GlucoseValue> = ArrayList()
iobCobCalculatorPlugin.bgReadings = bgReadingList
iobCobCalculatorPlugin.createBucketedData()
Assert.assertEquals(null, iobCobCalculatorPlugin.findPreviousTimeFromBucketedData(1000))
// Super data should not be touched
bgReadingList.clear()
bgReadingList.add(BgReading(injector).date(T.mins(20).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(15).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(10).msecs()).value(100.0))
bgReadingList.add(BgReading(injector).date(T.mins(5).msecs()).value(100.0))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
iobCobCalculatorPlugin.createBucketedData()
Assert.assertEquals(null, iobCobCalculatorPlugin.findPreviousTimeFromBucketedData(T.mins(4).msecs()))

View file

@ -2,6 +2,7 @@ package info.nightscout.androidaps.core.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.GlucoseValueDataPoint
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.*
@ -19,7 +20,7 @@ abstract class CoreDataClassesModule {
@ContributesAndroidInjector abstract fun profileInjector(): Profile
@ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore
@ContributesAndroidInjector abstract fun bgReadingInjector(): BgReading
@ContributesAndroidInjector abstract fun glucoseValueDataPointInjector(): GlucoseValueDataPoint
@ContributesAndroidInjector abstract fun treatmentInjector(): Treatment
@ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch
@ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal

View file

@ -0,0 +1,78 @@
package info.nightscout.androidaps.data
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
class GlucoseValueDataPoint @Inject constructor(
val injector: HasAndroidInjector,
val data: GlucoseValue
) : DataPointWithLabelInterface {
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper
init {
injector.androidInjector().inject(this)
}
fun valueToUnits(units: String): Double =
if (units == Constants.MGDL) data.value else data.value * Constants.MGDL_TO_MMOLL
override fun getX(): Double {
return data.timestamp.toDouble()
}
override fun getY(): Double {
return valueToUnits(profileFunction.getUnits())
}
override fun setY(y: Double) {}
override fun getLabel(): String? = null
override fun getDuration(): Long = 0
override fun getShape(): PointsWithLabelGraphSeries.Shape =
if (isPrediction) PointsWithLabelGraphSeries.Shape.PREDICTION
else PointsWithLabelGraphSeries.Shape.BG
override fun getSize(): Float = 1f
override fun getColor(): Int {
val units = profileFunction.getUnits()
val lowLine = defaultValueHelper.determineLowLine()
val highLine = defaultValueHelper.determineHighLine()
return when {
isPrediction -> predictionColor
valueToUnits(units) < lowLine -> resourceHelper.gc(R.color.low)
valueToUnits(units) > highLine -> resourceHelper.gc(R.color.high)
else -> resourceHelper.gc(R.color.inrange)
}
}
val predictionColor: Int
get() {
return when (data.sourceSensor) {
GlucoseValue.SourceSensor.IOB_PREDICTION -> resourceHelper.gc(R.color.iob)
GlucoseValue.SourceSensor.COB_PREDICTION -> resourceHelper.gc(R.color.cob)
GlucoseValue.SourceSensor.aCOB_PREDICTION -> -0x7f000001 and resourceHelper.gc(R.color.cob)
GlucoseValue.SourceSensor.UAM_PREDICTION -> resourceHelper.gc(R.color.uam)
GlucoseValue.SourceSensor.ZT_PREDICTION -> resourceHelper.gc(R.color.zt)
else -> R.color.white
}
}
private val isPrediction: Boolean
get() = data.sourceSensor == GlucoseValue.SourceSensor.IOB_PREDICTION ||
data.sourceSensor == GlucoseValue.SourceSensor.COB_PREDICTION ||
data.sourceSensor == GlucoseValue.SourceSensor.aCOB_PREDICTION ||
data.sourceSensor == GlucoseValue.SourceSensor.UAM_PREDICTION ||
data.sourceSensor == GlucoseValue.SourceSensor.ZT_PREDICTION
}

View file

@ -1,171 +0,0 @@
package info.nightscout.androidaps.db
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
class BgReading : DataPointWithLabelInterface {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var repository: AppRepository
var data: GlucoseValue
// Compatibility functions
fun setDate(timeStamp: Long) {
data.timestamp = timeStamp
}
fun getDate(): Long = data.timestamp
fun getValue(): Double = data.value
fun setValue(value: Double) {
data.value = value
}
var isCOBPrediction = false // true when drawing predictions as bg points (COB)
var isaCOBPrediction = false // true when drawing predictions as bg points (aCOB)
var isIOBPrediction = false // true when drawing predictions as bg points (IOB)
var isUAMPrediction = false // true when drawing predictions as bg points (UAM)
var isZTPrediction = false // true when drawing predictions as bg points (ZT)
@Deprecated("Create only with data")
constructor(injector: HasAndroidInjector) {
injector.androidInjector().inject(this)
data = GlucoseValue(
timestamp = 0,
utcOffset = 0,
raw = null,
value = 0.0,
trendArrow = GlucoseValue.TrendArrow.NONE,
noise = null,
sourceSensor = GlucoseValue.SourceSensor.UNKNOWN
)
}
constructor(injector: HasAndroidInjector, glucoseValue: GlucoseValue) {
injector.androidInjector().inject(this)
data = glucoseValue
}
fun valueToUnits(units: String): Double =
if (units == Constants.MGDL) data.value else data.value * Constants.MGDL_TO_MMOLL
fun valueToUnitsToString(units: String): String =
if (units == Constants.MGDL) DecimalFormatter.to0Decimal(data.value)
else DecimalFormatter.to1Decimal(data.value * Constants.MGDL_TO_MMOLL)
fun directionToSymbol(): String =
if (data.trendArrow == GlucoseValue.TrendArrow.NONE) calculateDirection().symbol
else data.trendArrow.symbol
fun date(date: Long): BgReading {
data.timestamp = date
return this
}
fun value(value: Double): BgReading {
data.value = value
return this
}
// ------------------ DataPointWithLabelInterface ------------------
override fun getX(): Double {
return data.timestamp.toDouble()
}
override fun getY(): Double {
return valueToUnits(profileFunction.getUnits())
}
override fun setY(y: Double) {}
override fun getLabel(): String? = null
override fun getDuration(): Long = 0
override fun getShape(): PointsWithLabelGraphSeries.Shape =
if (isPrediction) PointsWithLabelGraphSeries.Shape.PREDICTION
else PointsWithLabelGraphSeries.Shape.BG
override fun getSize(): Float = 1f
override fun getColor(): Int {
val units = profileFunction.getUnits()
val lowLine = defaultValueHelper.determineLowLine()
val highLine = defaultValueHelper.determineHighLine()
return when {
isPrediction -> predictionColor
valueToUnits(units) < lowLine -> resourceHelper.gc(R.color.low)
valueToUnits(units) > highLine -> resourceHelper.gc(R.color.high)
else -> resourceHelper.gc(R.color.inrange)
}
}
val predictionColor: Int
get() {
return when {
isIOBPrediction -> resourceHelper.gc(R.color.iob)
isCOBPrediction -> resourceHelper.gc(R.color.cob)
isaCOBPrediction -> -0x7f000001 and resourceHelper.gc(R.color.cob)
isUAMPrediction -> resourceHelper.gc(R.color.uam)
isZTPrediction -> resourceHelper.gc(R.color.zt)
else -> R.color.white
}
}
private val isPrediction: Boolean
get() = isaCOBPrediction || isCOBPrediction || isIOBPrediction || isUAMPrediction || isZTPrediction
// Copied from xDrip+
fun calculateDirection(): GlucoseValue.TrendArrow {
// Rework to get bgreaings from internal DB and calculate on that base
val bgReadingsList = repository.compatGetBgReadingsDataFromTime(data.timestamp - T.mins(10).msecs(), false)
.blockingGet()
if (bgReadingsList == null || bgReadingsList.size < 2) return GlucoseValue.TrendArrow.NONE
var current = bgReadingsList[1]
var previous = bgReadingsList[0]
if (bgReadingsList[1].timestamp < bgReadingsList[0].timestamp) {
current = bgReadingsList[0]
previous = bgReadingsList[1]
}
val slope: Double
// Avoid division by 0
slope = if (current.timestamp == previous.timestamp) 0.0 else (previous.value - current.value) / (previous.timestamp - current.timestamp)
aapsLogger.error(LTag.GLUCOSE, "Slope is :" + slope + " delta " + (previous.value - current.value) + " date difference " + (current.timestamp - previous.timestamp))
val slope_by_minute = slope * 60000
var arrow = GlucoseValue.TrendArrow.NONE
if (slope_by_minute <= -3.5) {
arrow = GlucoseValue.TrendArrow.DOUBLE_DOWN
} else if (slope_by_minute <= -2) {
arrow = GlucoseValue.TrendArrow.SINGLE_DOWN
} else if (slope_by_minute <= -1) {
arrow = GlucoseValue.TrendArrow.FORTY_FIVE_DOWN
} else if (slope_by_minute <= 1) {
arrow = GlucoseValue.TrendArrow.FLAT
} else if (slope_by_minute <= 2) {
arrow = GlucoseValue.TrendArrow.FORTY_FIVE_UP
} else if (slope_by_minute <= 3.5) {
arrow = GlucoseValue.TrendArrow.SINGLE_UP
} else if (slope_by_minute <= 40) {
arrow = GlucoseValue.TrendArrow.DOUBLE_UP
}
aapsLogger.error(LTag.GLUCOSE, "Direction set to: $arrow")
return arrow
}
private fun isSlopeNameInvalid(direction: String?): Boolean {
return direction!!.compareTo("NOT_COMPUTABLE") == 0 || direction.compareTo("NOT COMPUTABLE") == 0 || direction.compareTo("OUT_OF_RANGE") == 0 || direction.compareTo("OUT OF RANGE") == 0 || direction.compareTo("NONE") == 0 || direction.compareTo("NotComputable") == 0
}
}

View file

@ -1,438 +0,0 @@
package info.nightscout.androidaps.plugins.aps.loop;
import android.text.Spanned;
import androidx.annotation.NonNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.core.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.HtmlHelper;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
* Created by mike on 09.06.2016.
*/
public class APSResult {
@Inject HasAndroidInjector injector;
@Inject public AAPSLogger aapsLogger;
@Inject ConstraintChecker constraintChecker;
@Inject SP sp;
@Inject ActivePluginProvider activePlugin;
@Inject TreatmentsInterface treatmentsPlugin;
@Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper;
@Inject
public APSResult(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
}
public long date = 0;
public String reason;
public double rate;
public int percent;
public boolean usePercent = false;
public int duration;
public boolean tempBasalRequested = false;
public boolean bolusRequested = false;
public IobTotal iob;
public JSONObject json = new JSONObject();
public boolean hasPredictions = false;
public double smb = 0d; // super micro bolus in units
public long deliverAt = 0;
public double targetBG = 0d;
public int carbsReq = 0;
public int carbsReqWithin = 0;
public Constraint<Double> inputConstraints;
public Constraint<Double> rateConstraint;
public Constraint<Integer> percentConstraint;
public Constraint<Double> smbConstraint;
public APSResult rate(double rate) {
this.rate = rate;
return this;
}
public APSResult duration(int duration) {
this.duration = duration;
return this;
}
public APSResult percent(int percent) {
this.percent = percent;
return this;
}
public APSResult tempBasalRequested(boolean tempBasalRequested) {
this.tempBasalRequested = tempBasalRequested;
return this;
}
public APSResult usePercent(boolean usePercent) {
this.usePercent = usePercent;
return this;
}
public APSResult json(JSONObject json) {
this.json = json;
return this;
}
public String getCarbsRequiredText() {
return String.format(resourceHelper.gs(R.string.carbsreq), carbsReq, carbsReqWithin);
}
@NonNull @Override
public String toString() {
final PumpInterface pump = activePlugin.getActivePump();
if (isChangeRequested()) {
String ret;
// rate
if (rate == 0 && duration == 0)
ret = resourceHelper.gs(R.string.canceltemp) + "\n";
else if (rate == -1)
ret = resourceHelper.gs(R.string.let_temp_basal_run) + "\n";
else if (usePercent)
ret = resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)\n" +
resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n";
else
ret = resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) \n" +
resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n";
// smb
if (smb != 0)
ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump(), resourceHelper) + "\n");
if (isCarbsRequired()) {
ret += getCarbsRequiredText() + "\n";
}
// reason
ret += resourceHelper.gs(R.string.reason) + ": " + reason;
return ret;
}
if (isCarbsRequired()) {
return getCarbsRequiredText();
}
return resourceHelper.gs(R.string.nochangerequested);
}
public Spanned toSpanned() {
final PumpInterface pump = activePlugin.getActivePump();
if (isChangeRequested()) {
String ret;
// rate
if (rate == 0 && duration == 0)
ret = resourceHelper.gs(R.string.canceltemp) + "<br>";
else if (rate == -1)
ret = resourceHelper.gs(R.string.let_temp_basal_run) + "<br>";
else if (usePercent)
ret = "<b>" + resourceHelper.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(percent) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)<br>" +
"<b>" + resourceHelper.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
else
ret = "<b>" + resourceHelper.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100d) + "%) <br>" +
"<b>" + resourceHelper.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
// smb
if (smb != 0)
ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump(), resourceHelper) + "<br>");
if (isCarbsRequired()) {
ret += getCarbsRequiredText() + "<br>";
}
// reason
ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
return HtmlHelper.INSTANCE.fromHtml(ret);
}
if (isCarbsRequired()) {
return HtmlHelper.INSTANCE.fromHtml(getCarbsRequiredText());
}
return HtmlHelper.INSTANCE.fromHtml(resourceHelper.gs(R.string.nochangerequested));
}
public APSResult newAndClone(HasAndroidInjector injector) {
APSResult newResult = new APSResult(injector);
doClone(newResult);
return newResult;
}
protected void doClone(APSResult newResult) {
newResult.date = date;
newResult.reason = reason != null ? reason : null;
newResult.rate = rate;
newResult.duration = duration;
newResult.tempBasalRequested = tempBasalRequested;
newResult.bolusRequested = bolusRequested;
newResult.iob = iob;
try {
newResult.json = new JSONObject(json.toString());
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
newResult.hasPredictions = hasPredictions;
newResult.smb = smb;
newResult.deliverAt = deliverAt;
newResult.rateConstraint = rateConstraint;
newResult.smbConstraint = smbConstraint;
newResult.percent = percent;
newResult.usePercent = usePercent;
newResult.carbsReq = carbsReq;
newResult.carbsReqWithin = carbsReqWithin;
newResult.targetBG = targetBG;
}
public JSONObject json() {
JSONObject json = new JSONObject();
try {
if (isChangeRequested()) {
json.put("rate", rate);
json.put("duration", duration);
json.put("reason", reason);
}
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
return json;
}
public List<BgReading> getPredictions() {
List<BgReading> array = new ArrayList<>();
try {
long startTime = date;
if (json != null && json.has("predBGs")) {
JSONObject predBGs = json.getJSONObject("predBGs");
if (predBGs.has("IOB")) {
JSONArray iob = predBGs.getJSONArray("IOB");
for (int i = 1; i < iob.length(); i++) {
BgReading bg = new BgReading(injector);
bg.setValue(iob.getInt(i));
bg.setDate(startTime + i * 5 * 60 * 1000L);
bg.setIOBPrediction(true);
array.add(bg);
}
}
if (predBGs.has("aCOB")) {
JSONArray iob = predBGs.getJSONArray("aCOB");
for (int i = 1; i < iob.length(); i++) {
BgReading bg = new BgReading(injector);
bg.setValue(iob.getInt(i));
bg.setDate(startTime + i * 5 * 60 * 1000L);
bg.setIsaCOBPrediction(true);
array.add(bg);
}
}
if (predBGs.has("COB")) {
JSONArray iob = predBGs.getJSONArray("COB");
for (int i = 1; i < iob.length(); i++) {
BgReading bg = new BgReading(injector);
bg.setValue(iob.getInt(i));
bg.setDate(startTime + i * 5 * 60 * 1000L);
bg.setCOBPrediction(true);
array.add(bg);
}
}
if (predBGs.has("UAM")) {
JSONArray iob = predBGs.getJSONArray("UAM");
for (int i = 1; i < iob.length(); i++) {
BgReading bg = new BgReading(injector);
bg.setValue(iob.getInt(i));
bg.setDate(startTime + i * 5 * 60 * 1000L);
bg.setUAMPrediction(true);
array.add(bg);
}
}
if (predBGs.has("ZT")) {
JSONArray iob = predBGs.getJSONArray("ZT");
for (int i = 1; i < iob.length(); i++) {
BgReading bg = new BgReading(injector);
bg.setValue(iob.getInt(i));
bg.setDate(startTime + i * 5 * 60 * 1000L);
bg.setZTPrediction(true);
array.add(bg);
}
}
}
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
return array;
}
public long getLatestPredictionsTime() {
long latest = 0;
try {
long startTime = date;
if (json != null && json.has("predBGs")) {
JSONObject predBGs = json.getJSONObject("predBGs");
if (predBGs.has("IOB")) {
JSONArray iob = predBGs.getJSONArray("IOB");
latest = Math.max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L);
}
if (predBGs.has("aCOB")) {
JSONArray iob = predBGs.getJSONArray("aCOB");
latest = Math.max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L);
}
if (predBGs.has("COB")) {
JSONArray iob = predBGs.getJSONArray("COB");
latest = Math.max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L);
}
if (predBGs.has("UAM")) {
JSONArray iob = predBGs.getJSONArray("UAM");
latest = Math.max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L);
}
if (predBGs.has("ZT")) {
JSONArray iob = predBGs.getJSONArray("ZT");
latest = Math.max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L);
}
}
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
return latest;
}
public boolean isCarbsRequired() {
return carbsReq > 0;
}
public boolean isChangeRequested() {
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
// closed loop mode: handle change at driver level
if (closedLoopEnabled.value()) {
aapsLogger.debug(LTag.APS, "DEFAULT: Closed mode");
return tempBasalRequested || bolusRequested;
}
// open loop mode: try to limit request
if (!tempBasalRequested && !bolusRequested) {
aapsLogger.debug(LTag.APS, "FALSE: No request");
return false;
}
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now);
PumpInterface pump = activePlugin.getActivePump();
Profile profile = profileFunction.getProfile();
if (profile == null) {
aapsLogger.error("FALSE: No Profile");
return false;
}
if (usePercent) {
if (activeTemp == null && percent == 100) {
aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp");
return false;
}
if (activeTemp != null && Math.abs(percent - activeTemp.tempBasalConvertedToPercent(now, profile)) < pump.getPumpDescription().basalStep) {
aapsLogger.debug(LTag.APS, "FALSE: Temp equal");
return false;
}
// always report zerotemp
if (percent == 0) {
aapsLogger.debug(LTag.APS, "TRUE: Zero temp");
return true;
}
// always report hightemp
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
if (percent == pumpLimit) {
aapsLogger.debug(LTag.APS, "TRUE: Pump limit");
return true;
}
}
// report change bigger than 30%
double percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30d);
percentMinChangeChange /= 100d;
double lowThreshold = 1 - percentMinChangeChange;
double highThreshold = 1 + percentMinChangeChange;
double change = percent / 100d;
if (activeTemp != null)
change = percent / (double) activeTemp.tempBasalConvertedToPercent(now, profile);
if (change < lowThreshold || change > highThreshold) {
aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + (change * 100d) + "%");
return true;
} else {
aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + (change * 100d) + "%");
return false;
}
} else {
if (activeTemp == null && rate == pump.getBaseBasalRate()) {
aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp");
return false;
}
if (activeTemp != null && Math.abs(rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
aapsLogger.debug(LTag.APS, "FALSE: Temp equal");
return false;
}
// always report zerotemp
if (rate == 0) {
aapsLogger.debug(LTag.APS, "TRUE: Zero temp");
return true;
}
// always report hightemp
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
if (rate == pumpLimit) {
aapsLogger.debug(LTag.APS, "TRUE: Pump limit");
return true;
}
}
// report change bigger than 30%
double percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30d);
percentMinChangeChange /= 100d;
double lowThreshold = 1 - percentMinChangeChange;
double highThreshold = 1 + percentMinChangeChange;
double change = rate / profile.getBasal();
if (activeTemp != null)
change = rate / activeTemp.tempBasalConvertedToAbsolute(now, profile);
if (change < lowThreshold || change > highThreshold) {
aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + (change * 100d) + "%");
return true;
} else {
aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + (change * 100d) + "%");
return false;
}
}
}
}

View file

@ -0,0 +1,399 @@
package info.nightscout.androidaps.plugins.aps.loop
import android.text.Spanned
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.data.GlucoseValueDataPoint
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper.fromHtml
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
import kotlin.math.abs
import kotlin.math.max
/**
* Created by mike on 09.06.2016.
*/
open class APSResult @Inject constructor(val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var sp: SP
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var treatmentsPlugin: TreatmentsInterface
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper
var date: Long = 0
var reason: String? = null
var rate = 0.0
var percent = 0
var usePercent = false
var duration = 0
var tempBasalRequested = false
var bolusRequested = false
var iob: IobTotal? = null
var json: JSONObject? = JSONObject()
var hasPredictions = false
var smb = 0.0 // super micro bolus in units
var deliverAt: Long = 0
var targetBG = 0.0
var carbsReq = 0
var carbsReqWithin = 0
var inputConstraints: Constraint<Double>? = null
var rateConstraint: Constraint<Double>? = null
var percentConstraint: Constraint<Int>? = null
var smbConstraint: Constraint<Double>? = null
init {
injector.androidInjector().inject(this)
}
fun rate(rate: Double): APSResult {
this.rate = rate
return this
}
fun duration(duration: Int): APSResult {
this.duration = duration
return this
}
fun percent(percent: Int): APSResult {
this.percent = percent
return this
}
fun tempBasalRequested(tempBasalRequested: Boolean): APSResult {
this.tempBasalRequested = tempBasalRequested
return this
}
fun usePercent(usePercent: Boolean): APSResult {
this.usePercent = usePercent
return this
}
fun json(json: JSONObject?): APSResult {
this.json = json
return this
}
val carbsRequiredText: String
get() = String.format(resourceHelper.gs(R.string.carbsreq), carbsReq, carbsReqWithin)
override fun toString(): String {
val pump = activePlugin.activePump
if (isChangeRequested) {
// rate
var ret: String = if (rate == 0.0 && duration == 0) "${resourceHelper.gs(R.string.canceltemp)}\n"
else if (rate == -1.0) "${resourceHelper.gs(R.string.let_temp_basal_run)}\n"
else if (usePercent) "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h)\n" +
"${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min\n"
else "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%)" +
"${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min\n"
// smb
if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, resourceHelper)}\n"
if (isCarbsRequired) {
ret += "$carbsRequiredText\n"
}
// reason
ret += resourceHelper.gs(R.string.reason) + ": " + reason
return ret
}
return if (isCarbsRequired) {
carbsRequiredText
} else resourceHelper.gs(R.string.nochangerequested)
}
fun toSpanned(): Spanned {
val pump = activePlugin.activePump
if (isChangeRequested) {
// rate
var ret: String = if (rate == 0.0 && duration == 0) resourceHelper.gs(R.string.canceltemp) + "<br>" else if (rate == -1.0) resourceHelper.gs(R.string.let_temp_basal_run) + "<br>" else if (usePercent) "<b>" + resourceHelper.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(percent.toDouble()) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0) + " U/h)<br>" +
"<b>" + resourceHelper.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min<br>" else "<b>" + resourceHelper.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100.0) + "%) <br>" +
"<b>" + resourceHelper.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min<br>"
// smb
if (smb != 0.0) ret += "<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, resourceHelper) + "<br>"
if (isCarbsRequired) {
ret += "$carbsRequiredText<br>"
}
// reason
ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason!!.replace("<", "&lt;").replace(">", "&gt;")
return fromHtml(ret)
}
return if (isCarbsRequired) {
fromHtml(carbsRequiredText)
} else fromHtml(resourceHelper.gs(R.string.nochangerequested))
}
open fun newAndClone(injector: HasAndroidInjector): APSResult {
val newResult = APSResult(injector)
doClone(newResult)
return newResult
}
protected fun doClone(newResult: APSResult) {
newResult.date = date
newResult.reason = if (reason != null) reason else null
newResult.rate = rate
newResult.duration = duration
newResult.tempBasalRequested = tempBasalRequested
newResult.bolusRequested = bolusRequested
newResult.iob = iob
newResult.json = JSONObject(json.toString())
newResult.hasPredictions = hasPredictions
newResult.smb = smb
newResult.deliverAt = deliverAt
newResult.rateConstraint = rateConstraint
newResult.smbConstraint = smbConstraint
newResult.percent = percent
newResult.usePercent = usePercent
newResult.carbsReq = carbsReq
newResult.carbsReqWithin = carbsReqWithin
newResult.targetBG = targetBG
}
open fun json(): JSONObject? {
val json = JSONObject()
if (isChangeRequested) {
json.put("rate", rate)
json.put("duration", duration)
json.put("reason", reason)
}
return json
}
val predictions: MutableList<GlucoseValueDataPoint>
get() {
val array: MutableList<GlucoseValueDataPoint> = ArrayList()
val startTime = date
json?.let { json ->
if (json.has("predBGs")) {
val predBGs = json.getJSONObject("predBGs")
if (predBGs.has("IOB")) {
val iob = predBGs.getJSONArray("IOB")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.IOB_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(GlucoseValueDataPoint(injector, gv))
}
}
if (predBGs.has("aCOB")) {
val iob = predBGs.getJSONArray("aCOB")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.aCOB_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(GlucoseValueDataPoint(injector, gv))
}
}
if (predBGs.has("COB")) {
val iob = predBGs.getJSONArray("COB")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.COB_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(GlucoseValueDataPoint(injector, gv))
}
}
if (predBGs.has("UAM")) {
val iob = predBGs.getJSONArray("UAM")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.UAM_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(GlucoseValueDataPoint(injector, gv))
}
}
if (predBGs.has("ZT")) {
val iob = predBGs.getJSONArray("ZT")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.ZT_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(GlucoseValueDataPoint(injector, gv))
}
}
}
}
return array
}
val latestPredictionsTime: Long
get() {
var latest: Long = 0
try {
val startTime = date
if (json != null && json!!.has("predBGs")) {
val predBGs = json!!.getJSONObject("predBGs")
if (predBGs.has("IOB")) {
val iob = predBGs.getJSONArray("IOB")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("aCOB")) {
val iob = predBGs.getJSONArray("aCOB")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("COB")) {
val iob = predBGs.getJSONArray("COB")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("UAM")) {
val iob = predBGs.getJSONArray("UAM")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("ZT")) {
val iob = predBGs.getJSONArray("ZT")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
}
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return latest
}
val isCarbsRequired: Boolean
get() = carbsReq > 0
val isChangeRequested: Boolean
get() {
val closedLoopEnabled = constraintChecker.isClosedLoopAllowed()
// closed loop mode: handle change at driver level
if (closedLoopEnabled.value()) {
aapsLogger.debug(LTag.APS, "DEFAULT: Closed mode")
return tempBasalRequested || bolusRequested
}
// open loop mode: try to limit request
if (!tempBasalRequested && !bolusRequested) {
aapsLogger.debug(LTag.APS, "FALSE: No request")
return false
}
val now = System.currentTimeMillis()
val activeTemp = treatmentsPlugin.getTempBasalFromHistory(now)
val pump = activePlugin.activePump
val profile = profileFunction.getProfile()
if (profile == null) {
aapsLogger.error("FALSE: No Profile")
return false
}
return if (usePercent) {
if (activeTemp == null && percent == 100) {
aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp")
return false
}
if (activeTemp != null && abs(percent - activeTemp.tempBasalConvertedToPercent(now, profile)) < pump.pumpDescription.basalStep) {
aapsLogger.debug(LTag.APS, "FALSE: Temp equal")
return false
}
// always report zerotemp
if (percent == 0) {
aapsLogger.debug(LTag.APS, "TRUE: Zero temp")
return true
}
// always report hightemp
if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT) {
val pumpLimit = pump.pumpDescription.pumpType.tbrSettings.maxDose
if (percent.toDouble() == pumpLimit) {
aapsLogger.debug(LTag.APS, "TRUE: Pump limit")
return true
}
}
// report change bigger than 30%
var percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30.0)
percentMinChangeChange /= 100.0
val lowThreshold = 1 - percentMinChangeChange
val highThreshold = 1 + percentMinChangeChange
var change = percent / 100.0
if (activeTemp != null) change = percent / activeTemp.tempBasalConvertedToPercent(now, profile).toDouble()
if (change < lowThreshold || change > highThreshold) {
aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + change * 100.0 + "%")
true
} else {
aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + change * 100.0 + "%")
false
}
} else {
if (activeTemp == null && rate == pump.baseBasalRate) {
aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp")
return false
}
if (activeTemp != null && abs(rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.pumpDescription.basalStep) {
aapsLogger.debug(LTag.APS, "FALSE: Temp equal")
return false
}
// always report zerotemp
if (rate == 0.0) {
aapsLogger.debug(LTag.APS, "TRUE: Zero temp")
return true
}
// always report hightemp
if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) {
val pumpLimit = pump.pumpDescription.pumpType.tbrSettings.maxDose
if (rate == pumpLimit) {
aapsLogger.debug(LTag.APS, "TRUE: Pump limit")
return true
}
}
// report change bigger than 30%
var percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30.0)
percentMinChangeChange /= 100.0
val lowThreshold = 1 - percentMinChangeChange
val highThreshold = 1 + percentMinChangeChange
var change = rate / profile.basal
if (activeTemp != null) change = rate / activeTemp.tempBasalConvertedToAbsolute(now, profile)
if (change < lowThreshold || change > highThreshold) {
aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + change * 100.0 + "%")
true
} else {
aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + change * 100.0 + "%")
false
}
}
}
}

View file

@ -1,22 +1,15 @@
package info.nightscout.androidaps.plugins.general.nsclient;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -26,7 +19,7 @@ import info.nightscout.androidaps.core.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.database.entities.GlucoseValue;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.db.ExtendedBolus;
@ -211,7 +204,7 @@ public class NSUpload {
apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.getLastAPSRun()));
deviceStatus.suggested = apsResult.json();
deviceStatus.iob = lastRun.getRequest().iob.json();
deviceStatus.iob = lastRun.getRequest().getIob().json();
deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.getLastAPSRun()));
JSONObject requested = new JSONObject();
@ -221,8 +214,8 @@ public class NSUpload {
deviceStatus.enacted.put("rate", lastRun.getTbrSetByPump().json(profile).get("rate"));
deviceStatus.enacted.put("duration", lastRun.getTbrSetByPump().json(profile).get("duration"));
deviceStatus.enacted.put("recieved", true);
requested.put("duration", lastRun.getRequest().duration);
requested.put("rate", lastRun.getRequest().rate);
requested.put("duration", lastRun.getRequest().getDuration());
requested.put("rate", lastRun.getRequest().getRate());
requested.put("temp", "absolute");
deviceStatus.enacted.put("requested", requested);
}
@ -231,7 +224,7 @@ public class NSUpload {
deviceStatus.enacted = lastRun.getRequest().json();
}
deviceStatus.enacted.put("smb", lastRun.getTbrSetByPump().bolusDelivered);
requested.put("smb", lastRun.getRequest().smb);
requested.put("smb", lastRun.getRequest().getSmb());
deviceStatus.enacted.put("requested", requested);
}
} else {
@ -402,14 +395,14 @@ public class NSUpload {
uploadQueue.add(new DbRequest("dbAdd", "treatments", data));
}
public void uploadBg(BgReading reading, String source) {
public void uploadBg(GlucoseValue reading, String source) {
JSONObject data = new JSONObject();
try {
data.put("device", source);
data.put("date", reading.getDate());
data.put("dateString", DateUtil.toISOString(reading.getDate()));
data.put("date", reading.getTimestamp());
data.put("dateString", DateUtil.toISOString(reading.getTimestamp()));
data.put("sgv", reading.getValue());
data.put("direction", reading.getData().getTrendArrow().getText());
data.put("direction", reading.getTrendArrow().getText());
data.put("type", "sgv");
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
@ -417,18 +410,18 @@ public class NSUpload {
uploadQueue.add(new DbRequest("dbAdd", "entries", data));
}
public void updateBg(BgReading reading, String source) {
public void updateBg(GlucoseValue reading, String source) {
JSONObject data = new JSONObject();
try {
data.put("device", source);
data.put("date", reading.getDate());
data.put("dateString", DateUtil.toISOString(reading.getDate()));
data.put("date", reading.getTimestamp());
data.put("dateString", DateUtil.toISOString(reading.getTimestamp()));
data.put("sgv", reading.getValue());
data.put("direction", reading.getData().getTrendArrow().getText());
data.put("direction", reading.getTrendArrow().getText());
data.put("type", "sgv");
if (reading.getData().getInterfaceIDs_backing() != null)
if (reading.getData().getInterfaceIDs_backing().getNightscoutId() != null) {
uploadQueue.add(new DbRequest("dbUpdate", "entries", reading.getData().getInterfaceIDs_backing().getNightscoutId(), data));
if (reading.getInterfaceIDs() != null)
if (reading.getInterfaceIDs().getNightscoutId() != null) {
uploadQueue.add(new DbRequest("dbUpdate", "entries", reading.getInterfaceIDs().getNightscoutId(), data));
}
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);

View file

@ -41,7 +41,7 @@ data class GlucoseValue(
noise == other.noise &&
sourceSensor == other.sourceSensor &&
isValid == other.isValid &&
interfaceIDs?.nightscoutId == other.interfaceIDs?.nightscoutId
interfaceIDs.nightscoutId == other.interfaceIDs.nightscoutId
fun isRecordDeleted(other: GlucoseValue): Boolean =
isValid && !other.isValid
@ -91,7 +91,13 @@ data class GlucoseValue(
@SerializedName("MM600Series") MM_600_SERIES("MM600Series"),
@SerializedName("Eversense") EVERSENSE("Eversense"),
@SerializedName("Random") RANDOM("Random"),
@SerializedName("Unknown") UNKNOWN("Unknown")
@SerializedName("Unknown") UNKNOWN("Unknown"),
@SerializedName("IOBPrediction") IOB_PREDICTION("IOBPrediction"),
@SerializedName("aCOBPrediction") aCOB_PREDICTION("aCOBPrediction"),
@SerializedName("COBPrediction") COB_PREDICTION("COBPrediction"),
@SerializedName("UAMPrediction") UAM_PREDICTION("UAMPrediction"),
@SerializedName("ZTPrediction") ZT_PREDICTION("ZTPrediction")
;
companion object {