ExtendedBolus, TemporaryBasal -> room, DanaRS working

This commit is contained in:
Milos Kozak 2021-04-05 22:41:28 +02:00
parent e26e023ebf
commit 2463f8fc47
229 changed files with 9493 additions and 2753 deletions

View file

@ -23,7 +23,6 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.receivers.BTReceiver import info.nightscout.androidaps.receivers.BTReceiver
import info.nightscout.androidaps.receivers.ChargingStateReceiver import info.nightscout.androidaps.receivers.ChargingStateReceiver
import info.nightscout.androidaps.receivers.KeepAliveReceiver.KeepAliveManager import info.nightscout.androidaps.receivers.KeepAliveReceiver.KeepAliveManager
@ -47,7 +46,6 @@ class MainApp : DaggerApplication() {
@Inject lateinit var activityMonitor: ActivityMonitor @Inject lateinit var activityMonitor: ActivityMonitor
@Inject lateinit var versionCheckersUtils: VersionCheckerUtils @Inject lateinit var versionCheckersUtils: VersionCheckerUtils
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var keepAliveManager: KeepAliveManager @Inject lateinit var keepAliveManager: KeepAliveManager

View file

@ -24,7 +24,7 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TddCalculator
import java.text.DecimalFormat import java.text.DecimalFormat
import javax.inject.Inject import javax.inject.Inject

View file

@ -80,12 +80,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static Long earliestDataChange = null; public static Long earliestDataChange = null;
private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemBasalsPost = null;
private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledExtendedBolusPost = null;
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null; private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
@ -198,8 +192,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
aapsLogger.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
virtualPumpPlugin.setFakingStatus(true); virtualPumpPlugin.setFakingStatus(true);
scheduleTemporaryBasalChange();
scheduleExtendedBolusChange();
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
new java.util.Timer().schedule( new java.util.Timer().schedule(
new java.util.TimerTask() { new java.util.TimerTask() {
@ -212,29 +204,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
); );
} }
public void resetTemporaryBasals() {
try {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
virtualPumpPlugin.setFakingStatus(false);
scheduleTemporaryBasalChange();
}
public void resetExtededBoluses() {
try {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public void resetProfileSwitch() { public void resetProfileSwitch() {
try { try {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
@ -507,7 +476,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
openHumansUploader.enqueueTemporaryBasal(old); openHumansUploader.enqueueTemporaryBasal(old);
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
return false; return false;
} }
@ -516,7 +485,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
openHumansUploader.enqueueTemporaryBasal(tempBasal); openHumansUploader.enqueueTemporaryBasal(tempBasal);
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
return true; return true;
} }
if (tempBasal.source == Source.NIGHTSCOUT) { if (tempBasal.source == Source.NIGHTSCOUT) {
@ -535,7 +504,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
return true; return true;
} }
return false; return false;
@ -558,7 +527,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
return true; return true;
} }
} }
@ -567,7 +536,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
openHumansUploader.enqueueTemporaryBasal(tempBasal); openHumansUploader.enqueueTemporaryBasal(tempBasal);
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
return true; return true;
} }
if (tempBasal.source == Source.USER) { if (tempBasal.source == Source.USER) {
@ -575,7 +544,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
openHumansUploader.enqueueTemporaryBasal(tempBasal); openHumansUploader.enqueueTemporaryBasal(tempBasal);
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -592,16 +561,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) { } catch (SQLException e) {
aapsLogger.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
scheduleTemporaryBasalChange(); // scheduleTemporaryBasalChange();
}
public List<TemporaryBasal> getAllTemporaryBasals() {
try {
return getDaoTemporaryBasal().queryForAll();
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return Collections.emptyList();
} }
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) { public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
@ -620,44 +580,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<TemporaryBasal>(); return new ArrayList<TemporaryBasal>();
} }
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long from, long to, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", from, to);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return new ArrayList<TemporaryBasal>();
}
private void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
aapsLogger.debug(LTag.DATABASE, "Firing EventTempBasalChange");
rxBus.send(new EventReloadTempBasalData());
rxBus.send(new EventTempBasalChange());
if (earliestDataChange != null)
rxBus.send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemBasalsPost != null)
scheduledTemBasalsPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/* /*
{ {
"_id": "59232e1ddd032d04218dab00", "_id": "59232e1ddd032d04218dab00",
@ -674,93 +596,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
*/ */
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance())
.source(Source.NIGHTSCOUT)
.date(trJson.getLong("mills"))
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
.durationInMinutes(trJson.getInt("duration"))
.insulin(trJson.getDouble("originalExtendedAmount"))
._id(trJson.getString("_id"));
// if faking found in NS, adapt AAPS to use it too
if (!virtualPumpPlugin.getFakingStatus()) {
virtualPumpPlugin.setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance());
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id");
// if faking found in NS, adapt AAPS to use it too
if (!virtualPumpPlugin.getFakingStatus()) {
virtualPumpPlugin.setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else {
TemporaryBasal tempBasal = new TemporaryBasal(StaticInjector.Companion.getInstance())
.date(trJson.getLong("mills"))
.source(Source.NIGHTSCOUT)
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
if (trJson.has("duration")) {
tempBasal.durationInMinutes = trJson.getInt("duration");
}
if (trJson.has("percent")) {
tempBasal.percentRate = trJson.getInt("percent") + 100;
tempBasal.isAbsolute = false;
}
if (trJson.has("absolute")) {
tempBasal.absoluteRate = trJson.getDouble("absolute");
tempBasal.isAbsolute = true;
}
tempBasal._id = trJson.getString("_id");
createOrUpdate(tempBasal);
}
} catch (JSONException e) {
aapsLogger.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) {
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange();
}
}
public TemporaryBasal findTempBasalById(String _id) {
try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);
if (list.size() != 1) {
return null;
} else {
return list.get(0);
}
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return null;
}
public TemporaryBasal findTempBasalByPumpId(Long pumpId) { public TemporaryBasal findTempBasalByPumpId(Long pumpId) {
try { try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null; QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
@ -785,109 +620,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// ------------ ExtendedBolus handling --------------- // ------------ ExtendedBolus handling ---------------
public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try {
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) {
// if pumpId == 0 do not check for existing pumpId
// used with pumps without history
// and insight where record as added first without pumpId
// and then is record updated with pumpId
if (extendedBolus.pumpId == 0) {
getDaoExtendedBolus().createOrUpdate(extendedBolus);
openHumansUploader.enqueueExtendedBolus(extendedBolus);
} else {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 1) {
aapsLogger.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId);
return false;
}
getDaoExtendedBolus().createOrUpdate(extendedBolus);
openHumansUploader.enqueueExtendedBolus(extendedBolus);
}
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.NIGHTSCOUT) {
old = getDaoExtendedBolus().queryForId(extendedBolus.date);
if (old != null) {
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log());
openHumansUploader.enqueueExtendedBolus(old);
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
return false;
}
// find by NS _id
if (extendedBolus._id != null) {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", extendedBolus._id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log());
openHumansUploader.enqueueExtendedBolus(old);
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
}
}
getDaoExtendedBolus().create(extendedBolus);
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
openHumansUploader.enqueueExtendedBolus(extendedBolus);
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus);
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
openHumansUploader.enqueueExtendedBolus(extendedBolus);
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return false;
}
public List<ExtendedBolus> getAllExtendedBoluses() {
try {
return getDaoExtendedBolus().queryForAll();
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return Collections.emptyList();
}
public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
try { try {
return getDaoExtendedBolus().queryBuilder() return getDaoExtendedBolus().queryBuilder()
@ -907,69 +639,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) { } catch (SQLException e) {
aapsLogger.error("Unhandled exception", e); aapsLogger.error("Unhandled exception", e);
} }
scheduleExtendedBolusChange(); // scheduleExtendedBolusChange();
}
public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) {
try {
List<ExtendedBolus> extendedBoluses;
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses;
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return new ArrayList<ExtendedBolus>();
}
public List<ExtendedBolus> getExtendedBolusDataFromTime(long from, long to, boolean ascending) {
try {
List<ExtendedBolus> extendedBoluses;
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", from, to);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses;
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return new ArrayList<ExtendedBolus>();
}
public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) {
aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange();
}
}
public ExtendedBolus findExtendedBolusById(String _id) {
try {
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
return null;
} }
/* /*
@ -989,33 +659,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
*/ */
public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(StaticInjector.Companion.getInstance(), json);
if (extendedBolus != null)
createOrUpdate(extendedBolus);
}
private void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
aapsLogger.debug(LTag.DATABASE, "Firing EventExtendedBolusChange");
rxBus.send(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
rxBus.send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledExtendedBolusPost != null)
scheduledExtendedBolusPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
}
// ---------------- ProfileSwitch handling --------------- // ---------------- ProfileSwitch handling ---------------
public List<ProfileSwitch> getProfileSwitchData(long from, boolean ascending) { public List<ProfileSwitch> getProfileSwitchData(long from, boolean ascending) {

View file

@ -16,6 +16,7 @@ import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
@Deprecated
@Singleton @Singleton
public class DatabaseHelperProvider implements DatabaseHelperInterface { public class DatabaseHelperProvider implements DatabaseHelperInterface {
@ -82,6 +83,7 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id); return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id);
} }
@Deprecated
@NonNull @Override public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) { @NonNull @Override public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending);
} }
@ -134,42 +136,14 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
return MainApp.Companion.getDbHelper().getPumpStoppedEvent(pumpSerial, before); return MainApp.Companion.getDbHelper().getPumpStoppedEvent(pumpSerial, before);
} }
@Override public boolean createOrUpdate(@NonNull ExtendedBolus extendedBolus) {
return MainApp.Companion.getDbHelper().createOrUpdate(extendedBolus);
}
@Override public void createOrUpdate(@NonNull ProfileSwitch profileSwitch) { @Override public void createOrUpdate(@NonNull ProfileSwitch profileSwitch) {
MainApp.Companion.getDbHelper().createOrUpdate(profileSwitch); MainApp.Companion.getDbHelper().createOrUpdate(profileSwitch);
} }
@Override public void delete(@NonNull TemporaryBasal tempBasal) {
MainApp.Companion.getDbHelper().delete(tempBasal);
}
@NonNull @Override public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) {
return MainApp.Companion.getDbHelper().getExtendedBolusDataFromTime(mills, ascending);
}
@Override public void deleteTempBasalById(@NonNull String _id) {
MainApp.Companion.getDbHelper().deleteTempBasalById(_id);
}
@Override public void deleteExtendedBolusById(@NonNull String _id) {
MainApp.Companion.getDbHelper().deleteExtendedBolusById(_id);
}
@Override public void deleteProfileSwitchById(@NonNull String _id) { @Override public void deleteProfileSwitchById(@NonNull String _id) {
MainApp.Companion.getDbHelper().deleteProfileSwitchById(_id); MainApp.Companion.getDbHelper().deleteProfileSwitchById(_id);
} }
@Override public void createTempBasalFromJsonIfNotExists(@NonNull JSONObject json) {
MainApp.Companion.getDbHelper().createTempBasalFromJsonIfNotExists(json);
}
@Override public void createExtendedBolusFromJsonIfNotExists(@NonNull JSONObject json) {
MainApp.Companion.getDbHelper().createExtendedBolusFromJsonIfNotExists(json);
}
@Override public void createProfileSwitchFromJsonIfNotExists(@NonNull JSONObject trJson) { @Override public void createProfileSwitchFromJsonIfNotExists(@NonNull JSONObject trJson) {
MainApp.Companion.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson); MainApp.Companion.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson);
} }
@ -194,10 +168,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(mills, ascending); return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(mills, ascending);
} }
@NonNull @Override public List<ExtendedBolus> getAllExtendedBoluses() {
return MainApp.Companion.getDbHelper().getAllExtendedBoluses();
}
@NonNull @Override public List<ProfileSwitch> getAllProfileSwitches() { @NonNull @Override public List<ProfileSwitch> getAllProfileSwitches() {
return MainApp.Companion.getDbHelper().getAllProfileSwitches(); return MainApp.Companion.getDbHelper().getAllProfileSwitches();
} }
@ -206,10 +176,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
return MainApp.Companion.getDbHelper().getAllTDDs(); return MainApp.Companion.getDbHelper().getAllTDDs();
} }
@NonNull @Override public List<TemporaryBasal> getAllTemporaryBasals() {
return MainApp.Companion.getDbHelper().getAllTemporaryBasals();
}
@NonNull @Override public List<OHQueueItem> getAllOHQueueItems(long maxEntries) { @NonNull @Override public List<OHQueueItem> getAllOHQueueItems(long maxEntries) {
return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries); return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries);
} }

View file

@ -31,7 +31,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign

View file

@ -28,7 +28,7 @@ import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.Translator
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.fromConstant import info.nightscout.androidaps.extensions.fromConstant
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.text.DecimalFormat import java.text.DecimalFormat
import java.util.* import java.util.*

View file

@ -27,7 +27,7 @@ import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign

View file

@ -28,13 +28,12 @@ import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.extensions.toSignedString import info.nightscout.androidaps.utils.extensions.toSignedString
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
@ -57,7 +56,6 @@ class InsulinDialog : DialogFragmentWithDate() {
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var nsUpload: NSUpload
companion object { companion object {

View file

@ -27,7 +27,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject

View file

@ -17,7 +17,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.text.DecimalFormat import java.text.DecimalFormat
import java.util.* import java.util.*

View file

@ -23,14 +23,13 @@ import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
@ -48,7 +47,6 @@ class TreatmentDialog : DialogFragmentWithDate() {
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()

View file

@ -27,7 +27,6 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -37,8 +36,8 @@ import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.extensions.valueToUnits import info.nightscout.androidaps.extensions.valueToUnits
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -64,7 +63,6 @@ class WizardDialog : DaggerDialogFragment() {
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var treatmentsPlugin: TreatmentsInterface
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
private var wizard: BolusWizard? = null private var wizard: BolusWizard? = null
@ -274,7 +272,7 @@ class WizardDialog : DaggerDialogFragment() {
// IOB calculation // IOB calculation
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -bolusIob.iob) binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -bolusIob.iob)
binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -basalIob.basaliob) binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -basalIob.basaliob)

View file

@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable

View file

@ -28,7 +28,6 @@ class IobCobCalculatorPluginHistory @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
profileFunction: ProfileFunction, profileFunction: ProfileFunction,
activePlugin: ActivePluginProvider, activePlugin: ActivePluginProvider,
treatmentsPluginHistory: TreatmentsPluginHistory,
sensitivityOref1Plugin: SensitivityOref1Plugin, sensitivityOref1Plugin: SensitivityOref1Plugin,
sensitivityAAPSPlugin: SensitivityAAPSPlugin, sensitivityAAPSPlugin: SensitivityAAPSPlugin,
sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin, sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin,
@ -36,7 +35,7 @@ class IobCobCalculatorPluginHistory @Inject constructor(
dateUtil: DateUtil, dateUtil: DateUtil,
repository: AppRepository repository: AppRepository
) : IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, ) : IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction,
activePlugin, treatmentsPluginHistory, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) { activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) {
override fun onStart() { // do not attach to rxbus override fun onStart() { // do not attach to rxbus
} }

View file

@ -6,7 +6,6 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
@ -34,10 +33,9 @@ class TreatmentsPluginHistory @Inject constructor(
nsUpload: NSUpload, nsUpload: NSUpload,
fabricPrivacy: FabricPrivacy, fabricPrivacy: FabricPrivacy,
dateUtil: DateUtil, dateUtil: DateUtil,
uploadQueue: UploadQueueInterface,
databaseHelper: DatabaseHelperInterface, databaseHelper: DatabaseHelperInterface,
repository: AppRepository repository: AppRepository
) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) { ) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, databaseHelper, repository) {
init { init {
onStart() onStart()

View file

@ -38,9 +38,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction
import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.queue.commands.Command
import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.receivers.ReceiverStatusStore
@ -48,7 +46,10 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.extensions.buildDeviceStatus import info.nightscout.androidaps.extensions.buildDeviceStatus
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.convertedToPercent
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -72,9 +73,8 @@ open class LoopPlugin @Inject constructor(
private val context: Context, private val context: Context,
private val commandQueue: CommandQueueProvider, private val commandQueue: CommandQueueProvider,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val treatmentsPlugin: TreatmentsPlugin,
private val virtualPumpPlugin: VirtualPumpPlugin, private val virtualPumpPlugin: VirtualPumpPlugin,
private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val iobCobCalculator: IobCobCalculator,
private val receiverStatusStore: ReceiverStatusStore, private val receiverStatusStore: ReceiverStatusStore,
private val fabricPrivacy: FabricPrivacy, private val fabricPrivacy: FabricPrivacy,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -119,7 +119,7 @@ open class LoopPlugin @Inject constructor(
.subscribe({ event: EventAutosensCalculationFinished -> .subscribe({ event: EventAutosensCalculationFinished ->
// Autosens calculation not triggered by a new BG // Autosens calculation not triggered by a new BG
if (event.cause !is EventNewBG) return@subscribe if (event.cause !is EventNewBG) return@subscribe
val glucoseValue = iobCobCalculatorPlugin.actualBg() ?: return@subscribe val glucoseValue = iobCobCalculator.actualBg() ?: return@subscribe
// BG outdated // BG outdated
// already looped with that value // already looped with that value
if (glucoseValue.timestamp <= lastBgTriggeredRun) return@subscribe if (glucoseValue.timestamp <= lastBgTriggeredRun) return@subscribe
@ -316,7 +316,7 @@ open class LoopPlugin @Inject constructor(
lastRun.lastTBRRequest = 0 lastRun.lastTBRRequest = 0
lastRun.lastSMBEnact = 0 lastRun.lastSMBEnact = 0
lastRun.lastSMBRequest = 0 lastRun.lastSMBRequest = 0
buildDeviceStatus(dateUtil, this, iobCobCalculatorPlugin, profileFunction, buildDeviceStatus(dateUtil, this, iobCobCalculator, profileFunction,
activePlugin.activePump, receiverStatusStore, runningConfiguration, activePlugin.activePump, receiverStatusStore, runningConfiguration,
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also { BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {
repository.insert(it) repository.insert(it)
@ -504,7 +504,7 @@ open class LoopPlugin @Inject constructor(
lastRun.lastTBRRequest = lastRun.lastAPSRun lastRun.lastTBRRequest = lastRun.lastAPSRun
lastRun.lastTBREnact = DateUtil.now() lastRun.lastTBREnact = DateUtil.now()
lastRun.lastOpenModeAccept = DateUtil.now() lastRun.lastOpenModeAccept = DateUtil.now()
buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculatorPlugin, profileFunction, buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculator, profileFunction,
activePlugin.activePump, receiverStatusStore, runningConfiguration, activePlugin.activePump, receiverStatusStore, runningConfiguration,
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also { BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {
repository.insert(it) repository.insert(it)
@ -541,7 +541,7 @@ open class LoopPlugin @Inject constructor(
} }
aapsLogger.debug(LTag.APS, "applyAPSRequest: $request") aapsLogger.debug(LTag.APS, "applyAPSRequest: $request")
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val activeTemp = treatmentsPlugin.getTempBasalFromHistory(now) val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
if (request.usePercent && allowPercentage()) { if (request.usePercent && allowPercentage()) {
if (request.percent == 100 && request.duration == 0) { if (request.percent == 100 && request.duration == 0) {
if (activeTemp != null) { if (activeTemp != null) {
@ -552,7 +552,7 @@ open class LoopPlugin @Inject constructor(
callback?.result(PumpEnactResult(injector).percent(request.percent).duration(0) callback?.result(PumpEnactResult(injector).percent(request.percent).duration(0)
.enacted(false).success(true).comment(R.string.basal_set_correctly))?.run() .enacted(false).success(true).comment(R.string.basal_set_correctly))?.run()
} }
} else if (activeTemp != null && activeTemp.plannedRemainingMinutes > 5 && request.duration - activeTemp.plannedRemainingMinutes < 30 && request.percent == activeTemp.percentRate) { } else if (activeTemp != null && activeTemp.plannedRemainingMinutes > 5 && request.duration - activeTemp.plannedRemainingMinutes < 30 && request.percent == activeTemp.convertedToPercent(now, profile)) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: Temp basal set correctly") aapsLogger.debug(LTag.APS, "applyAPSRequest: Temp basal set correctly")
callback?.result(PumpEnactResult(injector).percent(request.percent) callback?.result(PumpEnactResult(injector).percent(request.percent)
.enacted(false).success(true).duration(activeTemp.plannedRemainingMinutes) .enacted(false).success(true).duration(activeTemp.plannedRemainingMinutes)
@ -571,9 +571,9 @@ open class LoopPlugin @Inject constructor(
callback?.result(PumpEnactResult(injector).absolute(request.rate).duration(0) callback?.result(PumpEnactResult(injector).absolute(request.rate).duration(0)
.enacted(false).success(true).comment(R.string.basal_set_correctly))?.run() .enacted(false).success(true).comment(R.string.basal_set_correctly))?.run()
} }
} else if (activeTemp != null && activeTemp.plannedRemainingMinutes > 5 && request.duration - activeTemp.plannedRemainingMinutes < 30 && abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.pumpDescription.basalStep) { } else if (activeTemp != null && activeTemp.plannedRemainingMinutes > 5 && request.duration - activeTemp.plannedRemainingMinutes < 30 && abs(request.rate - activeTemp.convertedToAbsolute(now, profile)) < pump.pumpDescription.basalStep) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: Temp basal set correctly") aapsLogger.debug(LTag.APS, "applyAPSRequest: Temp basal set correctly")
callback?.result(PumpEnactResult(injector).absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile)) callback?.result(PumpEnactResult(injector).absolute(activeTemp.convertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.plannedRemainingMinutes) .enacted(false).success(true).duration(activeTemp.plannedRemainingMinutes)
.comment(R.string.let_temp_basal_run))?.run() .comment(R.string.let_temp_basal_run))?.run()
} else { } else {
@ -643,7 +643,7 @@ open class LoopPlugin @Inject constructor(
} }
}) })
} }
if (pump.pumpDescription.isExtendedBolusCapable && treatmentsPlugin.isInHistoryExtendedBolusInProgress) { if (pump.pumpDescription.isExtendedBolusCapable && iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) {
commandQueue.cancelExtended(object : Callback() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {

View file

@ -6,6 +6,7 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.MealData import info.nightscout.androidaps.data.MealData
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
@ -16,7 +17,9 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.getPassedDurationToTimeInMinutes
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONException import org.json.JSONException
@ -37,7 +40,7 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var openHumansUploader: OpenHumansUploader
private val mScriptReader: ScriptReader private val mScriptReader: ScriptReader
@ -183,17 +186,14 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader
this.profile.put("out_units", "mmol/L") this.profile.put("out_units", "mmol/L")
} }
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val tb = treatmentsPlugin.getTempBasalFromHistory(now) val tb = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
currentTemp = JSONObject() currentTemp = JSONObject()
currentTemp.put("temp", "absolute") currentTemp.put("temp", "absolute")
currentTemp.put("duration", tb?.plannedRemainingMinutes ?: 0) currentTemp.put("duration", tb?.plannedRemainingMinutes ?: 0)
currentTemp.put("rate", tb?.tempBasalConvertedToAbsolute(now, profile) ?: 0.0) currentTemp.put("rate", tb?.convertedToAbsolute(now, profile) ?: 0.0)
// as we have non default temps longer than 30 minutes // as we have non default temps longer than 30 minutes
val tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now))
if (tempBasal != null) {
currentTemp.put("minutesrunning", tempBasal.realDuration)
}
iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray) iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray)
this.glucoseStatus = JSONObject() this.glucoseStatus = JSONObject()
this.glucoseStatus.put("glucose", glucoseStatus.glucose) this.glucoseStatus.put("glucose", glucoseStatus.glucose)

View file

@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.Profiler
import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.extensions.target import info.nightscout.androidaps.extensions.target
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONException import org.json.JSONException
import javax.inject.Inject import javax.inject.Inject
@ -37,7 +37,6 @@ open class OpenAPSAMAPlugin @Inject constructor(
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val treatmentsPlugin: TreatmentsInterface,
private val iobCobCalculator: IobCobCalculator, private val iobCobCalculator: IobCobCalculator,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val profiler: Profiler, private val profiler: Profiler,
@ -161,7 +160,7 @@ open class OpenAPSAMAPlugin @Inject constructor(
lastAPSResult = null lastAPSResult = null
lastAPSRun = 0 lastAPSRun = 0
} else { } else {
if (determineBasalResultAMA.rate == 0.0 && determineBasalResultAMA.duration == 0 && !treatmentsPlugin.isTempBasalInProgress) determineBasalResultAMA.tempBasalRequested = false if (determineBasalResultAMA.rate == 0.0 && determineBasalResultAMA.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) == null) determineBasalResultAMA.tempBasalRequested = false
determineBasalResultAMA.iob = iobArray[0] determineBasalResultAMA.iob = iobArray[0]
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
determineBasalResultAMA.json?.put("timestamp", DateUtil.toISOString(now)) determineBasalResultAMA.json?.put("timestamp", DateUtil.toISOString(now))

View file

@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.MealData import info.nightscout.androidaps.data.MealData
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
@ -16,8 +17,10 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.getPassedDurationToTimeInMinutes
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONArray import org.json.JSONArray
@ -37,7 +40,7 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader:
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var activePluginProvider: ActivePluginProvider @Inject lateinit var activePluginProvider: ActivePluginProvider
@Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var openHumansUploader: OpenHumansUploader
@ -227,16 +230,13 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader:
this.profile.put("out_units", "mmol/L") this.profile.put("out_units", "mmol/L")
} }
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val tb = treatmentsPlugin.getTempBasalFromHistory(now) val tb = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
currentTemp.put("temp", "absolute") currentTemp.put("temp", "absolute")
currentTemp.put("duration", tb?.plannedRemainingMinutes ?: 0) currentTemp.put("duration", tb?.plannedRemainingMinutes ?: 0)
currentTemp.put("rate", tb?.tempBasalConvertedToAbsolute(now, profile) ?: 0.0) currentTemp.put("rate", tb?.convertedToAbsolute(now, profile) ?: 0.0)
// as we have non default temps longer than 30 mintues // as we have non default temps longer than 30 mintues
val tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now))
if (tempBasal != null) {
currentTemp.put("minutesrunning", tempBasal.realDuration)
}
iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray) iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray)
mGlucoseStatus.put("glucose", glucoseStatus.glucose) mGlucoseStatus.put("glucose", glucoseStatus.glucose)
mGlucoseStatus.put("noise", glucoseStatus.noise) mGlucoseStatus.put("noise", glucoseStatus.noise)

View file

@ -22,7 +22,7 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.Profiler
import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.extensions.target import info.nightscout.androidaps.extensions.target
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
@ -38,7 +38,6 @@ open class OpenAPSSMBPlugin @Inject constructor(
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val treatmentsPlugin: TreatmentsInterface,
private val iobCobCalculator: IobCobCalculator, private val iobCobCalculator: IobCobCalculator,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val profiler: Profiler, private val profiler: Profiler,
@ -188,7 +187,7 @@ open class OpenAPSSMBPlugin @Inject constructor(
} else { } else {
// TODO still needed with oref1? // TODO still needed with oref1?
// Fix bug determine basal // Fix bug determine basal
if (determineBasalResultSMB.rate == 0.0 && determineBasalResultSMB.duration == 0 && !treatmentsPlugin.isTempBasalInProgress) determineBasalResultSMB.tempBasalRequested = false if (determineBasalResultSMB.rate == 0.0 && determineBasalResultSMB.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) == null) determineBasalResultSMB.tempBasalRequested = false
determineBasalResultSMB.iob = iobArray[0] determineBasalResultSMB.iob = iobArray[0]
determineBasalResultSMB.json?.put("timestamp", DateUtil.toISOString(now)) determineBasalResultSMB.json?.put("timestamp", DateUtil.toISOString(now))
determineBasalResultSMB.inputConstraints = inputConstraints determineBasalResultSMB.inputConstraints = inputConstraints

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers

View file

@ -13,6 +13,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.Round
@ -37,8 +38,9 @@ class SafetyPlugin @Inject constructor(
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val hardLimits: HardLimits, private val hardLimits: HardLimits,
private val buildHelper: BuildHelper, private val buildHelper: BuildHelper,
private val treatmentsPlugin: TreatmentsInterface, private val iobCobCalculator: IobCobCalculator,
private val config: Config private val config: Config,
private val dateUtil: DateUtil
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
.neverVisible(true) .neverVisible(true)
@ -68,7 +70,7 @@ class SafetyPlugin @Inject constructor(
value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this
} }
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (!pump.isFakingTempsByExtendedBoluses && treatmentsPlugin.isInHistoryExtendedBolusInProgress) { if (!pump.isFakingTempsByExtendedBoluses && iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) {
value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_with_eb)] = this value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_with_eb)] = this
} }
return value return value

View file

@ -16,12 +16,15 @@ import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.activities.TDDStatsActivity import info.nightscout.androidaps.activities.TDDStatsActivity
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.UserEntry.* import info.nightscout.androidaps.database.entities.UserEntry.*
import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.dialogs.*
import info.nightscout.androidaps.events.* import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
@ -31,10 +34,13 @@ import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler
import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.skins.SkinProvider
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toStringMedium
import info.nightscout.androidaps.extensions.toStringShort
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
@ -52,18 +58,21 @@ class ActionsFragment : DaggerFragment() {
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var statusLightHandler: StatusLightHandler
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var protectionCheck: ProtectionCheck
@Inject lateinit var skinProvider: SkinProvider @Inject lateinit var skinProvider: SkinProvider
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var repository: AppRepository
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -154,7 +163,7 @@ class ActionsFragment : DaggerFragment() {
} }
} }
extendedBolusCancel?.setOnClickListener { extendedBolusCancel?.setOnClickListener {
if (activePlugin.activeTreatments.isInHistoryExtendedBolusInProgress) { if (iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) {
uel.log(Action.CANCEL_EXTENDED_BOLUS) uel.log(Action.CANCEL_EXTENDED_BOLUS)
commandQueue.cancelExtended(object : Callback() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
@ -169,7 +178,7 @@ class ActionsFragment : DaggerFragment() {
TempBasalDialog().show(childFragmentManager, "Actions") TempBasalDialog().show(childFragmentManager, "Actions")
} }
cancelTempBasal?.setOnClickListener { cancelTempBasal?.setOnClickListener {
if (activePlugin.activeTreatments.isTempBasalInProgress) { if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) != null) {
uel.log(Action.CANCEL_TEMP_BASAL) uel.log(Action.CANCEL_TEMP_BASAL)
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
@ -264,12 +273,12 @@ class ActionsFragment : DaggerFragment() {
extendedBolus?.visibility = View.GONE extendedBolus?.visibility = View.GONE
extendedBolusCancel?.visibility = View.GONE extendedBolusCancel?.visibility = View.GONE
} else { } else {
val activeExtendedBolus = activePlugin.activeTreatments.getExtendedBolusFromHistory(System.currentTimeMillis()) val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet()
if (activeExtendedBolus != null) { if (activeExtendedBolus is ValueWrapper.Existing) {
extendedBolus?.visibility = View.GONE extendedBolus?.visibility = View.GONE
extendedBolusCancel?.visibility = View.VISIBLE extendedBolusCancel?.visibility = View.VISIBLE
@Suppress("SetTextI18n") @Suppress("SetTextI18n")
extendedBolusCancel?.text = resourceHelper.gs(R.string.cancel) + " " + activeExtendedBolus.toStringMedium() extendedBolusCancel?.text = resourceHelper.gs(R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil)
} else { } else {
extendedBolus?.visibility = View.VISIBLE extendedBolus?.visibility = View.VISIBLE
extendedBolusCancel?.visibility = View.GONE extendedBolusCancel?.visibility = View.GONE
@ -280,7 +289,7 @@ class ActionsFragment : DaggerFragment() {
setTempBasal?.visibility = View.GONE setTempBasal?.visibility = View.GONE
cancelTempBasal?.visibility = View.GONE cancelTempBasal?.visibility = View.GONE
} else { } else {
val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
if (activeTemp != null) { if (activeTemp != null) {
setTempBasal?.visibility = View.GONE setTempBasal?.visibility = View.GONE
cancelTempBasal?.visibility = View.VISIBLE cancelTempBasal?.visibility = View.VISIBLE

View file

@ -7,7 +7,6 @@ import android.os.Bundle
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.events.* import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -20,8 +19,11 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.services.Intents import info.nightscout.androidaps.services.Intents
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.extensions.durationInMinutes
import info.nightscout.androidaps.extensions.toStringFull
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -35,6 +37,7 @@ class DataBroadcastPlugin @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val context: Context, private val context: Context,
private val dateUtil: DateUtil,
private val fabricPrivacy: FabricPrivacy, private val fabricPrivacy: FabricPrivacy,
private val rxBus: RxBusWrapper, private val rxBus: RxBusWrapper,
private val iobCobCalculator: IobCobCalculator, private val iobCobCalculator: IobCobCalculator,
@ -131,8 +134,8 @@ class DataBroadcastPlugin @Inject constructor(
private fun iobCob(bundle: Bundle) { private fun iobCob(bundle: Bundle) {
profileFunction.getProfile() ?: return profileFunction.getProfile() ?: return
val bolusIob: IobTotal = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob: IobTotal = activePlugin.activeTreatments.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
bundle.putDouble("bolusIob", bolusIob.iob) bundle.putDouble("bolusIob", bolusIob.iob)
bundle.putDouble("basalIob", basalIob.basaliob) bundle.putDouble("basalIob", basalIob.basaliob)
bundle.putDouble("iob", bolusIob.iob + basalIob.basaliob) // total IOB bundle.putDouble("iob", bolusIob.iob + basalIob.basaliob) // total IOB
@ -174,12 +177,12 @@ class DataBroadcastPlugin @Inject constructor(
bundle.putLong("basalTimeStamp", now) bundle.putLong("basalTimeStamp", now)
bundle.putDouble("baseBasal", profile.basal) bundle.putDouble("baseBasal", profile.basal)
bundle.putString("profile", profileFunction.getProfileName()) bundle.putString("profile", profileFunction.getProfileName())
activePlugin.activeTreatments.getTempBasalFromHistory(now)?.let { iobCobCalculator.getTempBasalIncludingConvertedExtended(now)?.let {
bundle.putLong("tempBasalStart", it.date) bundle.putLong("tempBasalStart", it.timestamp)
bundle.putInt("tempBasalDurationInMinutes", it.durationInMinutes) bundle.putLong("tempBasalDurationInMinutes", it.durationInMinutes)
if (it.isAbsolute) bundle.putDouble("tempBasalAbsolute", it.absoluteRate) // U/h for absolute TBR if (it.isAbsolute) bundle.putDouble("tempBasalAbsolute", it.rate) // U/h for absolute TBR
else bundle.putInt("tempBasalPercent", it.percentRate) // % for percent type TBR else bundle.putInt("tempBasalPercent", it.rate.toInt()) // % for percent type TBR
bundle.putString("tempBasalString", it.toStringFull()) // user friendly string bundle.putString("tempBasalString", it.toStringFull(profile, dateUtil)) // user friendly string
} }
} }

View file

@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.Completable import io.reactivex.Completable

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.extensions.foodFromJson import info.nightscout.androidaps.extensions.foodFromJson
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONObject import org.json.JSONObject

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.interfaces.DataSyncSelector
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.extensions.toJson import info.nightscout.androidaps.extensions.toJson
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
@ -30,6 +30,8 @@ class DataSyncSelectorImplementation @Inject constructor(
sp.remove(R.string.key_ns_carbs_last_synced_id) sp.remove(R.string.key_ns_carbs_last_synced_id)
sp.remove(R.string.key_ns_bolus_calculator_result_last_synced_id) sp.remove(R.string.key_ns_bolus_calculator_result_last_synced_id)
sp.remove(R.string.key_ns_device_status_last_synced_id) sp.remove(R.string.key_ns_device_status_last_synced_id)
sp.remove(R.string.key_ns_temporary_basal_last_synced_id)
sp.remove(R.string.key_ns_extended_bolus_last_synced_id)
} }
override fun confirmLastBolusIdIfGreater(lastSynced: Long) { override fun confirmLastBolusIdIfGreater(lastSynced: Long) {
@ -326,4 +328,81 @@ class DataSyncSelectorImplementation @Inject constructor(
return false return false
} }
override fun confirmLastTemporaryBasalIdIfGreater(lastSynced: Long) {
if (lastSynced > sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)) {
aapsLogger.debug(LTag.NSCLIENT, "Setting TemporaryBasal data sync from $lastSynced")
sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, lastSynced)
}
}
// Prepared for v3 (returns all modified after)
override fun changedTemporaryBasals(): List<TemporaryBasal> {
val startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)
return appRepository.getModifiedTemporaryBasalDataFromId(startId).blockingGet().also {
aapsLogger.debug(LTag.NSCLIENT, "Loading TemporaryBasal data for sync from $startId. Records ${it.size}")
}
}
override fun processChangedTemporaryBasalsCompat(): Boolean {
val startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)
appRepository.getNextSyncElementTemporaryBasal(startId).blockingGet()?.let { tb ->
aapsLogger.info(LTag.DATABASE, "Loading TemporaryBasal data Start: $startId ID: ${tb.first.id} HistoryID: ${tb.second} ")
profileFunction.getProfile(tb.first.timestamp)?.let { profile ->
when {
// removed and not uploaded yet = ignore
!tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null -> Any()
// removed and already uploaded = send for removal
!tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null ->
nsClientPlugin.nsClientService?.dbRemove("treatments", tb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryBasal(tb.first, tb.second))
// existing without nsId = create new
tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null ->
nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second))
// existing with nsId = update
tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null ->
nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second))
}
return true
}
}
return false
}
override fun confirmLastExtendedBolusIdIfGreater(lastSynced: Long) {
if (lastSynced > sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)) {
aapsLogger.debug(LTag.NSCLIENT, "Setting ExtendedBolus data sync from $lastSynced")
sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, lastSynced)
}
}
// Prepared for v3 (returns all modified after)
override fun changedExtendedBoluses(): List<ExtendedBolus> {
val startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)
return appRepository.getModifiedExtendedBolusDataFromId(startId).blockingGet().also {
aapsLogger.debug(LTag.NSCLIENT, "Loading ExtendedBolus data for sync from $startId. Records ${it.size}")
}
}
override fun processChangedExtendedBolusesCompat(): Boolean {
val startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)
appRepository.getNextSyncElementExtendedBolus(startId).blockingGet()?.let { eb ->
aapsLogger.info(LTag.DATABASE, "Loading ExtendedBolus data Start: $startId ID: ${eb.first.id} HistoryID: ${eb.second} ")
profileFunction.getProfile(eb.first.timestamp)?.let { profile ->
when {
// removed and not uploaded yet = ignore
!eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> Any()
// removed and already uploaded = send for removal
!eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null ->
nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairExtendedBolus(eb.first, eb.second))
// existing without nsId = create new
eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null ->
nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile), DataSyncSelector.PairExtendedBolus(eb.first, eb.second))
// existing with nsId = update
eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null ->
nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile), DataSyncSelector.PairExtendedBolus(eb.first, eb.second))
}
return true
}
}
return false
}
} }

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.nsclient package info.nightscout.androidaps.plugins.general.nsclient
import android.content.Context import android.content.Context
import androidx.work.Data
import androidx.work.Worker import androidx.work.Worker
import androidx.work.WorkerParameters import androidx.work.WorkerParameters
import androidx.work.workDataOf import androidx.work.workDataOf
@ -11,10 +10,8 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.SyncNsBolusTransaction import info.nightscout.androidaps.database.transactions.*
import info.nightscout.androidaps.database.transactions.SyncNsCarbsTransaction import info.nightscout.androidaps.extensions.*
import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
import info.nightscout.androidaps.interfaces.ConfigInterface import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -28,10 +25,7 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.JsonHelper.safeGetLong import info.nightscout.androidaps.utils.JsonHelper.safeGetLong
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.bolusFromJson import info.nightscout.androidaps.utils.extensions.*
import info.nightscout.androidaps.utils.extensions.carbsFromJson
import info.nightscout.androidaps.utils.extensions.temporaryTargetFromJson
import info.nightscout.androidaps.utils.extensions.therapyEventFromJson
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
@ -92,12 +86,17 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.amount, UserEntry.Units.U) ValueWithUnit(it.amount, UserEntry.Units.U)
) )
aapsLogger.debug(LTag.DATABASE, "Inserted bolus $it")
} }
result.invalidated.forEach { result.invalidated.forEach {
uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.amount, UserEntry.Units.U) ValueWithUnit(it.amount, UserEntry.Units.U)
) )
aapsLogger.debug(LTag.DATABASE, "Invalidated bolus $it")
}
result.updatedNsId.forEach {
aapsLogger.debug(LTag.DATABASE, "Updated bolus $it")
} }
} }
} ?: aapsLogger.error("Error parsing bolus json $json") } ?: aapsLogger.error("Error parsing bolus json $json")
@ -116,12 +115,17 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.amount, UserEntry.Units.G) ValueWithUnit(it.amount, UserEntry.Units.G)
) )
aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it")
} }
result.invalidated.forEach { result.invalidated.forEach {
uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.amount, UserEntry.Units.G) ValueWithUnit(it.amount, UserEntry.Units.G)
) )
aapsLogger.debug(LTag.DATABASE, "Invalidated carbs $it")
}
result.updatedNsId.forEach {
aapsLogger.debug(LTag.DATABASE, "Updated carbs $it")
} }
} }
} ?: aapsLogger.error("Error parsing bolus json $json") } ?: aapsLogger.error("Error parsing bolus json $json")
@ -144,6 +148,7 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget), ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget),
ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true) ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true)
) )
aapsLogger.debug(LTag.DATABASE, "Inserted TemporaryTarget $it")
} }
result.invalidated.forEach { result.invalidated.forEach {
uel.log(UserEntry.Action.TT_DELETED_FROM_NS, uel.log(UserEntry.Action.TT_DELETED_FROM_NS,
@ -152,6 +157,7 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget), ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget),
ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true) ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true)
) )
aapsLogger.debug(LTag.DATABASE, "Invalidated TemporaryTarget $it")
} }
result.ended.forEach { result.ended.forEach {
uel.log(UserEntry.Action.TT_CANCELED_FROM_NS, uel.log(UserEntry.Action.TT_CANCELED_FROM_NS,
@ -160,6 +166,10 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget), ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget),
ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true) ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true)
) )
aapsLogger.debug(LTag.DATABASE, "Updated TemporaryTarget $it")
}
result.updatedNsId.forEach {
aapsLogger.debug(LTag.DATABASE, "Updated TemporaryTarget $it")
} }
} }
} ?: aapsLogger.error("Error parsing TT json $json") } ?: aapsLogger.error("Error parsing TT json $json")
@ -187,6 +197,7 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.type.text, UserEntry.Units.TherapyEvent) ValueWithUnit(it.type.text, UserEntry.Units.TherapyEvent)
) )
aapsLogger.debug(LTag.DATABASE, "Inserted TherapyEvent $it")
} }
result.invalidated.forEach { result.invalidated.forEach {
uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
@ -194,13 +205,83 @@ class NSClientAddUpdateWorker(
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.type.text, UserEntry.Units.TherapyEvent) ValueWithUnit(it.type.text, UserEntry.Units.TherapyEvent)
) )
aapsLogger.debug(LTag.DATABASE, "Invalidated TherapyEvent $it")
}
result.updatedNsId.forEach {
aapsLogger.debug(LTag.DATABASE, "Updated TherapyEvent $it")
} }
} }
} ?: aapsLogger.error("Error parsing TherapyEvent json $json") } ?: aapsLogger.error("Error parsing TherapyEvent json $json")
eventType == TherapyEvent.Type.TEMPORARY_BASAL.text -> eventType == TherapyEvent.Type.TEMPORARY_BASAL.text ->
databaseHelper.createTempBasalFromJsonIfNotExists(json) temporaryBasalFromJson(json)?.let { temporaryBasal ->
repository.runTransactionForResult(SyncNsTemporaryBasalTransaction(temporaryBasal))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary basal", it)
ret = Result.failure(workDataOf("Error" to it))
}
.blockingGet()
.also { result ->
result.inserted.forEach {
uel.log(UserEntry.Action.CAREPORTAL_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H)
)
aapsLogger.debug(LTag.DATABASE, "Inserted TemporaryBasal $it")
}
result.invalidated.forEach {
uel.log(UserEntry.Action.CAREPORTAL_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H)
)
aapsLogger.debug(LTag.DATABASE, "Invalidated TemporaryBasal $it")
}
result.ended.forEach {
uel.log(UserEntry.Action.CAREPORTAL_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H)
)
aapsLogger.debug(LTag.DATABASE, "Updated TemporaryBasal $it")
}
result.updatedNsId.forEach {
aapsLogger.debug(LTag.DATABASE, "Updated TemporaryBasal $it")
}
}
} ?: aapsLogger.error("Error parsing TemporaryBasal json $json")
eventType == TherapyEvent.Type.COMBO_BOLUS.text -> eventType == TherapyEvent.Type.COMBO_BOLUS.text ->
databaseHelper.createExtendedBolusFromJsonIfNotExists(json) extendedBolusFromJson(json)?.let { extendedBolus ->
repository.runTransactionForResult(SyncNsExtendedBolusTransaction(extendedBolus))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving extended bolus", it)
ret = Result.failure(workDataOf("Error" to it))
}
.blockingGet()
.also { result ->
result.inserted.forEach {
uel.log(UserEntry.Action.CAREPORTAL_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H)
)
aapsLogger.debug(LTag.DATABASE, "Inserted ExtendedBolus $it")
}
result.invalidated.forEach {
uel.log(UserEntry.Action.CAREPORTAL_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H)
)
aapsLogger.debug(LTag.DATABASE, "Invalidated ExtendedBolus $it")
}
result.ended.forEach {
uel.log(UserEntry.Action.CAREPORTAL_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H)
)
aapsLogger.debug(LTag.DATABASE, "Updated ExtendedBolus $it")
}
result.updatedNsId.forEach {
aapsLogger.debug(LTag.DATABASE, "Updated ExtendedBolus $it")
}
}
} ?: aapsLogger.error("Error parsing ExtendedBolus json $json")
eventType == TherapyEvent.Type.PROFILE_SWITCH.text -> eventType == TherapyEvent.Type.PROFILE_SWITCH.text ->
databaseHelper.createProfileSwitchFromJsonIfNotExists(json) databaseHelper.createProfileSwitchFromJsonIfNotExists(json)
} }

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.therapyEventFromNsMbg import info.nightscout.androidaps.extensions.therapyEventFromNsMbg
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject

View file

@ -9,10 +9,8 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.SyncNsBolusTransaction import info.nightscout.androidaps.database.transactions.*
import info.nightscout.androidaps.database.transactions.SyncNsCarbsTransaction import info.nightscout.androidaps.extensions.*
import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
import info.nightscout.androidaps.interfaces.ConfigInterface import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -22,10 +20,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.bolusFromNsIdForInvalidating import info.nightscout.androidaps.utils.extensions.*
import info.nightscout.androidaps.utils.extensions.carbsFromNsIdForInvalidating
import info.nightscout.androidaps.utils.extensions.temporaryTargetFromNsIdForInvalidating
import info.nightscout.androidaps.utils.extensions.therapyEventFromNsIdForInvalidating
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
@ -114,7 +109,7 @@ class NSClientRemoveWorker(
} }
} }
// room Bolus // room Carbs
val carbs = carbsFromNsIdForInvalidating(nsId) val carbs = carbsFromNsIdForInvalidating(nsId)
repository.runTransactionForResult(SyncNsCarbsTransaction(carbs)) repository.runTransactionForResult(SyncNsCarbsTransaction(carbs))
.doOnError { .doOnError {
@ -131,9 +126,41 @@ class NSClientRemoveWorker(
} }
} }
// room TemporaryBasal
val temporaryBasal = temporaryBasalFromNsIdForInvalidating(nsId)
repository.runTransactionForResult(SyncNsTemporaryBasalTransaction(temporaryBasal))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while invalidating temporary basal", it)
ret = Result.failure(workDataOf("Error" to it))
}
.blockingGet()
.also { result ->
result.invalidated.forEach {
uel.log(
UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.rate, UserEntry.Units.U_H))
}
}
// room ExtendedBolus
val extendedBolus = extendedBolusFromNsIdForInvalidating(nsId)
repository.runTransactionForResult(SyncNsExtendedBolusTransaction(extendedBolus))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while invalidating extended bolus", it)
ret = Result.failure(workDataOf("Error" to it))
}
.blockingGet()
.also { result ->
result.invalidated.forEach {
uel.log(
UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
ValueWithUnit(it.amount, UserEntry.Units.U))
}
}
// old DB model // old DB model
databaseHelper.deleteTempBasalById(nsId)
databaseHelper.deleteExtendedBolusById(nsId)
databaseHelper.deleteProfileSwitchById(nsId) databaseHelper.deleteProfileSwitchById(nsId)
} }

View file

@ -37,8 +37,10 @@ import info.nightscout.androidaps.database.transactions.UpdateNsIdBolusCalculato
import info.nightscout.androidaps.database.transactions.UpdateNsIdBolusTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdBolusTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdCarbsTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdCarbsTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdDeviceStatusTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdDeviceStatusTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdExtendedBolusTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdFoodTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdFoodTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdGlucoseValueTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdGlucoseValueTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdTemporaryBasalTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdTemporaryTargetTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdTemporaryTargetTransaction;
import info.nightscout.androidaps.database.transactions.UpdateNsIdTherapyEventTransaction; import info.nightscout.androidaps.database.transactions.UpdateNsIdTherapyEventTransaction;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
@ -139,7 +141,7 @@ public class NSClientService extends DaggerService {
private final ArrayList<Long> reconnections = new ArrayList<>(); private final ArrayList<Long> reconnections = new ArrayList<>();
private final int WATCHDOG_INTERVAL_MINUTES = 2; private final int WATCHDOG_INTERVAL_MINUTES = 2;
private final int WATCHDOG_RECONNECT_IN = 15; private final int WATCHDOG_RECONNECT_IN = 15;
private final int WATCHDOG_MAXCONNECTIONS = 5; private final int WATCHDOG_MAX_CONNECTIONS = 5;
public NSClientService() { public NSClientService() {
super(); super();
@ -340,6 +342,38 @@ public class NSClientService extends DaggerService {
dataSyncSelector.processChangedBolusCalculatorResultsCompat(); dataSyncSelector.processChangedBolusCalculatorResultsCompat();
return; return;
} }
if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryBasal) {
DataSyncSelector.PairTemporaryBasal pair = (DataSyncSelector.PairTemporaryBasal) ack.getOriginalObject();
pair.getValue().getInterfaceIDs().setNightscoutId(ack.getId());
disposable.add(repository.runTransactionForResult(new UpdateNsIdTemporaryBasalTransaction(pair.getValue()))
.observeOn(aapsSchedulers.getIo())
.subscribe(
result -> aapsLogger.debug(LTag.DATABASE, "Updated ns id of TemporaryBasal " + pair.getValue()),
error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryBasal failed", error)
));
dataSyncSelector.confirmLastTemporaryBasalIdIfGreater(pair.getUpdateRecordId());
rxBus.send(new EventNSClientNewLog("DBADD", "Acked TemporaryBasal" + pair.getValue().getInterfaceIDs().getNightscoutId()));
// Send new if waiting
dataSyncSelector.processChangedTemporaryBasalsCompat();
return;
}
if (ack.getOriginalObject() instanceof DataSyncSelector.PairExtendedBolus) {
DataSyncSelector.PairExtendedBolus pair = (DataSyncSelector.PairExtendedBolus) ack.getOriginalObject();
pair.getValue().getInterfaceIDs().setNightscoutId(ack.getId());
disposable.add(repository.runTransactionForResult(new UpdateNsIdExtendedBolusTransaction(pair.getValue()))
.observeOn(aapsSchedulers.getIo())
.subscribe(
result -> aapsLogger.debug(LTag.DATABASE, "Updated ns id of ExtendedBolus " + pair.getValue()),
error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of ExtendedBolus failed", error)
));
dataSyncSelector.confirmLastExtendedBolusIdIfGreater(pair.getUpdateRecordId());
rxBus.send(new EventNSClientNewLog("DBADD", "Acked ExtendedBolus" + pair.getValue().getInterfaceIDs().getNightscoutId()));
// Send new if waiting
dataSyncSelector.processChangedTemporaryBasalsCompat();
return;
}
if (ack.getOriginalObject() instanceof DeviceStatus) { if (ack.getOriginalObject() instanceof DeviceStatus) {
DeviceStatus deviceStatus = (DeviceStatus) ack.getOriginalObject(); DeviceStatus deviceStatus = (DeviceStatus) ack.getOriginalObject();
deviceStatus.getInterfaceIDs().setNightscoutId(ack.getId()); deviceStatus.getInterfaceIDs().setNightscoutId(ack.getId());
@ -424,6 +458,22 @@ public class NSClientService extends DaggerService {
dataSyncSelector.processChangedBolusCalculatorResultsCompat(); dataSyncSelector.processChangedBolusCalculatorResultsCompat();
return; return;
} }
if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryBasal) {
DataSyncSelector.PairTemporaryBasal pair = (DataSyncSelector.PairTemporaryBasal) ack.getOriginalObject();
dataSyncSelector.confirmLastTemporaryBasalIdIfGreater(pair.getUpdateRecordId());
rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked TemporaryBasal " + ack.get_id()));
// Send new if waiting
dataSyncSelector.processChangedTemporaryBasalsCompat();
return;
}
if (ack.getOriginalObject() instanceof DataSyncSelector.PairExtendedBolus) {
DataSyncSelector.PairExtendedBolus pair = (DataSyncSelector.PairExtendedBolus) ack.getOriginalObject();
dataSyncSelector.confirmLastExtendedBolusIdIfGreater(pair.getUpdateRecordId());
rxBus.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked ExtendedBolus " + ack.get_id()));
// Send new if waiting
dataSyncSelector.processChangedExtendedBolusesCompat();
return;
}
// old way // old way
if (ack.getResult()) { if (ack.getResult()) {
uploadQueue.removeByMongoId(ack.getAction(), ack.get_id()); uploadQueue.removeByMongoId(ack.getAction(), ack.get_id());
@ -549,8 +599,8 @@ public class NSClientService extends DaggerService {
reconnections.remove(r); reconnections.remove(r);
} }
} }
rxBus.send(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS)); rxBus.send(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAX_CONNECTIONS));
if (reconnections.size() >= WATCHDOG_MAXCONNECTIONS) { if (reconnections.size() >= WATCHDOG_MAX_CONNECTIONS) {
Notification n = new Notification(Notification.NS_MALFUNCTION, resourceHelper.gs(R.string.nsmalfunction), Notification.URGENT); Notification n = new Notification(Notification.NS_MALFUNCTION, resourceHelper.gs(R.string.nsmalfunction), Notification.URGENT);
rxBus.send(new EventNewNotification(n)); rxBus.send(new EventNewNotification(n));
rxBus.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins")); rxBus.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
@ -990,6 +1040,8 @@ public class NSClientService extends DaggerService {
dataSyncSelector.processChangedBolusesCompat(); dataSyncSelector.processChangedBolusesCompat();
dataSyncSelector.processChangedCarbsCompat(); dataSyncSelector.processChangedCarbsCompat();
dataSyncSelector.processChangedBolusCalculatorResultsCompat(); dataSyncSelector.processChangedBolusCalculatorResultsCompat();
dataSyncSelector.processChangedTemporaryBasalsCompat();
dataSyncSelector.processChangedExtendedBolusesCompat();
dataSyncSelector.processChangedGlucoseValuesCompat(); dataSyncSelector.processChangedGlucoseValuesCompat();
dataSyncSelector.processChangedTempTargetsCompat(); dataSyncSelector.processChangedTempTargetsCompat();
dataSyncSelector.processChangedFoodsCompat(); dataSyncSelector.processChangedFoodsCompat();

View file

@ -28,7 +28,7 @@ import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.extensions.toConstant import info.nightscout.androidaps.extensions.toConstant
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -365,18 +365,18 @@ class OpenHumansUploader @Inject constructor(
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetTherapyEventDataFromTime(0, true).blockingGet()) }) .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTherapyEventDataFromTime(0, true).blockingGet()) })
.map { enqueueTherapyEvent(it); increaseCounter() } .map { enqueueTherapyEvent(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) }) // .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) })
.map { enqueueExtendedBolus(it); increaseCounter() } // .map { enqueueExtendedBolus(it); increaseCounter() }
.ignoreElements() // .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllProfileSwitches()) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllProfileSwitches()) })
.map { enqueueProfileSwitch(it); increaseCounter() } .map { enqueueProfileSwitch(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) })
.map { enqueueTotalDailyDose(it); increaseCounter() } .map { enqueueTotalDailyDose(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) }) // .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) })
.map { enqueueTemporaryBasal(it); increaseCounter() } // .map { enqueueTemporaryBasal(it); increaseCounter() }
.ignoreElements() // .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) }) .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) })
.map { enqueueTempTarget(it); increaseCounter() } .map { enqueueTempTarget(it); increaseCounter() }
.ignoreElements() .ignoreElements()

View file

@ -36,6 +36,7 @@ import info.nightscout.androidaps.database.interfaces.end
import info.nightscout.androidaps.databinding.OverviewFragmentBinding import info.nightscout.androidaps.databinding.OverviewFragmentBinding
import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.dialogs.*
import info.nightscout.androidaps.events.* import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.extensions.*
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
@ -61,10 +62,7 @@ import info.nightscout.androidaps.skins.SkinProvider
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.directionToIcon import info.nightscout.androidaps.utils.extensions.*
import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.extensions.valueToUnits
import info.nightscout.androidaps.utils.extensions.valueToUnitsString
import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
@ -100,7 +98,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculator @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var dexcomPlugin: DexcomPlugin
@Inject lateinit var dexcomMediator: DexcomPlugin.DexcomMediator @Inject lateinit var dexcomMediator: DexcomPlugin.DexcomMediator
@Inject lateinit var xdripPlugin: XdripPlugin @Inject lateinit var xdripPlugin: XdripPlugin
@ -412,7 +410,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
private fun onClickQuickWizard() { private fun onClickQuickWizard() {
val actualBg = iobCobCalculatorPlugin.actualBg() val actualBg = iobCobCalculator.actualBg()
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val profileName = profileFunction.getProfileName() val profileName = profileFunction.getProfileName()
val pump = activePlugin.activePump val pump = activePlugin.activePump
@ -447,11 +445,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
private fun processButtonsVisibility() { private fun processButtonsVisibility() {
val lastBG = iobCobCalculatorPlugin.lastBg() val lastBG = iobCobCalculator.lastBg()
val pump = activePlugin.activePump val pump = activePlugin.activePump
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val profileName = profileFunction.getProfileName() val profileName = profileFunction.getProfileName()
val actualBG = iobCobCalculatorPlugin.actualBg() val actualBG = iobCobCalculator.actualBg()
// QuickWizard button // QuickWizard button
val quickWizardEntry = quickWizard.getActive() val quickWizardEntry = quickWizard.getActive()
@ -563,8 +561,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
binding.loopPumpStatusLayout.loopLayout.visibility = View.VISIBLE binding.loopPumpStatusLayout.loopLayout.visibility = View.VISIBLE
val profile = profileFunction.getProfile() ?: return val profile = profileFunction.getProfile() ?: return
val actualBG = iobCobCalculatorPlugin.actualBg() val actualBG = iobCobCalculator.actualBg()
val lastBG = iobCobCalculatorPlugin.lastBg() val lastBG = iobCobCalculator.lastBg()
val pump = activePlugin.activePump val pump = activePlugin.activePump
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
val lowLine = defaultValueHelper.determineLowLine() val lowLine = defaultValueHelper.determineLowLine()
@ -703,13 +701,13 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
// Basal, TBR // Basal, TBR
val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
binding.infoLayout.baseBasal.text = activeTemp?.let { "T:" + activeTemp.toStringVeryShort() } binding.infoLayout.baseBasal.text = activeTemp?.let { "T:" + activeTemp.toStringShort() }
?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal) ?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)
binding.infoLayout.basalLayout.setOnClickListener { binding.infoLayout.basalLayout.setOnClickListener {
var fullText = "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}" var fullText = "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}"
if (activeTemp != null) if (activeTemp != null)
fullText += "\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + activeTemp.toStringFull() fullText += "\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + activeTemp.toStringFull(profile, dateUtil)
activity?.let { activity?.let {
OKDialog.show(it, resourceHelper.gs(R.string.basal), fullText) OKDialog.show(it, resourceHelper.gs(R.string.basal), fullText)
} }
@ -718,23 +716,23 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
?: resourceHelper.gc(R.color.defaulttextcolor)) ?: resourceHelper.gc(R.color.defaulttextcolor))
binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_no_tbr) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_no_tbr)
val percentRate = activeTemp?.tempBasalConvertedToPercent(System.currentTimeMillis(), profile) val percentRate = activeTemp?.convertedToPercent(System.currentTimeMillis(), profile)
?: 100 ?: 100
if (percentRate > 100) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_tbr_high) if (percentRate > 100) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_tbr_high)
if (percentRate < 100) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_tbr_low) if (percentRate < 100) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_tbr_low)
// Extended bolus // Extended bolus
val extendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()) val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet()
binding.infoLayout.extendedBolus.text = binding.infoLayout.extendedBolus.text =
if (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses) if (extendedBolus is ValueWrapper.Existing && !pump.isFakingTempsByExtendedBoluses)
resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.absoluteRate()) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.value.rate)
else "" else ""
binding.infoLayout.extendedBolus.setOnClickListener { binding.infoLayout.extendedBolus.setOnClickListener {
if (extendedBolus != null) activity?.let { if (extendedBolus is ValueWrapper.Existing) activity?.let {
OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), extendedBolus.toString()) OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), extendedBolus.value.toStringFull(dateUtil))
} }
} }
binding.infoLayout.extendedLayout.visibility = (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility() binding.infoLayout.extendedLayout.visibility = (extendedBolus is ValueWrapper.Existing && !pump.isFakingTempsByExtendedBoluses).toVisibility()
// Active profile // Active profile
binding.loopPumpStatusLayout.activeProfile.text = profileFunction.getProfileNameWithDuration() binding.loopPumpStatusLayout.activeProfile.text = profileFunction.getProfileNameWithDuration()
@ -749,8 +747,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
processButtonsVisibility() processButtonsVisibility()
// iob // iob
val bolusIob = iobCobCalculatorPlugin.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
binding.infoLayout.iob.text = resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) binding.infoLayout.iob.text = resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob)
binding.infoLayout.iobLayout.setOnClickListener { binding.infoLayout.iobLayout.setOnClickListener {
@ -769,7 +767,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
// cob // cob
var cobText: String = resourceHelper.gs(R.string.value_unavailable_short) var cobText: String = resourceHelper.gs(R.string.value_unavailable_short)
val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "Overview COB") val cobInfo = iobCobCalculator.getCobInfo(false, "Overview COB")
if (cobInfo.displayCob != null) { if (cobInfo.displayCob != null) {
cobText = resourceHelper.gs(R.string.format_carbs, cobInfo.displayCob!!.toInt()) cobText = resourceHelper.gs(R.string.format_carbs, cobInfo.displayCob!!.toInt())
if (cobInfo.futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(cobInfo.futureCarbs) + ")" if (cobInfo.futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(cobInfo.futureCarbs) + ")"
@ -813,7 +811,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
binding.infoLayout.sensitivity.text = binding.infoLayout.sensitivity.text =
iobCobCalculatorPlugin.getLastAutosensData("Overview")?.let { autosensData -> iobCobCalculator.getLastAutosensData("Overview")?.let { autosensData ->
String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100) String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100)
} ?: "" } ?: ""
} }
@ -823,7 +821,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (_binding == null) return@launch if (_binding == null) return@launch
val menuChartSettings = overviewMenus.setting val menuChartSettings = overviewMenus.setting
prepareGraphsIfNeeded(menuChartSettings.size) prepareGraphsIfNeeded(menuChartSettings.size)
val graphData = GraphData(injector, binding.graphsLayout.bgGraph, iobCobCalculatorPlugin, treatmentsPlugin) val graphData = GraphData(injector, binding.graphsLayout.bgGraph, iobCobCalculator, treatmentsPlugin)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList() val secondaryGraphsData: ArrayList<GraphData> = ArrayList()
// do preparation in different thread // do preparation in different thread
@ -890,7 +888,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
// ------------------ 2nd graph // ------------------ 2nd graph
synchronized(graphLock) { synchronized(graphLock) {
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) { for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobCalculatorPlugin, treatmentsPlugin) val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobCalculator, treatmentsPlugin)
var useABSForScale = false var useABSForScale = false
var useIobForScale = false var useIobForScale = false
var useCobForScale = false var useCobForScale = false

View file

@ -6,6 +6,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.extensions.*
import info.nightscout.androidaps.interfaces.OverviewInterface import info.nightscout.androidaps.interfaces.OverviewInterface
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugi
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.utils.WarnColors
import info.nightscout.androidaps.utils.extensions.age import info.nightscout.androidaps.extensions.age
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject

View file

@ -24,7 +24,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.* import info.nightscout.androidaps.plugins.general.overview.graphExtensions.*
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.extensions.target import info.nightscout.androidaps.extensions.target
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
@ -259,8 +259,8 @@ class GraphData(
// Extended bolus // Extended bolus
if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) { if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) {
treatmentsPlugin.extendedBolusesFromHistory.list repository.getExtendedBolusDataFromTimeToTime(fromTime, endTime, true).blockingGet()
.filterTimeframe(fromTime, endTime) .map { ExtendedBolusDataPoint(it) }
.filter { it.duration != 0L } .filter { it.duration != 0L }
.forEach { .forEach {
it.y = getNearestBg(it.x.toLong()) it.y = getNearestBg(it.x.toLong())
@ -529,9 +529,9 @@ class GraphData(
while (time <= toTime) { while (time <= toTime) {
// if align Dev Scale with BGI scale, then calculate BGI value, else bgi = 0.0 // if align Dev Scale with BGI scale, then calculate BGI value, else bgi = 0.0
val bgi: Double = if (devBgiScale) { val bgi: Double = if (devBgiScale) {
val profile = profileFunction.getProfile(time) val profile = profileFunction.getProfile(time) ?: continue
total = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile) total = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile)
total.activity * (profile?.getIsfMgdl(time) ?: 0.0) * 5.0 total.activity * profile.getIsfMgdl(time) * 5.0
} else 0.0 } else 0.0
iobCobCalculator.getAutosensData(time)?.let { autosensData -> iobCobCalculator.getAutosensData(time)?.let { autosensData ->

View file

@ -0,0 +1,25 @@
package info.nightscout.androidaps.plugins.general.overview.graphExtensions
import android.graphics.Color
import info.nightscout.androidaps.database.entities.ExtendedBolus
import info.nightscout.androidaps.extensions.toStringTotal
import javax.inject.Inject
class ExtendedBolusDataPoint @Inject constructor(
val data: ExtendedBolus
) : DataPointWithLabelInterface {
private var yValue = 0.0
override fun getX(): Double = data.timestamp.toDouble()
override fun getY(): Double = yValue
override fun getLabel(): String = data.toStringTotal()
override fun getDuration(): Long = data.duration
override fun getSize(): Float = 10f
override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.EXTENDEDBOLUS
override fun getColor(): Int = Color.CYAN
override fun setY(y: Double) {
yValue = y
}
}

View file

@ -15,15 +15,14 @@ import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.extensions.toStringShort
import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.IconsProvider
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.extensions.valueToUnitsString import info.nightscout.androidaps.extensions.valueToUnitsString
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -150,14 +149,14 @@ class PersistentNotificationPlugin @Inject constructor(
line1aa = resourceHelper.gs(R.string.missed_bg_readings) line1aa = resourceHelper.gs(R.string.missed_bg_readings)
line1 = line1aa line1 = line1aa
} }
val activeTemp = activePlugins.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
if (activeTemp != null) { if (activeTemp != null) {
line1 += " " + activeTemp.toStringShort() line1 += " " + activeTemp.toStringShort()
line1aa += " " + activeTemp.toStringShort() + "." line1aa += " " + activeTemp.toStringShort() + "."
} }
//IOB //IOB
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = activePlugins.activeTreatments.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString()
val line2aa = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + "." val line2aa = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + "."
line3 = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h" line3 = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h"

View file

@ -41,7 +41,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.extensions.valueToUnitsString import info.nightscout.androidaps.extensions.valueToUnitsString
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -322,7 +322,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val glucoseStatus = glucoseStatusProvider.glucoseStatusData val glucoseStatus = glucoseStatusProvider.glucoseStatusData
if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", "
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB") val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB")
reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "

View file

@ -1,10 +1,9 @@
package info.nightscout.androidaps.plugins.general.tidepool.comm package info.nightscout.androidaps.plugins.general.tidepool.comm
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TemporaryBasal
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
@ -146,18 +145,19 @@ class UploadChunk @Inject constructor(
return selection return selection
} }
private fun fromTemporaryBasals(tbrList: Intervals<TemporaryBasal>, start: Long, end: Long): List<BasalElement> { private fun fromTemporaryBasals(tbrList: List<TemporaryBasal>, start: Long, end: Long): List<BasalElement> {
val results = LinkedList<BasalElement>() val results = LinkedList<BasalElement>()
for (tbr in tbrList.list) { for (tbr in tbrList) {
if (tbr.date in start..end && tbr.durationInMinutes != 0) if (tbr.timestamp in start..end)
results.add(BasalElement(tbr, profileFunction)) profileFunction.getProfile(tbr.timestamp)?.let {
results.add(BasalElement(tbr, it))
}
} }
return results return results
} }
private fun getBasals(start: Long, end: Long): List<BasalElement> { private fun getBasals(start: Long, end: Long): List<BasalElement> {
val temporaryBasals = treatmentsPlugin.temporaryBasalsFromHistory val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(start, end, true).blockingGet()
temporaryBasals.merge()
val selection = fromTemporaryBasals(temporaryBasals, start, end) // TODO do not upload running TBR val selection = fromTemporaryBasals(temporaryBasals, start, end) // TODO do not upload running TBR
if (selection.isNotEmpty()) if (selection.isNotEmpty())
rxBus.send(EventTidepoolStatus("${selection.size} TBRs selected for upload")) rxBus.send(EventTidepoolStatus("${selection.size} TBRs selected for upload"))

View file

@ -1,32 +1,38 @@
package info.nightscout.androidaps.plugins.general.tidepool.elements package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.database.entities.TemporaryBasal
import info.nightscout.androidaps.extensions.convertedToAbsolute
import java.util.* import java.util.*
class BasalElement(tbr: TemporaryBasal, private val profileFunction: ProfileFunction) class BasalElement(tbr: TemporaryBasal, private val profile: Profile)
: BaseElement(tbr.date, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.date).toByteArray()).toString()) { : BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString()) {
internal var timestamp: Long = 0 // not exposed internal var timestamp: Long = 0 // not exposed
@Expose @Expose
internal var deliveryType = "automated" internal var deliveryType = "automated"
@Expose @Expose
internal var duration: Long = 0 internal var duration: Long = 0
@Expose @Expose
internal var rate = -1.0 internal var rate = -1.0
@Expose @Expose
internal var scheduleName = "AAPS" internal var scheduleName = "AAPS"
@Expose @Expose
internal var clockDriftOffset: Long = 0 internal var clockDriftOffset: Long = 0
@Expose @Expose
internal var conversionOffset: Long = 0 internal var conversionOffset: Long = 0
init { init {
type = "basal" type = "basal"
timestamp = tbr.date timestamp = tbr.timestamp
rate = tbr.tempBasalConvertedToAbsolute(tbr.date, profileFunction.getProfile(tbr.date)) rate = tbr.convertedToAbsolute(tbr.timestamp, profile)
duration = tbr.end() - tbr.start() duration = tbr.duration
} }
} }

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.utils.extensions.toConstant import info.nightscout.androidaps.extensions.toConstant
import java.util.* import java.util.*
class BloodGlucoseElement(therapyEvent: TherapyEvent) class BloodGlucoseElement(therapyEvent: TherapyEvent)

View file

@ -33,7 +33,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.extensions.valueToUnits import info.nightscout.androidaps.extensions.valueToUnits
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP

View file

@ -32,13 +32,14 @@ import dagger.android.AndroidInjection;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.database.AppRepository; import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.Bolus; import info.nightscout.androidaps.database.entities.Bolus;
import info.nightscout.androidaps.database.entities.GlucoseValue; import info.nightscout.androidaps.database.entities.GlucoseValue;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.database.entities.TemporaryBasal;
import info.nightscout.androidaps.extensions.GlucoseValueExtensionKt;
import info.nightscout.androidaps.extensions.TemporaryBasalExtensionKt;
import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.IobCobCalculator; import info.nightscout.androidaps.interfaces.IobCobCalculator;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
@ -48,17 +49,16 @@ import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint;
import info.nightscout.androidaps.plugins.general.wear.WearPlugin; import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction; import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction;
import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction; import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.receivers.ReceiverStatusStore;
import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.DefaultValueHelper; import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.extensions.GlucoseValueExtensionKt;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -75,7 +75,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
@Inject public ActivePluginProvider activePlugin; @Inject public ActivePluginProvider activePlugin;
@Inject public LoopPlugin loopPlugin; @Inject public LoopPlugin loopPlugin;
@Inject public IobCobCalculator iobCobCalculator; @Inject public IobCobCalculator iobCobCalculator;
@Inject public TreatmentsPlugin treatmentsPlugin;
@Inject public AppRepository repository; @Inject public AppRepository repository;
@Inject ReceiverStatusStore receiverStatusStore; @Inject ReceiverStatusStore receiverStatusStore;
@Inject Config config; @Inject Config config;
@ -437,8 +436,8 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
double beginBasalValue = profile.getBasal(beginBasalSegmentTime); double beginBasalValue = profile.getBasal(beginBasalSegmentTime);
double endBasalValue = beginBasalValue; double endBasalValue = beginBasalValue;
TemporaryBasal tb1 = treatmentsPlugin.getTempBasalFromHistory(runningTime); TemporaryBasal tb1 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime);
TemporaryBasal tb2 = treatmentsPlugin.getTempBasalFromHistory(runningTime); //TODO for Adrian ... what's the meaning? TemporaryBasal tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime); //TODO for Adrian ... what's the meaning?
double tb_before = beginBasalValue; double tb_before = beginBasalValue;
double tb_amount = beginBasalValue; double tb_amount = beginBasalValue;
long tb_start = runningTime; long tb_start = runningTime;
@ -447,7 +446,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
tb_before = beginBasalValue; tb_before = beginBasalValue;
Profile profileTB = profileFunction.getProfile(runningTime); Profile profileTB = profileFunction.getProfile(runningTime);
if (profileTB != null) { if (profileTB != null) {
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime, profileTB); tb_amount = TemporaryBasalExtensionKt.convertedToAbsolute(tb1, runningTime, profileTB);
tb_start = runningTime; tb_start = runningTime;
} }
} }
@ -469,7 +468,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
} }
//temps //temps
tb2 = treatmentsPlugin.getTempBasalFromHistory(runningTime); tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime);
if (tb1 == null && tb2 == null) { if (tb1 == null && tb2 == null) {
//no temp stays no temp //no temp stays no temp
@ -484,10 +483,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
tb1 = tb2; tb1 = tb2;
tb_start = runningTime; tb_start = runningTime;
tb_before = endBasalValue; tb_before = endBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime, profileTB); tb_amount = TemporaryBasalExtensionKt.convertedToAbsolute(tb1, runningTime, profileTB);
} else if (tb1 != null && tb2 != null) { } else if (tb1 != null && tb2 != null) {
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime, profileTB); double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, runningTime, profileTB);
if (currentAmount != tb_amount) { if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount)); temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount));
tb_start = runningTime; tb_start = runningTime;
@ -502,14 +501,14 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue)); basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
} }
if (tb1 != null) { if (tb1 != null) {
tb2 = treatmentsPlugin.getTempBasalFromHistory(now); //use "now" to express current situation tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now); //use "now" to express current situation
if (tb2 == null) { if (tb2 == null) {
//express the cancelled temp by painting it down one minute early //express the cancelled temp by painting it down one minute early
temps.add(tempDatamap(tb_start, tb_before, now - 1 * 60 * 1000, endBasalValue, tb_amount)); temps.add(tempDatamap(tb_start, tb_before, now - 1 * 60 * 1000, endBasalValue, tb_amount));
} else { } else {
//express currently running temp by painting it a bit into the future //express currently running temp by painting it a bit into the future
Profile profileNow = profileFunction.getProfile(now); Profile profileNow = profileFunction.getProfile(now);
double currentAmount = tb2.tempBasalConvertedToAbsolute(now, profileNow); double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, now, profileNow);
if (currentAmount != tb_amount) { if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, now, tb_amount, tb_amount)); temps.add(tempDatamap(tb_start, tb_before, now, tb_amount, tb_amount));
temps.add(tempDatamap(now, tb_amount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)); temps.add(tempDatamap(now, tb_amount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
@ -518,11 +517,11 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
} }
} }
} else { } else {
tb2 = treatmentsPlugin.getTempBasalFromHistory(now); //use "now" to express current situation tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now); //use "now" to express current situation
if (tb2 != null) { if (tb2 != null) {
//onset at the end //onset at the end
Profile profileTB = profileFunction.getProfile(runningTime); Profile profileTB = profileFunction.getProfile(runningTime);
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime, profileTB); double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, runningTime, profileTB);
temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)); temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
} }
} }
@ -538,7 +537,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) { if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) {
List<GlucoseValueDataPoint> predArray = List<GlucoseValueDataPoint> predArray =
finalLastRun.getConstraintsProcessed().getPredictions() finalLastRun.getConstraintsProcessed().getPredictions()
.stream().map( bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) .stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper))
.collect(Collectors.toList()); .collect(Collectors.toList());
if (!predArray.isEmpty()) { if (!predArray.isEmpty()) {
@ -688,7 +687,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
iobSum = iobDetail = cobString = currentBasal = bgiString = ""; iobSum = iobDetail = cobString = currentBasal = bgiString = "";
if (profile != null) { if (profile != null) {
IobTotal bolusIob = iobCobCalculator.calculateIobFromBolus().round(); IobTotal bolusIob = iobCobCalculator.calculateIobFromBolus().round();
IobTotal basalIob = treatmentsPlugin.getLastCalculationTempBasals().round(); IobTotal basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round();
iobSum = DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob + basalIob.basaliob); iobSum = DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob + basalIob.basaliob);
iobDetail = "(" + DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.INSTANCE.to2Decimal(basalIob.basaliob) + ")"; iobDetail = "(" + DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.INSTANCE.to2Decimal(basalIob.basaliob) + ")";
@ -798,15 +797,11 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
if (profile == null) if (profile == null)
return ""; return "";
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis());
if (activeTemp != null) { if (activeTemp != null) {
basalStringResult = activeTemp.toStringShort(); basalStringResult = TemporaryBasalExtensionKt.toStringShort(activeTemp);
} else { } else {
if (sp.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false)) { basalStringResult = DecimalFormatter.INSTANCE.to2Decimal(profile.getBasal()) + "U/h";
basalStringResult = "100%";
} else {
basalStringResult = DecimalFormatter.INSTANCE.to2Decimal(profile.getBasal()) + "U/h";
}
} }
return basalStringResult; return basalStringResult;
} }

View file

@ -13,6 +13,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.extensions.toStringShort
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -121,13 +122,13 @@ class StatusLinePlugin @Inject constructor(
lastLoopStatus = true lastLoopStatus = true
} }
//Temp basal //Temp basal
val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
if (activeTemp != null) { if (activeTemp != null) {
status += activeTemp.toStringShort() + " " status += activeTemp.toStringShort() + " "
} }
//IOB //IOB
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U" status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U"
if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) { if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) {
status += ("(" status += ("("

View file

@ -6,8 +6,8 @@ import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.extensions.storeInt import info.nightscout.androidaps.extensions.storeInt
import info.nightscout.androidaps.utils.extensions.putInt import info.nightscout.androidaps.extensions.putInt
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONObject import org.json.JSONObject

View file

@ -9,9 +9,12 @@ import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.MealData import info.nightscout.androidaps.data.MealData
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.ExtendedBolus
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.database.entities.TemporaryBasal
import info.nightscout.androidaps.database.interfaces.end
import info.nightscout.androidaps.events.* import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -23,12 +26,13 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHi
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.extensions.iobCalc import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.iobCalc
import info.nightscout.androidaps.extensions.toTemporaryBasal
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -52,7 +56,6 @@ open class IobCobCalculatorPlugin @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val treatmentsPlugin: TreatmentsPlugin,
private val sensitivityOref1Plugin: SensitivityOref1Plugin, private val sensitivityOref1Plugin: SensitivityOref1Plugin,
private val sensitivityAAPSPlugin: SensitivityAAPSPlugin, private val sensitivityAAPSPlugin: SensitivityAAPSPlugin,
private val sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin, private val sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin,
@ -173,7 +176,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
return autosensDataTable return autosensDataTable
} }
fun adjustToReferenceTime(someTime: Long): Long { private fun adjustToReferenceTime(someTime: Long): Long {
if (referenceTime == -1L) { if (referenceTime == -1L) {
referenceTime = someTime referenceTime = someTime
return someTime return someTime
@ -377,11 +380,25 @@ open class IobCobCalculatorPlugin @Inject constructor(
bucketedData = bData bucketedData = bData
} }
fun oldestDataAvailable(): Long {
var oldestTime = System.currentTimeMillis()
val oldestTempBasal = repository.getOldestTemporaryBasalRecord()
if (oldestTempBasal != null) oldestTime = Math.min(oldestTime, oldestTempBasal.timestamp)
val oldestExtendedBolus = repository.getOldestExtendedBolusRecord()
if (oldestExtendedBolus != null) oldestTime = Math.min(oldestTime, oldestExtendedBolus.timestamp)
val oldestBolus = repository.getOldestBolusRecord()
if (oldestBolus != null) oldestTime = Math.min(oldestTime, oldestBolus.timestamp)
val oldestCarbs = repository.getOldestCarbsRecord()
if (oldestCarbs != null) oldestTime = Math.min(oldestTime, oldestCarbs.timestamp)
oldestTime -= 15 * 60 * 1000L // allow 15 min before
return oldestTime
}
fun calculateDetectionStart(from: Long, limitDataToOldestAvailable: Boolean): Long { fun calculateDetectionStart(from: Long, limitDataToOldestAvailable: Boolean): Long {
val profile = profileFunction.getProfile(from) val profile = profileFunction.getProfile(from)
var dia = Constants.defaultDIA var dia = Constants.defaultDIA
if (profile != null) dia = profile.dia if (profile != null) dia = profile.dia
val oldestDataAvailable = treatmentsPlugin.oldestDataAvailable() val oldestDataAvailable = oldestDataAvailable()
val getBGDataFrom: Long val getBGDataFrom: Long
if (limitDataToOldestAvailable) { if (limitDataToOldestAvailable) {
getBGDataFrom = max(oldestDataAvailable, (from - T.hours(1).msecs() * (24 + dia)).toLong()) getBGDataFrom = max(oldestDataAvailable, (from - T.hours(1).msecs() * (24 + dia)).toLong())
@ -390,7 +407,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
return getBGDataFrom return getBGDataFrom
} }
override fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile?): IobTotal { override fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile): IobTotal {
synchronized(dataLock) { return calculateFromTreatmentsAndTemps(time, profile) } synchronized(dataLock) { return calculateFromTreatmentsAndTemps(time, profile) }
} }
@ -398,7 +415,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
synchronized(dataLock) { return calculateFromTreatmentsAndTemps(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget) } synchronized(dataLock) { return calculateFromTreatmentsAndTemps(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget) }
} }
fun calculateFromTreatmentsAndTemps(fromTime: Long, profile: Profile?): IobTotal { fun calculateFromTreatmentsAndTemps(fromTime: Long, profile: Profile): IobTotal {
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val time = roundUpTime(fromTime) val time = roundUpTime(fromTime)
val cacheHit = iobTable[time] val cacheHit = iobTable[time]
@ -407,16 +424,18 @@ open class IobCobCalculatorPlugin @Inject constructor(
return cacheHit return cacheHit
} // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); } // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
val bolusIob = calculateIobFromBolusToTime(time).round() val bolusIob = calculateIobFromBolusToTime(time).round()
val basalIob = treatmentsPlugin.getCalculationToTimeTempBasals(time, true, now).round() val basalIob = calculateIobToTimeFromTempBasalsIncludingConvertedExtended(time).round()
// OpenAPSSMB only // OpenAPSSMB only
// Add expected zero temp basal for next 240 minutes // Add expected zero temp basal for next 240 minutes
val basalIobWithZeroTemp = basalIob.copy() val basalIobWithZeroTemp = basalIob.copy()
val t = TemporaryBasal(injector) val t = TemporaryBasal(
.date(now + 60 * 1000L) timestamp = now + 60 * 1000L,
.duration(240) duration = 240,
.absolute(0.0) rate = 0.0,
if (t.date < time) { isAbsolute = true,
val calc = t.iobCalc(time, profile) type = TemporaryBasal.Type.NORMAL)
if (t.timestamp < time) {
val calc = t.iobCalc(time, profile, activePlugin.activeInsulin)
basalIobWithZeroTemp.plus(calc) basalIobWithZeroTemp.plus(calc)
} }
basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round() basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round()
@ -437,7 +456,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
return cacheHit return cacheHit
} // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); } // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
val bolusIob = calculateIobFromBolusToTime(time).round() val bolusIob = calculateIobFromBolusToTime(time).round()
val basalIob = treatmentsPlugin.getAbsoluteIOBTempBasals(time).round() val basalIob = calculateAbsoluteIobTempBasals(time).round()
val iobTotal = IobTotal.combine(bolusIob, basalIob).round() val iobTotal = IobTotal.combine(bolusIob, basalIob).round()
if (time < System.currentTimeMillis()) { if (time < System.currentTimeMillis()) {
absIobTable.put(time, iobTotal) absIobTable.put(time, iobTotal)
@ -449,18 +468,20 @@ open class IobCobCalculatorPlugin @Inject constructor(
private fun calculateFromTreatmentsAndTemps(time: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal { private fun calculateFromTreatmentsAndTemps(time: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal {
val now = DateUtil.now() val now = DateUtil.now()
val bolusIob = calculateIobFromBolusToTime(time).round() val bolusIob = calculateIobFromBolusToTime(time).round()
val basalIob = treatmentsPlugin.getCalculationToTimeTempBasals(time, now, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round() val basalIob = getCalculationToTimeTempBasals(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round()
// OpenAPSSMB only // OpenAPSSMB only
// Add expected zero temp basal for next 240 minutes // Add expected zero temp basal for next 240 minutes
val basalIobWithZeroTemp = basalIob.copy() val basalIobWithZeroTemp = basalIob.copy()
val t = TemporaryBasal(injector) val t = TemporaryBasal(
.date(now + 60 * 1000L) timestamp = now + 60 * 1000L,
.duration(240) duration = 240,
.absolute(0.0) rate = 0.0,
if (t.date < time) { isAbsolute = true,
val profile = profileFunction.getProfile(t.date) type = TemporaryBasal.Type.NORMAL)
if (t.timestamp < time) {
val profile = profileFunction.getProfile(t.timestamp)
if (profile != null) { if (profile != null) {
val calc = t.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget) val calc = t.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget, activePlugin.activeInsulin)
basalIobWithZeroTemp.plus(calc) basalIobWithZeroTemp.plus(calc)
} }
} }
@ -484,11 +505,11 @@ open class IobCobCalculatorPlugin @Inject constructor(
if (retVal == null) { if (retVal == null) {
//log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString()); //log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString());
retVal = BasalData() retVal = BasalData()
val tb = treatmentsPlugin.getTempBasalFromHistory(time) val tb = getTempBasalIncludingConvertedExtended(time)
retVal.basal = profile.getBasal(time) retVal.basal = profile.getBasal(time)
if (tb != null) { if (tb != null) {
retVal.isTempBasalRunning = true retVal.isTempBasalRunning = true
retVal.tempBasalAbsolute = tb.tempBasalConvertedToAbsolute(time, profile) retVal.tempBasalAbsolute = tb.convertedToAbsolute(time, profile)
} else { } else {
retVal.isTempBasalRunning = false retVal.isTempBasalRunning = false
retVal.tempBasalAbsolute = retVal.basal retVal.tempBasalAbsolute = retVal.basal
@ -784,31 +805,29 @@ open class IobCobCalculatorPlugin @Inject constructor(
* Time range to the past for IOB calculation * Time range to the past for IOB calculation
* @return milliseconds * @return milliseconds
*/ */
fun range(): Long { fun range(): Long = ((profileFunction.getProfile()?.dia
val dia = profileFunction.getProfile()?.dia ?: Constants.defaultDIA ?: Constants.defaultDIA) * 60 * 60 * 1000).toLong()
return (60 * 60 * 1000L * (24 + dia)).toLong()
}
override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil._now()) override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil._now())
override fun calculateIobFromBolusToTime(timestamp: Long): IobTotal { override fun calculateIobFromBolusToTime(toTime: Long): IobTotal {
val total = IobTotal(timestamp) val total = IobTotal(toTime)
val profile = profileFunction.getProfile() ?: return total val profile = profileFunction.getProfile() ?: return total
val dia = profile.dia val dia = profile.dia
val divisor = sp.getDouble(R.string.key_openapsama_bolussnooze_dia_divisor, 2.0) val divisor = sp.getDouble(R.string.key_openapsama_bolussnooze_dia_divisor, 2.0)
val boluses = repository.getBolusesDataFromTime(timestamp - range(), true).blockingGet() val boluses = repository.getBolusesDataFromTime(toTime - range(), true).blockingGet()
boluses.forEach { t -> boluses.forEach { t ->
if (t.isValid && t.timestamp < timestamp) { if (t.isValid && t.timestamp < toTime) {
val tIOB = t.iobCalc(activePlugin, timestamp, dia) val tIOB = t.iobCalc(activePlugin, toTime, dia)
total.iob += tIOB.iobContrib total.iob += tIOB.iobContrib
total.activity += tIOB.activityContrib total.activity += tIOB.activityContrib
if (t.amount > 0 && t.timestamp > total.lastBolusTime) total.lastBolusTime = t.timestamp if (t.amount > 0 && t.timestamp > total.lastBolusTime) total.lastBolusTime = t.timestamp
if (t.type != Bolus.Type.SMB) { if (t.type != Bolus.Type.SMB) {
// instead of dividing the DIA that only worked on the bilinear curves, // instead of dividing the DIA that only worked on the bilinear curves,
// multiply the time the treatment is seen active. // multiply the time the treatment is seen active.
val timeSinceTreatment = timestamp - t.timestamp val timeSinceTreatment = toTime - t.timestamp
val snoozeTime = t.timestamp + (timeSinceTreatment * divisor).toLong() val snoozeTime = t.timestamp + (timeSinceTreatment * divisor).toLong()
val bIOB = t.iobCalc(activePlugin, snoozeTime, dia) val bIOB = t.iobCalc(activePlugin, snoozeTime, dia)
total.bolussnooze += bIOB.iobContrib total.bolussnooze += bIOB.iobContrib
@ -816,8 +835,146 @@ open class IobCobCalculatorPlugin @Inject constructor(
} }
} }
total.plus(treatmentsPlugin.getCalculationToTimeExtendedBoluses(timestamp)) total.plus(calculateIobToTimeFromExtendedBoluses(toTime))
return total return total
} }
private fun calculateIobToTimeFromExtendedBoluses(toTime: Long): IobTotal {
val total = IobTotal(toTime)
val now = dateUtil._now()
val pumpInterface = activePlugin.activePump
if (!pumpInterface.isFakingTempsByExtendedBoluses) {
val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
for (pos in extendedBoluses.indices) {
val e = extendedBoluses[pos]
if (e.timestamp > toTime) continue
if (e.end > now) e.end = now
val profile = profileFunction.getProfile(e.timestamp) ?: return total
val calc = e.iobCalc(toTime, profile, activePlugin.activeInsulin)
total.plus(calc)
}
}
return total
}
override fun getTempBasal(timestamp: Long): TemporaryBasal? {
val tb = repository.getTemporaryBasalActiveAt(timestamp).blockingGet()
if (tb is ValueWrapper.Existing) return tb.value
return null
}
override fun getExtendedBolus(timestamp: Long): ExtendedBolus? {
val tb = repository.getExtendedBolusActiveAt(timestamp).blockingGet()
if (tb is ValueWrapper.Existing) return tb.value
return null
}
override fun getTempBasalIncludingConvertedExtended(timestamp: Long): TemporaryBasal? {
val tb = repository.getTemporaryBasalActiveAt(timestamp).blockingGet()
if (tb is ValueWrapper.Existing) return tb.value
val eb = repository.getExtendedBolusActiveAt(timestamp).blockingGet()
val profile = profileFunction.getProfile(timestamp) ?: return null
if (eb is ValueWrapper.Existing && activePlugin.activePump.isFakingTempsByExtendedBoluses)
return eb.value.toTemporaryBasal(profile)
return null
}
override fun calculateAbsoluteIobTempBasals(toTime: Long): IobTotal {
val total = IobTotal(toTime)
var i = toTime - range()
while (i < toTime) {
val profile = profileFunction.getProfile(i)
if (profile == null) {
i += T.mins(5).msecs()
continue
}
val runningTBR = getTempBasalIncludingConvertedExtended(i)
val running = runningTBR?.convertedToAbsolute(i, profile) ?: profile.getBasal(i)
val bolus = Bolus(
timestamp = i,
amount = running * 5.0 / 60.0,
type = Bolus.Type.NORMAL,
isBasalInsulin = true
)
val iob = bolus.iobCalc(activePlugin, toTime, profile.dia)
total.basaliob += iob.iobContrib
total.activity += iob.activityContrib
i += T.mins(5).msecs()
}
return total
}
override fun calculateIobFromTempBasalsIncludingConvertedExtended(): IobTotal =
calculateIobToTimeFromTempBasalsIncludingConvertedExtended(dateUtil._now())
override fun calculateIobToTimeFromTempBasalsIncludingConvertedExtended(toTime: Long): IobTotal {
val total = IobTotal(toTime)
val now = dateUtil._now()
val pumpInterface = activePlugin.activePump
val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
for (pos in temporaryBasals.indices) {
val t = temporaryBasals[pos]
if (t.timestamp > toTime) continue
val profile = profileFunction.getProfile(t.timestamp) ?: continue
if (t.end > now) t.end = now
val calc = t.iobCalc(toTime, profile, activePlugin.activeInsulin)
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basaliob);
total.plus(calc)
}
if (pumpInterface.isFakingTempsByExtendedBoluses) {
val totalExt = IobTotal(toTime)
val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
for (pos in extendedBoluses.indices) {
val e = extendedBoluses[pos]
if (e.timestamp > toTime) continue
val profile = profileFunction.getProfile(e.timestamp) ?: continue
if (e.end > now) e.end = now
val calc = e.iobCalc(toTime, profile, activePlugin.activeInsulin)
totalExt.plus(calc)
}
// Convert to basal iob
totalExt.basaliob = totalExt.iob
totalExt.iob = 0.0
totalExt.netbasalinsulin = totalExt.extendedBolusInsulin
totalExt.hightempinsulin = totalExt.extendedBolusInsulin
total.plus(totalExt)
}
return total
}
open fun getCalculationToTimeTempBasals(toTime: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal {
val total = IobTotal(toTime)
val pumpInterface = activePlugin.activePump
val now = dateUtil._now()
val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
for (pos in temporaryBasals.indices) {
val t = temporaryBasals[pos]
if (t.timestamp > toTime) continue
val profile = profileFunction.getProfile(t.timestamp) ?: continue
if (t.end > now) t.end = now
val calc = t.iobCalc(toTime, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget, activePlugin.activeInsulin)
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basaliob);
total.plus(calc)
}
if (pumpInterface.isFakingTempsByExtendedBoluses) {
val totalExt = IobTotal(toTime)
val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
for (pos in extendedBoluses.indices) {
val e = extendedBoluses[pos]
if (e.timestamp > toTime) continue
val profile = profileFunction.getProfile(e.timestamp) ?: continue
if (e.end > now) e.end = now
val calc = e.iobCalc(toTime, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget, activePlugin.activeInsulin)
totalExt.plus(calc)
}
// Convert to basal iob
totalExt.basaliob = totalExt.iob
totalExt.iob = 0.0
totalExt.netbasalinsulin = totalExt.extendedBolusInsulin
totalExt.hightempinsulin = totalExt.extendedBolusInsulin
total.plus(totalExt)
}
return total
}
} }

View file

@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.target import info.nightscout.androidaps.extensions.target
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.* import java.util.*

View file

@ -10,24 +10,29 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.VirtualpumpFragmentBinding import info.nightscout.androidaps.databinding.VirtualpumpFragmentBinding
import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.events.EventTempBasalChange
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import io.reactivex.rxkotlin.plusAssign import info.nightscout.androidaps.extensions.toStringFull
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject import javax.inject.Inject
class VirtualPumpFragment : DaggerFragment() { class VirtualPumpFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin @Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -88,10 +93,11 @@ class VirtualPumpFragment : DaggerFragment() {
@Synchronized @Synchronized
private fun updateGui() { private fun updateGui() {
if (_binding == null) return if (_binding == null) return
val profile = profileFunction.getProfile() ?: return
binding.basabasalrate.text = resourceHelper.gs(R.string.pump_basebasalrate, virtualPumpPlugin.baseBasalRate) binding.basabasalrate.text = resourceHelper.gs(R.string.pump_basebasalrate, virtualPumpPlugin.baseBasalRate)
binding.tempbasal.text = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() binding.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil._now())?.toStringFull(profile, dateUtil)
?: "" ?: ""
binding.extendedbolus.text = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis())?.toString() binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil._now())?.toStringFull(dateUtil)
?: "" ?: ""
binding.battery.text = resourceHelper.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent) binding.battery.text = resourceHelper.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent)
binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble()) binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble())

View file

@ -9,9 +9,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
@ -23,12 +20,13 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.InstanceId.instanceId import info.nightscout.androidaps.utils.InstanceId.instanceId
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.TimeChangeType
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -50,7 +48,7 @@ open class VirtualPumpPlugin @Inject constructor(
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val sp: SP, private val sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val treatmentsPlugin: TreatmentsPlugin, private val iobCobCalculator: IobCobCalculator,
commandQueue: CommandQueueProvider, commandQueue: CommandQueueProvider,
private val pumpSync: PumpSync, private val pumpSync: PumpSync,
private val config: Config, private val config: Config,
@ -223,11 +221,6 @@ open class VirtualPumpPlugin @Inject constructor(
override fun stopBolusDelivering() {} override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val tempBasal = TemporaryBasal(injector)
.date(System.currentTimeMillis())
.absolute(absoluteRate)
.duration(durationInMinutes)
.source(Source.USER)
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = true result.success = true
result.enacted = true result.enacted = true
@ -235,7 +228,16 @@ open class VirtualPumpPlugin @Inject constructor(
result.absolute = absoluteRate result.absolute = absoluteRate
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
treatmentsPlugin.addToHistoryTempBasal(tempBasal) pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil._now(),
rate = absoluteRate,
duration = T.mins(durationInMinutes.toLong()).msecs(),
isAbsolute = true,
type = tbrType,
pumpId = dateUtil._now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Setting temp basal absolute: $result") aapsLogger.debug(LTag.PUMP, "Setting temp basal absolute: $result")
rxBus.send(EventVirtualPumpUpdateGui()) rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis() lastDataTime = System.currentTimeMillis()
@ -243,11 +245,6 @@ open class VirtualPumpPlugin @Inject constructor(
} }
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val tempBasal = TemporaryBasal(injector)
.date(System.currentTimeMillis())
.percent(percent)
.duration(durationInMinutes)
.source(Source.USER)
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = true result.success = true
result.enacted = true result.enacted = true
@ -256,7 +253,16 @@ open class VirtualPumpPlugin @Inject constructor(
result.isTempCancel = false result.isTempCancel = false
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
treatmentsPlugin.addToHistoryTempBasal(tempBasal) pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil._now(),
rate = percent.toDouble(),
duration = T.mins(durationInMinutes.toLong()).msecs(),
isAbsolute = false,
type = tbrType,
pumpId = dateUtil._now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Settings temp basal percent: $result") aapsLogger.debug(LTag.PUMP, "Settings temp basal percent: $result")
rxBus.send(EventVirtualPumpUpdateGui()) rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis() lastDataTime = System.currentTimeMillis()
@ -266,18 +272,21 @@ open class VirtualPumpPlugin @Inject constructor(
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
val result = cancelExtendedBolus() val result = cancelExtendedBolus()
if (!result.success) return result if (!result.success) return result
val extendedBolus = ExtendedBolus(injector)
.date(System.currentTimeMillis())
.insulin(insulin)
.durationInMinutes(durationInMinutes)
.source(Source.USER)
result.success = true result.success = true
result.enacted = true result.enacted = true
result.bolusDelivered = insulin result.bolusDelivered = insulin
result.isTempCancel = false result.isTempCancel = false
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus) pumpSync.syncExtendedBolusWithPumpId(
timestamp = dateUtil._now(),
amount = insulin,
duration = T.mins(durationInMinutes.toLong()).msecs(),
isEmulatingTB = false,
pumpId = dateUtil._now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Setting extended bolus: $result") aapsLogger.debug(LTag.PUMP, "Setting extended bolus: $result")
rxBus.send(EventVirtualPumpUpdateGui()) rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis() lastDataTime = System.currentTimeMillis()
@ -289,11 +298,14 @@ open class VirtualPumpPlugin @Inject constructor(
result.success = true result.success = true
result.isTempCancel = true result.isTempCancel = true
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
if (treatmentsPlugin.isTempBasalInProgress) { if (pumpSync.expectedPumpState().temporaryBasal != null) {
result.enacted = true result.enacted = true
val tempStop = TemporaryBasal(injector).date(System.currentTimeMillis()).source(Source.USER) pumpSync.syncStopTemporaryBasalWithPumpId(
treatmentsPlugin.addToHistoryTempBasal(tempStop) timestamp = dateUtil._now(),
//tempBasal = null; endPumpId = dateUtil._now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result") aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result")
rxBus.send(EventVirtualPumpUpdateGui()) rxBus.send(EventVirtualPumpUpdateGui())
} }
@ -303,10 +315,13 @@ open class VirtualPumpPlugin @Inject constructor(
override fun cancelExtendedBolus(): PumpEnactResult { override fun cancelExtendedBolus(): PumpEnactResult {
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
if (treatmentsPlugin.isInHistoryExtendedBolusInProgress) { if (pumpSync.expectedPumpState().extendedBolus != null) {
val exStop = ExtendedBolus(injector, System.currentTimeMillis()) pumpSync.syncStopExtendedBolusWithPumpId(
exStop.source = Source.USER timestamp = dateUtil._now(),
treatmentsPlugin.addToHistoryExtendedBolus(exStop) endPumpId = dateUtil._now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
} }
result.success = true result.success = true
result.enacted = true result.enacted = true
@ -335,16 +350,16 @@ open class VirtualPumpPlugin @Inject constructor(
extended.put("ActiveProfile", profileName) extended.put("ActiveProfile", profileName)
} catch (ignored: Exception) { } catch (ignored: Exception) {
} }
val tb = treatmentsPlugin.getTempBasalFromHistory(now) val tb = iobCobCalculator.getTempBasal(now)
if (tb != null) { if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)) extended.put("TempBasalAbsoluteRate", tb.convertedToAbsolute(now, profile))
extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date)) extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.timestamp))
extended.put("TempBasalRemaining", tb.plannedRemainingMinutes) extended.put("TempBasalRemaining", tb.plannedRemainingMinutes)
} }
val eb = treatmentsPlugin.getExtendedBolusFromHistory(now) val eb = iobCobCalculator.getExtendedBolus(now)
if (eb != null) { if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()) extended.put("ExtendedBolusAbsoluteRate", eb.rate)
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date)) extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp))
extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes) extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes)
} }
status.put("timestamp", DateUtil.toISOString(now)) status.put("timestamp", DateUtil.toISOString(now))

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.extensions.isEvent5minBack import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.extensions.isEvent5minBack import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.extensions.isEvent5minBack import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException

View file

@ -24,9 +24,9 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.directionToIcon import info.nightscout.androidaps.extensions.directionToIcon
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.extensions.valueToUnitsString import info.nightscout.androidaps.extensions.valueToUnitsString
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable

View file

@ -21,15 +21,12 @@ import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.XDripBroadcast
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -73,10 +70,6 @@ class DexcomPlugin @Inject constructor(
dexcomMediator.requestPermissionIfNeeded() dexcomMediator.requestPermissionIfNeeded()
} }
override fun onStop() {
super.onStop()
}
// cannot be inner class because of needed injection // cannot be inner class because of needed injection
class DexcomWorker( class DexcomWorker(
context: Context, context: Context,

View file

@ -57,6 +57,9 @@ class RandomBgPlugin @Inject constructor(
companion object { companion object {
const val interval = 5L // minutes const val interval = 5L // minutes
const val min = 70 // mgdl
const val max = 190 // mgdl
const val period = 30.0 // minutes
} }
init { init {
@ -93,12 +96,10 @@ class RandomBgPlugin @Inject constructor(
private fun handleNewData() { private fun handleNewData() {
if (!isEnabled(PluginType.BGSOURCE)) return if (!isEnabled(PluginType.BGSOURCE)) return
val min = 70
val max = 190
val cal = GregorianCalendar() val cal = GregorianCalendar()
val currentMinute = cal.get(Calendar.MINUTE) + (cal.get(Calendar.HOUR_OF_DAY) % 2) * 60 val currentMinute = cal.get(Calendar.MINUTE) + (cal.get(Calendar.HOUR_OF_DAY) % 2) * 60
val bgMgdl = min + ((max - min) + (max - min) * sin(currentMinute / 120.0 * 2 * PI)) / 2 val bgMgdl = min + ((max - min) + (max - min) * sin(currentMinute / period * 2 * PI)) / 2
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>() val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( glucoseValues += CgmSourceTransaction.TransactionGlucoseValue(

View file

@ -15,7 +15,6 @@ import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.XDripBroadcast
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -49,7 +48,6 @@ class TomatoPlugin @Inject constructor(
@Inject lateinit var tomatoPlugin: TomatoPlugin @Inject lateinit var tomatoPlugin: TomatoPlugin
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var broadcastToXDrip: XDripBroadcast @Inject lateinit var broadcastToXDrip: XDripBroadcast

View file

@ -11,11 +11,13 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.TreatmentsFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsFragmentBinding
import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.treatments.fragments.* import info.nightscout.androidaps.plugins.treatments.fragments.*
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -28,9 +30,10 @@ class TreatmentsFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var dateUtil: DateUtil
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -124,6 +127,6 @@ class TreatmentsFragment : DaggerFragment() {
private fun updateGui() { private fun updateGui() {
if (_binding == null) return if (_binding == null) return
binding.extendedBoluses.visibility = (activePlugin.activePump.pumpDescription.isExtendedBolusCapable || treatmentsPlugin.extendedBolusesFromHistory.size() > 0).toVisibility() binding.extendedBoluses.visibility = (activePlugin.activePump.pumpDescription.isExtendedBolusCapable || iobCobCalculator.getExtendedBolus(dateUtil._now()) != null).toVisibility()
} }
} }

View file

@ -1,13 +1,10 @@
package info.nightscout.androidaps.plugins.treatments; package info.nightscout.androidaps.plugins.treatments;
import android.content.Context; import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -17,25 +14,15 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.NonOverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileIntervals; import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.database.AppRepository; import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.Bolus;
import info.nightscout.androidaps.database.entities.Carbs;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventReloadProfileSwitchData; import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -43,25 +30,16 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentServiceInterface; import info.nightscout.androidaps.interfaces.TreatmentServiceInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.interfaces.UpdateReturn;
import info.nightscout.androidaps.interfaces.UploadQueueInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.extensions.BolusExtensionKt;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.rx.AapsSchedulers;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -78,7 +56,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final ActivePluginProvider activePlugin; private final ActivePluginProvider activePlugin;
private final NSUpload nsUpload; private final NSUpload nsUpload;
private final UploadQueueInterface uploadQueue;
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final DateUtil dateUtil; private final DateUtil dateUtil;
private final DatabaseHelperInterface databaseHelper; private final DatabaseHelperInterface databaseHelper;
@ -88,8 +65,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
protected TreatmentServiceInterface service; protected TreatmentServiceInterface service;
private final Intervals<TemporaryBasal> tempBasals = new NonOverlappingIntervals<>();
private final Intervals<ExtendedBolus> extendedBoluses = new NonOverlappingIntervals<>();
private final ProfileIntervals<ProfileSwitch> profiles = new ProfileIntervals<>(); private final ProfileIntervals<ProfileSwitch> profiles = new ProfileIntervals<>();
@Inject @Inject
@ -106,7 +81,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
NSUpload nsUpload, NSUpload nsUpload,
FabricPrivacy fabricPrivacy, FabricPrivacy fabricPrivacy,
DateUtil dateUtil, DateUtil dateUtil,
UploadQueueInterface uploadQueue,
DatabaseHelperInterface databaseHelper, DatabaseHelperInterface databaseHelper,
AppRepository repository AppRepository repository
) { ) {
@ -131,7 +105,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
this.fabricPrivacy = fabricPrivacy; this.fabricPrivacy = fabricPrivacy;
this.dateUtil = dateUtil; this.dateUtil = dateUtil;
this.nsUpload = nsUpload; this.nsUpload = nsUpload;
this.uploadQueue = uploadQueue;
this.databaseHelper = databaseHelper; this.databaseHelper = databaseHelper;
this.repository = repository; this.repository = repository;
} }
@ -141,32 +114,12 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
this.service = new TreatmentService(getInjector()); this.service = new TreatmentService(getInjector());
initializeData(range()); initializeData(range());
super.onStart(); super.onStart();
disposable.add(rxBus
.toObservable(EventReloadTreatmentData.class)
.observeOn(aapsSchedulers.getIo())
.subscribe(event -> {
getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTreatmentData");
//initializeTreatmentData(range());
initializeExtendedBolusData(range());
rxBus.send(event.getNext());
},
fabricPrivacy::logException
));
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventReloadProfileSwitchData.class) .toObservable(EventReloadProfileSwitchData.class)
.observeOn(aapsSchedulers.getIo()) .observeOn(aapsSchedulers.getIo())
.subscribe(event -> initializeProfileSwitchData(range()), .subscribe(event -> initializeProfileSwitchData(range()),
fabricPrivacy::logException fabricPrivacy::logException
)); ));
disposable.add(rxBus
.toObservable(EventReloadTempBasalData.class)
.observeOn(aapsSchedulers.getIo())
.subscribe(event -> {
getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTempBasalData");
initializeTempBasalData(range());
},
fabricPrivacy::logException
));
} }
@Override @Override
@ -188,27 +141,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
public void initializeData(long range) { public void initializeData(long range) {
initializeTempBasalData(range);
initializeExtendedBolusData(range);
initializeProfileSwitchData(range); initializeProfileSwitchData(range);
} }
private void initializeTempBasalData(long range) {
getAapsLogger().debug(LTag.DATATREATMENTS, "initializeTempBasalData");
synchronized (tempBasals) {
tempBasals.reset().add(databaseHelper.getTemporaryBasalsDataFromTime(DateUtil.now() - range, false));
}
}
private void initializeExtendedBolusData(long range) {
getAapsLogger().debug(LTag.DATATREATMENTS, "initializeExtendedBolusData");
synchronized (extendedBoluses) {
extendedBoluses.reset().add(databaseHelper.getExtendedBolusDataFromTime(DateUtil.now() - range, false));
}
}
private void initializeProfileSwitchData(long range) { private void initializeProfileSwitchData(long range) {
getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData"); getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData");
synchronized (profiles) { synchronized (profiles) {
@ -216,28 +151,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
} }
@Override
public IobTotal getCalculationToTimeExtendedBoluses(long time) {
IobTotal total = new IobTotal(time);
Profile profile = profileFunction.getProfile();
if (profile == null)
return total;
PumpInterface pumpInterface = activePlugin.getActivePump();
if (!pumpInterface.isFakingTempsByExtendedBoluses())
synchronized (extendedBoluses) {
for (int pos = 0; pos < extendedBoluses.size(); pos++) {
ExtendedBolus e = extendedBoluses.get(pos);
if (e.date > time) continue;
IobTotal calc = e.iobCalc(time, profile);
total.plus(calc);
}
}
return total;
}
/** /**
* Returns all Treatments after specified timestamp. Also returns invalid entries (required to * Returns all Treatments after specified timestamp. Also returns invalid entries (required to
* map "Fill Cannula" entries to history (and not to add double bolus for it) * map "Fill Cannula" entries to history (and not to add double bolus for it)
@ -307,211 +220,12 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
*/ */
@Override @Deprecated
public boolean isInHistoryRealTempBasalInProgress() {
return getRealTempBasalFromHistory(System.currentTimeMillis()) != null;
}
@Override
public TemporaryBasal getRealTempBasalFromHistory(long time) {
synchronized (tempBasals) {
return tempBasals.getValueByInterval(time);
}
}
@Override
public boolean isTempBasalInProgress() {
return getTempBasalFromHistory(System.currentTimeMillis()) != null;
}
@Override public void removeTempBasal(TemporaryBasal tempBasal) {
String tempBasalId = tempBasal._id;
if (NSUpload.isIdValid(tempBasalId)) {
nsUpload.removeCareportalEntryFromNS(tempBasalId);
} else {
uploadQueue.removeByMongoId("dbAdd", tempBasalId);
}
databaseHelper.delete(tempBasal);
}
@Override
public boolean isInHistoryExtendedBolusInProgress() {
return getExtendedBolusFromHistory(System.currentTimeMillis()) != null; //TODO: crosscheck here
}
@Override
public IobTotal getLastCalculationTempBasals() {
return getCalculationToTimeTempBasals(DateUtil.now());
}
@Override
public IobTotal getCalculationToTimeTempBasals(long time) {
return getCalculationToTimeTempBasals(time, false, 0);
}
public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) {
IobTotal total = new IobTotal(time);
PumpInterface pumpInterface = activePlugin.getActivePump();
synchronized (tempBasals) {
for (int pos = 0; pos < tempBasals.size(); pos++) {
TemporaryBasal t = tempBasals.get(pos);
if (t.date > time) continue;
IobTotal calc;
Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue;
if (truncate && t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal(getInjector());
dummyTemp.copyFrom(t);
dummyTemp.cutEndTo(truncateTime);
calc = dummyTemp.iobCalc(time, profile);
} else {
calc = t.iobCalc(time, profile);
}
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basaliob);
total.plus(calc);
}
}
if (pumpInterface.isFakingTempsByExtendedBoluses()) {
IobTotal totalExt = new IobTotal(time);
synchronized (extendedBoluses) {
for (int pos = 0; pos < extendedBoluses.size(); pos++) {
ExtendedBolus e = extendedBoluses.get(pos);
if (e.date > time) continue;
IobTotal calc;
Profile profile = profileFunction.getProfile(e.date);
if (profile == null) continue;
if (truncate && e.end() > truncateTime) {
ExtendedBolus dummyExt = new ExtendedBolus(getInjector());
dummyExt.copyFrom(e);
dummyExt.cutEndTo(truncateTime);
calc = dummyExt.iobCalc(time, profile);
} else {
calc = e.iobCalc(time, profile);
}
totalExt.plus(calc);
}
}
// Convert to basal iob
totalExt.basaliob = totalExt.iob;
totalExt.iob = 0d;
totalExt.netbasalinsulin = totalExt.extendedBolusInsulin;
totalExt.hightempinsulin = totalExt.extendedBolusInsulin;
total.plus(totalExt);
}
return total;
}
public IobTotal getAbsoluteIOBTempBasals(long time) {
IobTotal total = new IobTotal(time);
for (long i = time - range(); i < time; i += T.mins(5).msecs()) {
Profile profile = profileFunction.getProfile(i);
if (profile == null) continue;
double basal = profile.getBasal(i);
TemporaryBasal runningTBR = getTempBasalFromHistory(i);
double running = basal;
if (runningTBR != null) {
running = runningTBR.tempBasalConvertedToAbsolute(i, profile);
}
Bolus bolus = new Bolus(
0, // id
0, // version
0, //dateCreated
true, // isValid
null,
null,
i,
0,
running * 5.0 / 60.0,
Bolus.Type.NORMAL,
true,
null
);
Iob iob = BolusExtensionKt.iobCalc(bolus, activePlugin, time, profile.getDia());
total.basaliob += iob.getIobContrib();
total.activity += iob.getActivityContrib();
}
return total;
}
public IobTotal getCalculationToTimeTempBasals(long time, long truncateTime, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) {
IobTotal total = new IobTotal(time);
PumpInterface pumpInterface = activePlugin.getActivePump();
synchronized (tempBasals) {
for (int pos = 0; pos < tempBasals.size(); pos++) {
TemporaryBasal t = tempBasals.get(pos);
if (t.date > time) continue;
IobTotal calc;
Profile profile = profileFunction.getProfile(t.date);
if (profile == null) continue;
if (t.end() > truncateTime) {
TemporaryBasal dummyTemp = new TemporaryBasal(getInjector());
dummyTemp.copyFrom(t);
dummyTemp.cutEndTo(truncateTime);
calc = dummyTemp.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget);
} else {
calc = t.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget);
}
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basaliob);
total.plus(calc);
}
}
if (pumpInterface.isFakingTempsByExtendedBoluses()) {
IobTotal totalExt = new IobTotal(time);
synchronized (extendedBoluses) {
for (int pos = 0; pos < extendedBoluses.size(); pos++) {
ExtendedBolus e = extendedBoluses.get(pos);
if (e.date > time) continue;
IobTotal calc;
Profile profile = profileFunction.getProfile(e.date);
if (profile == null) continue;
if (e.end() > truncateTime) {
ExtendedBolus dummyExt = new ExtendedBolus(getInjector());
dummyExt.copyFrom(e);
dummyExt.cutEndTo(truncateTime);
calc = dummyExt.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget);
} else {
calc = e.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget);
}
totalExt.plus(calc);
}
}
// Convert to basal iob
totalExt.basaliob = totalExt.iob;
totalExt.iob = 0d;
totalExt.netbasalinsulin = totalExt.extendedBolusInsulin;
totalExt.hightempinsulin = totalExt.extendedBolusInsulin;
total.plus(totalExt);
}
return total;
}
@Nullable
@Override
public TemporaryBasal getTempBasalFromHistory(long time) {
TemporaryBasal tb = getRealTempBasalFromHistory(time);
if (tb != null)
return tb;
ExtendedBolus eb = getExtendedBolusFromHistory(time);
if (eb != null && activePlugin.getActivePump().isFakingTempsByExtendedBoluses())
return new TemporaryBasal(eb);
return null;
}
@Override
public ExtendedBolus getExtendedBolusFromHistory(long time) {
synchronized (extendedBoluses) {
return extendedBoluses.getValueByInterval(time);
}
}
@Override @Override
public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) { public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) {
throw new IllegalStateException("Migrate to new DB");
//log.debug("Adding new ExtentedBolus record" + extendedBolus.log()); //log.debug("Adding new ExtentedBolus record" + extendedBolus.log());
/*
boolean newRecordCreated = databaseHelper.createOrUpdate(extendedBolus); boolean newRecordCreated = databaseHelper.createOrUpdate(extendedBolus);
if (newRecordCreated) { if (newRecordCreated) {
if (extendedBolus.durationInMinutes == 0) { if (extendedBolus.durationInMinutes == 0) {
@ -525,26 +239,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
nsUpload.uploadExtendedBolus(extendedBolus); nsUpload.uploadExtendedBolus(extendedBolus);
} }
return newRecordCreated; return newRecordCreated;
*/
} }
@Override @Deprecated
@NonNull
public Intervals<ExtendedBolus> getExtendedBolusesFromHistory() {
synchronized (extendedBoluses) {
return new NonOverlappingIntervals<>(extendedBoluses);
}
}
@Override
@NonNull
public NonOverlappingIntervals<TemporaryBasal> getTemporaryBasalsFromHistory() {
synchronized (tempBasals) {
return new NonOverlappingIntervals<>(tempBasals);
}
}
@Override @Override
public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) { public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) {
throw new IllegalStateException("Migrate to new DB");
/*
//log.debug("Adding new TemporaryBasal record" + tempBasal.toString()); //log.debug("Adding new TemporaryBasal record" + tempBasal.toString());
boolean newRecordCreated = databaseHelper.createOrUpdate(tempBasal); boolean newRecordCreated = databaseHelper.createOrUpdate(tempBasal);
if (newRecordCreated) { if (newRecordCreated) {
@ -556,17 +258,25 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date)); nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date));
} }
return newRecordCreated; return newRecordCreated;
*/
} }
@Deprecated
public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) {
throw new IllegalStateException("Migrate to new DB");
/*
UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout); UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout);
return new TreatmentUpdateReturn(resultRecord.getSuccess(), resultRecord.getNewRecord()); return new TreatmentUpdateReturn(resultRecord.getSuccess(), resultRecord.getNewRecord());
*/
} }
// return true if new record is created // return true if new record is created
@Deprecated
@Override @Override
public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) { public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) {
throw new IllegalStateException("Migrate to new DB");
/*
boolean medtronicPump = activePlugin.getActivePump() instanceof MedtronicPumpPlugin; boolean medtronicPump = activePlugin.getActivePump() instanceof MedtronicPumpPlugin;
getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump); getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump);
@ -627,27 +337,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
return newRecordCreated; return newRecordCreated;
} */
@Override
public long oldestDataAvailable() {
long oldestTime = System.currentTimeMillis();
synchronized (tempBasals) {
if (tempBasals.size() > 0)
oldestTime = Math.min(oldestTime, tempBasals.get(0).date);
}
synchronized (extendedBoluses) {
if (extendedBoluses.size() > 0)
oldestTime = Math.min(oldestTime, extendedBoluses.get(0).date);
}
Bolus oldestBolus = repository.getOldestBolusRecord();
if (oldestBolus != null)
oldestTime = Math.min(oldestTime, oldestBolus.getTimestamp());
Carbs oldestCarbs = repository.getOldestCarbsRecord();
if (oldestCarbs != null)
oldestTime = Math.min(oldestTime, oldestCarbs.getTimestamp());
oldestTime -= 15 * 60 * 1000L; // allow 15 min before
return oldestTime;
} }
@Override @Override

View file

@ -28,7 +28,6 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -36,8 +35,8 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.iobCalc import info.nightscout.androidaps.extensions.iobCalc
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -274,7 +273,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
ml.bolus?.let { bolus -> ml.bolus?.let { bolus ->
holder.binding.bolusDate.text = dateUtil.timeString(bolus.timestamp) holder.binding.bolusDate.text = dateUtil.timeString(bolus.timestamp)
holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, bolus.amount) holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, bolus.amount)
holder.binding.bolusNs.visibility = (NSUpload.isIdValid(bolus.interfaceIDs.nightscoutId)).toVisibility() holder.binding.bolusNs.visibility = (bolus.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.bolusPump.visibility = (bolus.interfaceIDs.pumpId != null).toVisibility() holder.binding.bolusPump.visibility = (bolus.interfaceIDs.pumpId != null).toVisibility()
holder.binding.bolusInvalid.visibility = bolus.isValid.not().toVisibility() holder.binding.bolusInvalid.visibility = bolus.isValid.not().toVisibility()
val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia) val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia)
@ -283,8 +282,8 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
if (bolus.timestamp > dateUtil._now()) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorScheduled)) else holder.binding.date.setTextColor(holder.binding.carbs.currentTextColor) if (bolus.timestamp > dateUtil._now()) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorScheduled)) else holder.binding.date.setTextColor(holder.binding.carbs.currentTextColor)
holder.binding.mealOrCorrection.text = holder.binding.mealOrCorrection.text =
when (ml.bolus.type) { when (ml.bolus.type) {
Bolus.Type.SMB -> "SMB" Bolus.Type.SMB -> "SMB"
Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus) Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus)
Bolus.Type.PRIMING -> resourceHelper.gs(R.string.prime) Bolus.Type.PRIMING -> resourceHelper.gs(R.string.prime)
} }
} }
@ -293,8 +292,8 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
ml.carbs?.let { carbs -> ml.carbs?.let { carbs ->
holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp) holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp)
holder.binding.carbs.text = resourceHelper.gs(R.string.format_carbs, carbs.amount.toInt()) holder.binding.carbs.text = resourceHelper.gs(R.string.format_carbs, carbs.amount.toInt())
holder.binding.carbsDuration.text = if (carbs.duration> 0) resourceHelper.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) else "" holder.binding.carbsDuration.text = if (carbs.duration > 0) resourceHelper.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) else ""
holder.binding.carbsNs.visibility = (NSUpload.isIdValid(carbs.interfaceIDs.nightscoutId)).toVisibility() holder.binding.carbsNs.visibility = (carbs.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility() holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility()
holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility() holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility()
} }

View file

@ -32,7 +32,7 @@ import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.Translator
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP

View file

@ -11,45 +11,52 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry.* import info.nightscout.androidaps.database.entities.ExtendedBolus
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.interfaces.end
import info.nightscout.androidaps.database.transactions.InvalidateExtendedBolusTransaction
import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusItemBinding import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusItemBinding
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.extensions.getPassedDurationToTimeInMinutes
import info.nightscout.androidaps.extensions.iobCalc
import info.nightscout.androidaps.extensions.isInProgress
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
class TreatmentsExtendedBolusesFragment : DaggerFragment() { class TreatmentsExtendedBolusesFragment : DaggerFragment() {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
private val millsToThePast = T.days(30).msecs()
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var databaseHelper: DatabaseHelperInterface
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var repository: AppRepository
private var _binding: TreatmentsExtendedbolusFragmentBinding? = null private var _binding: TreatmentsExtendedbolusFragmentBinding? = null
@ -58,18 +65,54 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
private val binding get() = _binding!! private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View { savedInstanceState: Bundle?): View =
_binding = TreatmentsExtendedbolusFragmentBinding.inflate(inflater, container, false) TreatmentsExtendedbolusFragmentBinding.inflate(inflater, container, false).also { _binding = it }.root
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.recyclerview.setHasFixedSize(true) binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.recyclerview.adapter = RecyclerViewAdapter(activePlugin.activeTreatments.extendedBolusesFromHistory)
} }
private inner class RecyclerViewAdapter(private var extendedBolusList: Intervals<ExtendedBolus>) : RecyclerView.Adapter<ExtendedBolusesViewHolder>() { fun swapAdapter() {
val now = System.currentTimeMillis()
if (binding.showInvalidated.isChecked)
repository
.getExtendedBolusDataIncludingInvalidFromTime(now - millsToThePast, false)
.observeOn(aapsSchedulers.main)
.subscribe { list -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(list), true) }
else
repository
.getExtendedBolusDataFromTime(now - millsToThePast, false)
.observeOn(aapsSchedulers.main)
.subscribe { list -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(list), true) }
}
@Synchronized
override fun onResume() {
super.onResume()
swapAdapter()
disposable += rxBus
.toObservable(EventExtendedBolusChange::class.java)
.observeOn(aapsSchedulers.io)
.debounce(1L, TimeUnit.SECONDS)
.subscribe({ swapAdapter() }, fabricPrivacy::logException)
}
@Synchronized
override fun onPause() {
super.onPause()
disposable.clear()
}
@Synchronized
override fun onDestroyView() {
super.onDestroyView()
binding.recyclerview.adapter = null // avoid leaks
_binding = null
}
private inner class RecyclerViewAdapter(private var extendedBolusList: List<ExtendedBolus>) : RecyclerView.Adapter<ExtendedBolusesViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ExtendedBolusesViewHolder { override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ExtendedBolusesViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_extendedbolus_item, viewGroup, false) val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_extendedbolus_item, viewGroup, false)
@ -77,38 +120,28 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
} }
override fun onBindViewHolder(holder: ExtendedBolusesViewHolder, position: Int) { override fun onBindViewHolder(holder: ExtendedBolusesViewHolder, position: Int) {
val extendedBolus = extendedBolusList.getReversed(position) val extendedBolus = extendedBolusList[position]
holder.binding.ph.visibility = if (extendedBolus.source == Source.PUMP) View.VISIBLE else View.GONE holder.binding.ph.visibility = (extendedBolus.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.ns.visibility = if (NSUpload.isIdValid(extendedBolus._id)) View.VISIBLE else View.GONE holder.binding.invalid.visibility = extendedBolus.isValid.not().toVisibility()
if (extendedBolus.isEndingEvent) { @SuppressLint("SetTextI18n")
holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.date) if (extendedBolus.isInProgress(dateUtil)) {
holder.binding.duration.text = resourceHelper.gs(R.string.cancel) holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp)
holder.binding.insulin.text = "" holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive))
holder.binding.realDuration.text = ""
holder.binding.iob.text = ""
holder.binding.insulinSoFar.text = ""
holder.binding.ratio.text = ""
} else { } else {
@SuppressLint("SetTextI18n") holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp) + " - " + dateUtil.timeString(extendedBolus.end)
if (extendedBolus.isInProgress) holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.date) holder.binding.date.setTextColor(holder.binding.insulin.currentTextColor)
else holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.date) + " - " + dateUtil.timeString(extendedBolus.end())
val profile = profileFunction.getProfile(extendedBolus.date)
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, extendedBolus.durationInMinutes)
holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.insulin)
holder.binding.realDuration.text = resourceHelper.gs(R.string.format_mins, extendedBolus.realDuration)
val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iob)
holder.binding.insulinSoFar.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.insulinSoFar())
holder.binding.ratio.text = resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.absoluteRate())
if (extendedBolus.isInProgress) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.date.setTextColor(holder.binding.insulin.currentTextColor)
if (iob.iob != 0.0) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.insulin.currentTextColor)
} }
val profile = profileFunction.getProfile(extendedBolus.timestamp) ?: return
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(extendedBolus.duration).mins())
holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.amount)
val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile, activePlugin.activeInsulin)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iob)
holder.binding.ratio.text = resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate)
if (iob.iob != 0.0) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.insulin.currentTextColor)
holder.binding.remove.tag = extendedBolus holder.binding.remove.tag = extendedBolus
} }
override fun getItemCount(): Int { override fun getItemCount(): Int = extendedBolusList.size
return extendedBolusList.size()
}
inner class ExtendedBolusesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { inner class ExtendedBolusesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@ -117,17 +150,17 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
init { init {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val extendedBolus = v.tag as ExtendedBolus val extendedBolus = v.tag as ExtendedBolus
context?.let { context?.let { context ->
OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(context, resourceHelper.gs(R.string.removerecord),
""" """
${resourceHelper.gs(R.string.extended_bolus)} ${resourceHelper.gs(R.string.extended_bolus)}
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.date)} ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.timestamp)}
""".trimIndent(), { _: DialogInterface, _: Int -> """.trimIndent(), { _: DialogInterface, _: Int ->
uel.log(Action.EXTENDED_BOLUS_REMOVED) uel.log(Action.EXTENDED_BOLUS_REMOVED)
val id = extendedBolus._id disposable += repository.runTransactionForResult(InvalidateExtendedBolusTransaction(extendedBolus.id))
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) .subscribe(
else uploadQueue.removeByMongoId("dbAdd", id) { aapsLogger.debug(LTag.DATABASE, "Removed extended bolus $extendedBolus") },
databaseHelper.delete(extendedBolus) { aapsLogger.error(LTag.DATABASE, "Error while invalidating extended bolus", it) })
}, null) }, null)
} }
} }
@ -136,35 +169,4 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
} }
} }
@Synchronized override fun onResume() {
super.onResume()
disposable.add(rxBus
.toObservable(EventExtendedBolusChange::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updateGui() }, fabricPrivacy::logException)
)
disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updateGui() }, fabricPrivacy::logException)
)
updateGui()
}
@Synchronized override fun onPause() {
super.onPause()
disposable.clear()
}
@Synchronized
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun updateGui() {
if (_binding == null) return
binding.recyclerview.swapAdapter(RecyclerViewAdapter(activePlugin.activeTreatments.extendedBolusesFromHistory), false)
}
} }

View file

@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP

View file

@ -37,10 +37,10 @@ import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.Translator
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.friendlyDescription import info.nightscout.androidaps.extensions.friendlyDescription
import info.nightscout.androidaps.utils.extensions.highValueToUnitsToString import info.nightscout.androidaps.extensions.highValueToUnitsToString
import info.nightscout.androidaps.utils.extensions.lowValueToUnitsToString import info.nightscout.androidaps.extensions.lowValueToUnitsToString
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -151,7 +151,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
_binding = null _binding = null
} }
inner class RecyclerViewAdapter internal constructor(private var tempTargetList: List<TemporaryTarget>) : RecyclerView.Adapter<TempTargetsViewHolder>() { private inner class RecyclerViewAdapter internal constructor(private var tempTargetList: List<TemporaryTarget>) : RecyclerView.Adapter<TempTargetsViewHolder>() {
private val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() private val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet()
private val currentlyActiveTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null private val currentlyActiveTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null

View file

@ -10,33 +10,43 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals
import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TemporaryBasal
import info.nightscout.androidaps.database.entities.UserEntry.* import info.nightscout.androidaps.database.entities.UserEntry.*
import info.nightscout.androidaps.database.interfaces.end
import info.nightscout.androidaps.database.transactions.InvalidateTemporaryBasalTransaction
import info.nightscout.androidaps.databinding.TreatmentsTempbasalsFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsTempbasalsFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsTempbasalsItemBinding import info.nightscout.androidaps.databinding.TreatmentsTempbasalsItemBinding
import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.events.EventTempBasalChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment.RecyclerViewAdapter.TempBasalsViewHolder import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment.RecyclerViewAdapter.TempBasalsViewHolder
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.extensions.getPassedDurationToTimeInMinutes
import info.nightscout.androidaps.extensions.iobCalc
import info.nightscout.androidaps.extensions.toStringFull
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject import javax.inject.Inject
import kotlin.math.abs
class TreatmentsTemporaryBasalsFragment : DaggerFragment() { class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@ -45,9 +55,12 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var repository: AppRepository
private var _binding: TreatmentsTempbasalsFragmentBinding? = null private var _binding: TreatmentsTempbasalsFragmentBinding? = null
private val millsToThePast = T.days(30).msecs()
// This property is only valid between onCreateView and // This property is only valid between onCreateView and
// onDestroyView. // onDestroyView.
private val binding get() = _binding!! private val binding get() = _binding!!
@ -59,23 +72,37 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
binding.recyclerview.setHasFixedSize(true) binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.recyclerview.adapter = RecyclerViewAdapter(activePlugin.activeTreatments.temporaryBasalsFromHistory) }
fun swapAdapter() {
val now = System.currentTimeMillis()
if (binding.showInvalidated.isChecked)
repository
.getTemporaryBasalsDataIncludingInvalidFromTime(now - millsToThePast, false)
.observeOn(aapsSchedulers.main)
.subscribe { list -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(list), true) }
else
repository
.getTemporaryBasalsDataFromTime(now - millsToThePast, false)
.observeOn(aapsSchedulers.main)
.subscribe { list -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(list), true) }
} }
@Synchronized @Synchronized
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
swapAdapter()
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventTempBasalChange::class.java) .toObservable(EventTempBasalChange::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe({ updateGui() }, fabricPrivacy::logException) .subscribe({ swapAdapter() }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished::class.java) .toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe({ updateGui() }, fabricPrivacy::logException) .subscribe({ swapAdapter() }, fabricPrivacy::logException)
) )
updateGui()
} }
@Synchronized @Synchronized
@ -87,69 +114,44 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
@Synchronized @Synchronized
override fun onDestroyView() { override fun onDestroyView() {
super.onDestroyView() super.onDestroyView()
binding.recyclerview.adapter = null // avoid leaks
_binding = null _binding = null
} }
inner class RecyclerViewAdapter internal constructor(private var tempBasalList: Intervals<TemporaryBasal>) : RecyclerView.Adapter<TempBasalsViewHolder>() { inner class RecyclerViewAdapter internal constructor(private var tempBasalList: List<TemporaryBasal>) : RecyclerView.Adapter<TempBasalsViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TempBasalsViewHolder = override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TempBasalsViewHolder =
TempBasalsViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_tempbasals_item, viewGroup, false)) TempBasalsViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_tempbasals_item, viewGroup, false))
override fun onBindViewHolder(holder: TempBasalsViewHolder, position: Int) { override fun onBindViewHolder(holder: TempBasalsViewHolder, position: Int) {
val tempBasal = tempBasalList.getReversed(position) val tempBasal = tempBasalList[position]
holder.binding.ph.visibility = if (tempBasal.source == Source.PUMP) View.VISIBLE else View.GONE holder.binding.ns.visibility = (tempBasal.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.ns.visibility = if (NSUpload.isIdValid(tempBasal._id)) View.VISIBLE else View.GONE holder.binding.invalid.visibility = tempBasal.isValid.not().toVisibility()
if (tempBasal.isEndingEvent) { holder.binding.ph.visibility = (tempBasal.interfaceIDs.pumpId != null).toVisibility()
holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.date) if (tempBasal.isInProgress) {
holder.binding.duration.text = resourceHelper.gs(R.string.cancel) holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.timestamp)
holder.binding.absolute.text = "" holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive))
holder.binding.percent.text = ""
holder.binding.realDuration.text = ""
holder.binding.iob.text = ""
holder.binding.netInsulin.text = ""
holder.binding.netRatio.text = ""
holder.binding.extendedFlag.visibility = View.GONE
holder.binding.iob.setTextColor(holder.binding.netRatio.currentTextColor)
} else { } else {
if (tempBasal.isInProgress) { holder.binding.date.text = dateUtil.dateAndTimeRangeString(tempBasal.timestamp, tempBasal.end)
holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.date) holder.binding.date.setTextColor(holder.binding.duration.currentTextColor)
holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive))
} else {
holder.binding.date.text = dateUtil.dateAndTimeRangeString(tempBasal.date, tempBasal.end())
holder.binding.date.setTextColor(holder.binding.netRatio.currentTextColor)
}
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, tempBasal.durationInMinutes)
if (tempBasal.isAbsolute) {
val profile = profileFunction.getProfile(tempBasal.date)
if (profile != null) {
holder.binding.absolute.text = resourceHelper.gs(R.string.pump_basebasalrate, tempBasal.tempBasalConvertedToAbsolute(tempBasal.date, profile))
holder.binding.percent.text = ""
} else {
holder.binding.absolute.text = resourceHelper.gs(R.string.noprofile)
holder.binding.percent.text = ""
}
} else {
holder.binding.absolute.text = ""
holder.binding.percent.text = resourceHelper.gs(R.string.format_percent, tempBasal.percentRate)
}
holder.binding.realDuration.text = resourceHelper.gs(R.string.format_mins, tempBasal.realDuration)
val now = DateUtil.now()
var iob = IobTotal(now)
val profile = profileFunction.getProfile(now)
if (profile != null) iob = tempBasal.iobCalc(now, profile)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.basaliob)
holder.binding.netInsulin.text = resourceHelper.gs(R.string.formatinsulinunits, iob.netInsulin)
holder.binding.netRatio.text = resourceHelper.gs(R.string.pump_basebasalrate, iob.netRatio)
holder.binding.extendedFlag.visibility = View.GONE
if (iob.basaliob != 0.0) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.netRatio.currentTextColor)
} }
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins())
if (tempBasal.isAbsolute) holder.binding.rate.text = resourceHelper.gs(R.string.pump_basebasalrate, tempBasal.rate)
else holder.binding.rate.text = resourceHelper.gs(R.string.format_percent, tempBasal.rate.toInt())
val now = DateUtil.now()
var iob = IobTotal(now)
val profile = profileFunction.getProfile(now)
if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.basaliob)
holder.binding.extendedFlag.visibility = (tempBasal.type == TemporaryBasal.Type.FAKE_EXTENDED).toVisibility()
if (abs(iob.basaliob) > 0.01) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.duration.currentTextColor)
holder.binding.type.text = tempBasal.type.toString()
holder.binding.remove.tag = tempBasal holder.binding.remove.tag = tempBasal
} }
override fun getItemCount(): Int { override fun getItemCount(): Int = tempBasalList.size
return tempBasalList.size()
}
@Deprecated("remove remove functionality after finish")
inner class TempBasalsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { inner class TempBasalsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = TreatmentsTempbasalsItemBinding.bind(itemView) val binding = TreatmentsTempbasalsItemBinding.bind(itemView)
@ -157,15 +159,20 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
init { init {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val tempBasal = v.tag as TemporaryBasal val tempBasal = v.tag as TemporaryBasal
val profile = profileFunction.getProfile(dateUtil._now())
?: return@setOnClickListener
context?.let { context?.let {
OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord),
""" """
${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull()} ${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull(profile, dateUtil)}
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.date)} ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)}
""".trimIndent(), """.trimIndent(),
{ _: DialogInterface?, _: Int -> { _: DialogInterface?, _: Int ->
uel.log(Action.TT_REMOVED, ValueWithUnit(tempBasal.date, Units.Timestamp)) uel.log(Action.TB_REMOVED, ValueWithUnit(tempBasal.timestamp, Units.Timestamp))
activePlugin.activeTreatments.removeTempBasal(tempBasal) disposable += repository.runTransactionForResult(InvalidateTemporaryBasalTransaction(tempBasal.id))
.subscribe(
{ aapsLogger.debug(LTag.DATABASE, "Removed temporary basal $tempBasal") },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating temporary basal", it) })
}, null) }, null)
} }
} }
@ -174,11 +181,4 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
} }
} }
private fun updateGui() {
if (_binding == null) return
binding.recyclerview.swapAdapter(RecyclerViewAdapter(activePlugin.activeTreatments.temporaryBasalsFromHistory), false)
val tempBasalsCalculation = activePlugin.activeTreatments.lastCalculationTempBasals
if (tempBasalsCalculation != null) binding.totalTempIob.text = resourceHelper.gs(R.string.formatinsulinunits, tempBasalsCalculation.basaliob)
}
} }

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.*
import info.nightscout.androidaps.databinding.TreatmentsUserEntryFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsUserEntryFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsUserEntryItemBinding import info.nightscout.androidaps.databinding.TreatmentsUserEntryItemBinding
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.extensions.colorId
import info.nightscout.androidaps.interfaces.ImportExportPrefsInterface import info.nightscout.androidaps.interfaces.ImportExportPrefsInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger

View file

@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.LocalAlertUtils import info.nightscout.androidaps.utils.LocalAlertUtils
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.extensions.buildDeviceStatus import info.nightscout.androidaps.extensions.buildDeviceStatus
import javax.inject.Inject import javax.inject.Inject
import kotlin.math.abs import kotlin.math.abs

View file

@ -20,7 +20,7 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.general.maintenance.formats.Prefs import info.nightscout.androidaps.plugins.general.maintenance.formats.Prefs
import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsStatus import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsStatus
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.extensions.runOnUiThread import info.nightscout.androidaps.extensions.runOnUiThread
import java.util.* import java.util.*
object PrefImportSummaryDialog { object PrefImportSummaryDialog {

View file

@ -9,7 +9,7 @@ import android.view.View
import android.widget.TextView import android.widget.TextView
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.extensions.runOnUiThread import info.nightscout.androidaps.extensions.runOnUiThread
object TwoMessagesAlertDialog { object TwoMessagesAlertDialog {

View file

@ -1,71 +1,48 @@
package info.nightscout.androidaps.utils.stats package info.nightscout.androidaps.utils.stats
import android.content.Context
import android.text.Spanned import android.text.Spanned
import android.util.LongSparseArray import android.util.LongSparseArray
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.db.TDD
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
class TddCalculator @Inject constructor( class TddCalculator @Inject constructor(
injector: HasAndroidInjector, private val aapsLogger: AAPSLogger,
aapsLogger: AAPSLogger, private val resourceHelper: ResourceHelper,
rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
context: Context,
aapsSchedulers: AapsSchedulers,
sp: SP,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
fabricPrivacy: FabricPrivacy,
nsUpload: NSUpload,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
uploadQueue: UploadQueueInterface, private val iobCobCalculator: IobCobCalculator,
databaseHelper: DatabaseHelperInterface,
private val repository: AppRepository private val repository: AppRepository
) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) { ) {
init {
service = TreatmentService(injector) // plugin is not started
}
fun calculate(days: Long): LongSparseArray<TDD> { fun calculate(days: Long): LongSparseArray<TDD> {
val range = T.days(days + 1).msecs()
val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs()) val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs())
val endTime = MidnightTime.calc(DateUtil.now()) val endTime = MidnightTime.calc(DateUtil.now())
initializeData(range)
val result = LongSparseArray<TDD>() val result = LongSparseArray<TDD>()
repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet() repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet()
.filter { it.type != Bolus.Type.PRIMING } .filter { it.type != Bolus.Type.PRIMING }
.forEach { t-> .forEach { t ->
val midnight = MidnightTime.calc(t.timestamp) val midnight = MidnightTime.calc(t.timestamp)
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
tdd.bolus += t.amount tdd.bolus += t.amount
result.put(midnight, tdd) result.put(midnight, tdd)
} }
repository.getCarbsDataFromTimeToTimeExpanded(startTime, endTime, true).blockingGet().forEach { t-> repository.getCarbsDataFromTimeToTimeExpanded(startTime, endTime, true).blockingGet().forEach { t ->
val midnight = MidnightTime.calc(t.timestamp) val midnight = MidnightTime.calc(t.timestamp)
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
tdd.carbs += t.amount tdd.carbs += t.amount
@ -75,15 +52,15 @@ class TddCalculator @Inject constructor(
for (t in startTime until endTime step T.mins(5).msecs()) { for (t in startTime until endTime step T.mins(5).msecs()) {
val midnight = MidnightTime.calc(t) val midnight = MidnightTime.calc(t)
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
val tbr = getTempBasalFromHistory(t) val tbr = iobCobCalculator.getTempBasalIncludingConvertedExtended(t)
val profile = profileFunction.getProfile(t, this) ?: continue val profile = profileFunction.getProfile(t) ?: continue
val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t) val absoluteRate = tbr?.convertedToAbsolute(t, profile) ?: profile.getBasal(t)
tdd.basal += absoluteRate / 60.0 * 5.0 tdd.basal += absoluteRate / 60.0 * 5.0
if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) { if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) {
// they are not included in TBRs // they are not included in TBRs
val eb = getExtendedBolusFromHistory(t) val eb = iobCobCalculator.getExtendedBolus(t)
val absoluteEbRate = eb?.absoluteRate() ?: 0.0 val absoluteEbRate = eb?.rate ?: 0.0
tdd.bolus += absoluteEbRate / 60.0 * 5.0 tdd.bolus += absoluteEbRate / 60.0 * 5.0
} }
result.put(midnight, tdd) result.put(midnight, tdd)

View file

@ -23,7 +23,6 @@ import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
@ -33,7 +32,7 @@ import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -62,7 +61,6 @@ class BolusWizard @Inject constructor(
@Inject lateinit var carbTimer: CarbTimer @Inject lateinit var carbTimer: CarbTimer
@Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var nsUpload: NSUpload
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -205,7 +203,7 @@ class BolusWizard @Inject constructor(
// Insulin from IOB // Insulin from IOB
// IOB calculation // IOB calculation
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0 insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0
insulinFromBasalIOB = if (includeBasalIOB) -basalIob.basaliob else 0.0 insulinFromBasalIOB = if (includeBasalIOB) -basalIob.basaliob else 0.0

View file

@ -6,16 +6,15 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.JsonHelper.safeGetInt import info.nightscout.androidaps.utils.JsonHelper.safeGetInt
import info.nightscout.androidaps.utils.JsonHelper.safeGetString import info.nightscout.androidaps.utils.JsonHelper.safeGetString
import info.nightscout.androidaps.utils.extensions.valueToUnits import info.nightscout.androidaps.extensions.valueToUnits
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
@ -27,9 +26,8 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider
@ -89,7 +87,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
// COB // COB
var cob = 0.0 var cob = 0.0
if (useCOB() == YES) { if (useCOB() == YES) {
val cobInfo = iobCobCalculatorPlugin.getCobInfo(_synchronized, "QuickWizard COB") val cobInfo = iobCobCalculator.getCobInfo(_synchronized, "QuickWizard COB")
if (cobInfo.displayCob != null) cob = cobInfo.displayCob!! if (cobInfo.displayCob != null) cob = cobInfo.displayCob!!
} }
// Bolus IOB // Bolus IOB
@ -98,7 +96,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
bolusIOB = true bolusIOB = true
} }
// Basal IOB // Basal IOB
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
var basalIOB = false var basalIOB = false
if (useBasalIOB() == YES) { if (useBasalIOB() == YES) {
basalIOB = true basalIOB = true

View file

@ -141,8 +141,6 @@
</LinearLayout> </LinearLayout>
<include layout="@layout/datetime" />
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"

View file

@ -1,10 +1,34 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:orientation="vertical" android:orientation="vertical"
tools:context=".plugins.treatments.fragments.TreatmentsExtendedBolusesFragment"> tools:context=".plugins.treatments.fragments.TreatmentsExtendedBolusesFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/show_invalidated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center_vertical"
android:checked="false"
android:paddingEnd="5dp"
tools:ignore="RtlSymmetry" />
<ImageView
app:srcCompat="@drawable/ic_visibility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:contentDescription="@string/show_removed" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView <androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview" android:id="@+id/recyclerview"
android:layout_width="match_parent" android:layout_width="match_parent"

View file

@ -55,73 +55,9 @@
android:textAppearance="?android:attr/textAppearanceSmall" android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText,RtlSymmetry" /> tools:ignore="HardcodedText,RtlSymmetry" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView <TextView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingStart="10dp"
android:paddingEnd="5dp"
android:text="@string/tempbasals_realduration_label_string"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/real_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="10 min"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingEnd="5dp"
android:text="@string/tempbasals_netratio_label_string"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="RtlSymmetry" />
<TextView
android:id="@+id/ratio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="0.05 U/h"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingEnd="5dp"
android:text="@string/tempbasals_netinsulin_label_string"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="RtlSymmetry" />
<TextView
android:id="@+id/insulin_so_far"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="0.05 U"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp" android:layout_marginEnd="10dp"
android:layout_weight="1" android:layout_weight="1"
android:text="" /> android:text="" />
@ -156,6 +92,25 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="top" android:layout_gravity="top"
android:paddingLeft="10dp" android:paddingLeft="10dp"
android:paddingEnd="5dp"
android:text="@string/tempbasals_netratio_label_string"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="RtlSymmetry" />
<TextView
android:id="@+id/ratio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="0.05 U/h"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingRight="10dp" android:paddingRight="10dp"
android:text="@string/tempbasals_iob_label_string" android:text="@string/tempbasals_iob_label_string"
android:textAppearance="?android:attr/textAppearanceSmall" /> android:textAppearance="?android:attr/textAppearanceSmall" />
@ -171,15 +126,35 @@
tools:ignore="HardcodedText" /> tools:ignore="HardcodedText" />
<TextView <TextView
android:id="@+id/remove" android:layout_width="wrap_content"
android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="10dp" android:layout_marginEnd="10dp"
android:layout_weight="1" android:layout_weight="1"
android:text="" />
<TextView
android:id="@+id/invalid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="@string/invalid"
android:textColor="@android:color/holo_red_light" />
<TextView
android:id="@+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="@string/remove_button" android:text="@string/remove_button"
android:textAlignment="viewEnd" android:textAlignment="viewEnd"
android:textColor="@android:color/holo_orange_light" /> android:textColor="@android:color/holo_orange_light" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
tools:ignore="RtlSymmetry" />
</LinearLayout> </LinearLayout>
<View <View

View file

@ -1,4 +1,5 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
@ -9,26 +10,24 @@
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal" android:orientation="horizontal">
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView <CheckBox
android:id="@+id/show_invalidated"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:paddingStart="10dp" android:layout_gravity="end|center_vertical"
android:text="@string/tempbasals_iobtotal_label_string" android:checked="false"
android:textAppearance="?android:attr/textAppearanceSmall" android:paddingEnd="5dp"
tools:ignore="RtlSymmetry" /> tools:ignore="RtlSymmetry" />
<TextView <ImageView
android:id="@+id/total_temp_iob"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:paddingStart="10dp" android:layout_gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceSmall" android:contentDescription="@string/show_removed"
android:textStyle="bold" app:srcCompat="@drawable/ic_visibility" />
tools:ignore="RtlSymmetry" />
</LinearLayout> </LinearLayout>

View file

@ -38,16 +38,7 @@
tools:ignore="HardcodedText" /> tools:ignore="HardcodedText" />
<TextView <TextView
android:id="@+id/absolute" android:id="@+id/rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="10dp"
android:text="0.25 U"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:id="@+id/percent"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:paddingStart="10dp" android:paddingStart="10dp"
@ -65,93 +56,24 @@
tools:ignore="HardcodedText,RtlSymmetry" /> tools:ignore="HardcodedText,RtlSymmetry" />
<TextView <TextView
android:id="@+id/extended_flag"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="1" />
android:gravity="end"
android:paddingEnd="5dp" <TextView
android:id="@+id/extended_flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="E" android:text="E"
android:textColor="@color/colorSetExtendedButton" android:textColor="@color/colorSetExtendedButton"
tools:ignore="HardcodedText,RtlSymmetry" /> tools:ignore="HardcodedText,RtlSymmetry" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingStart="10dp"
android:paddingEnd="5dp"
android:text="@string/tempbasals_realduration_label_string"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/real_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="10 min"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingEnd="5dp"
android:text="@string/tempbasals_netratio_label_string"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="RtlSymmetry" />
<TextView
android:id="@+id/net_ratio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="0.05 U/h"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingEnd="5dp"
android:text="@string/tempbasals_netinsulin_label_string"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="RtlSymmetry" />
<TextView
android:id="@+id/net_insulin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingEnd="10dp"
android:text="0.05 U"
android:textStyle="bold"
tools:ignore="HardcodedText,RtlSymmetry" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:text="" />
<TextView <TextView
android:id="@+id/ph" android:id="@+id/ph"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="10dp" android:layout_marginStart="5dp"
android:text="PH" android:text="PH"
android:textColor="@color/colorSetTempButton" android:textColor="@color/colorSetTempButton"
tools:ignore="HardcodedText" /> tools:ignore="HardcodedText" />
@ -160,11 +82,17 @@
android:id="@+id/ns" android:id="@+id/ns"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="10dp" android:layout_marginStart="5dp"
android:text="NS" android:text="NS"
android:textColor="@color/colorSetTempButton" android:textColor="@color/colorSetTempButton"
tools:ignore="HardcodedText" /> tools:ignore="HardcodedText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
tools:ignore="RtlSymmetry" />
</LinearLayout> </LinearLayout>
<LinearLayout <LinearLayout
@ -192,24 +120,51 @@
tools:ignore="HardcodedText" /> tools:ignore="HardcodedText" />
<TextView <TextView
android:id="@+id/remove"
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="10dp" android:layout_weight="1" />
android:layout_weight="1"
<TextView
android:id="@+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="NORMAL"
android:textColor="@color/colorSetTempButton"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/invalid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="@string/invalid"
android:textColor="@android:color/holo_red_light" />
<TextView
android:id="@+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="@string/remove_button" android:text="@string/remove_button"
android:textAlignment="viewEnd" android:textAlignment="viewEnd"
android:textColor="@android:color/holo_orange_light" /> android:textColor="@android:color/holo_orange_light" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingEnd="10dp"
tools:ignore="RtlSymmetry" />
</LinearLayout> </LinearLayout>
<View <View
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="2dip" android:layout_height="2dip"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp" android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:background="@color/list_delimiter" /> android:background="@color/list_delimiter" />
</LinearLayout> </LinearLayout>

View file

@ -38,7 +38,6 @@
android:contentDescription="@string/show_removed" android:contentDescription="@string/show_removed"
app:srcCompat="@drawable/ic_visibility" /> app:srcCompat="@drawable/ic_visibility" />
</LinearLayout> </LinearLayout>
<androidx.recyclerview.widget.RecyclerView <androidx.recyclerview.widget.RecyclerView

View file

@ -44,6 +44,8 @@
<string name="key_ns_carbs_last_synced_id" translatable="false">ns_carbs_last_synced_id</string> <string name="key_ns_carbs_last_synced_id" translatable="false">ns_carbs_last_synced_id</string>
<string name="key_ns_bolus_last_synced_id" translatable="false">ns_bolus_last_synced_id</string> <string name="key_ns_bolus_last_synced_id" translatable="false">ns_bolus_last_synced_id</string>
<string name="key_ns_device_status_last_synced_id" translatable="false">ns_device_status_last_synced_id</string> <string name="key_ns_device_status_last_synced_id" translatable="false">ns_device_status_last_synced_id</string>
<string name="key_ns_temporary_basal_last_synced_id" translatable="false">ns_temporary_basal_last_synced_id</string>
<string name="key_ns_extended_bolus_last_synced_id" translatable="false">ns_extended_bolus_last_synced_id</string>
<string name="treatmentssafety_title">Treatments safety</string> <string name="treatmentssafety_title">Treatments safety</string>
<string name="treatmentssafety_maxbolus_title">Max allowed bolus [U]</string> <string name="treatmentssafety_maxbolus_title">Max allowed bolus [U]</string>

View file

@ -4,11 +4,7 @@ import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.DefaultValueHelper
@ -26,6 +22,7 @@ open class TestBaseWithProfile : TestBase() {
@Mock lateinit var activePluginProvider: ActivePluginProvider @Mock lateinit var activePluginProvider: ActivePluginProvider
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var treatmentsInterface: TreatmentsInterface @Mock lateinit var treatmentsInterface: TreatmentsInterface
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var defaultValueHelper: DefaultValueHelper @Mock lateinit var defaultValueHelper: DefaultValueHelper

View file

@ -6,6 +6,7 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.interfaces.PumpInterface
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.TimeChangeType
@ -50,8 +51,8 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : PumpInterface {
override val batteryLevel: Int = 0 override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true) override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun stopBolusDelivering() {} override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true) override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true) override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true) override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true) override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true) override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)

View file

@ -30,13 +30,12 @@ class QuickWizardTest : TestBase() {
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var loopPlugin: LoopPlugin @Mock lateinit var loopPlugin: LoopPlugin
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
private val data1 = "{\"buttonText\":\"Meal\",\"carbs\":36,\"validFrom\":0,\"validTo\":18000," + private val data1 = "{\"buttonText\":\"Meal\",\"carbs\":36,\"validFrom\":0,\"validTo\":18000," +
"\"useBG\":0,\"useCOB\":0,\"useBolusIOB\":0,\"useBasalIOB\":0,\"useTrend\":0,\"useSuperBolus\":0,\"useTemptarget\":0}" "\"useBG\":0,\"useCOB\":0,\"useBolusIOB\":0,\"useBasalIOB\":0,\"useTrend\":0,\"useSuperBolus\":0,\"useTemptarget\":0}"
private val data2 = "{\"buttonText\":\"Lunch\",\"carbs\":18,\"validFrom\":36000,\"validTo\":39600," + private val data2 = "{\"buttonText\":\"Lunch\",\"carbs\":18,\"validFrom\":36000,\"validTo\":39600," +
"\"useBG\":0,\"useCOB\":0,\"useBolusIOB\":1,\"useBasalIOB\":2,\"useTrend\":0,\"useSuperBolus\":0,\"useTemptarget\":0}" "\"useBG\":0,\"useCOB\":0,\"useBolusIOB\":1,\"useBasalIOB\":2,\"useTrend\":0,\"useSuperBolus\":0,\"useTemptarget\":0}"
var array: JSONArray = JSONArray("[$data1,$data2]") private var array: JSONArray = JSONArray("[$data1,$data2]")
val injector = HasAndroidInjector { val injector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -44,9 +43,7 @@ class QuickWizardTest : TestBase() {
it.aapsLogger = aapsLogger it.aapsLogger = aapsLogger
it.sp = sp it.sp = sp
it.profileFunction = profileFunction it.profileFunction = profileFunction
it.treatmentsPlugin = treatmentsPlugin
it.loopPlugin = loopPlugin it.loopPlugin = loopPlugin
it.iobCobCalculatorPlugin = iobCobCalculatorPlugin
} }
} }
} }

View file

@ -25,6 +25,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
@ -61,8 +62,8 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage
@Mock lateinit var context: Context @Mock lateinit var context: Context
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var profiler: Profiler @Mock lateinit var profiler: Profiler
@ -139,16 +140,16 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator)
danaPump = DanaPump(aapsLogger, sp, injector) danaPump = DanaPump(aapsLogger, sp, dateUtil, injector)
hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository)
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel)
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, treatmentsInterface, sp, commandQueue, context, databaseHelper) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync)
danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync)
danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil)
insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil, databaseHelper, pumpSync) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil, databaseHelper, pumpSync)
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider)
openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider)
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), treatmentsInterface, Config()) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), iobCobCalculator, Config(), dateUtil)
val constraintsPluginsList = ArrayList<PluginBase>() val constraintsPluginsList = ArrayList<PluginBase>()
constraintsPluginsList.add(safetyPlugin) constraintsPluginsList.add(safetyPlugin)
constraintsPluginsList.add(objectivesPlugin) constraintsPluginsList.add(objectivesPlugin)

View file

@ -13,7 +13,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.RunningConfiguration import info.nightscout.androidaps.plugins.configBuilder.RunningConfiguration
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.receivers.ReceiverStatusStore
@ -44,10 +43,9 @@ class LoopPluginTest : TestBase() {
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var receiverStatusStore: ReceiverStatusStore @Mock lateinit var receiverStatusStore: ReceiverStatusStore
@Mock lateinit var nsUpload: NSUpload
@Mock lateinit var notificationManager: NotificationManager @Mock lateinit var notificationManager: NotificationManager
@Mock lateinit var repository: AppRepository @Mock lateinit var repository: AppRepository
@Mock lateinit var dateUtil: DateUtil @Mock lateinit var dateUtil: DateUtil
@ -58,7 +56,7 @@ class LoopPluginTest : TestBase() {
val injector = HasAndroidInjector { AndroidInjector { } } val injector = HasAndroidInjector { AndroidInjector { } }
@Before fun prepareMock() { @Before fun prepareMock() {
loopPlugin = LoopPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, Config(), constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, treatmentsPlugin, virtualPumpPlugin, iobCobCalculatorPlugin, receiverStatusStore, fabricPrivacy, nsUpload, dateUtil, repository, runningConfiguration) loopPlugin = LoopPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, Config(), constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, virtualPumpPlugin, iobCobCalculator, receiverStatusStore, fabricPrivacy, dateUtil, repository, runningConfiguration)
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(context.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(notificationManager) `when`(context.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(notificationManager)
} }

View file

@ -76,7 +76,7 @@ class SafetyPluginTest : TestBaseWithProfile() {
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription)
hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository)
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, treatmentsInterface, Config()) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, iobCobCalculator, Config(), dateUtil)
} }
@Test fun pumpDescriptionShouldLimitLoopInvocation() { @Test fun pumpDescriptionShouldLimitLoopInvocation() {

View file

@ -19,7 +19,6 @@ import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo
@ -66,14 +65,12 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var loopPlugin: LoopPlugin @Mock lateinit var loopPlugin: LoopPlugin
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var localProfilePlugin: LocalProfilePlugin @Mock lateinit var localProfilePlugin: LocalProfilePlugin
@Mock lateinit var treatmentService: TreatmentService @Mock lateinit var treatmentService: TreatmentService
@Mock lateinit var otp: OneTimePassword @Mock lateinit var otp: OneTimePassword
@Mock lateinit var xdripCalibrations: XdripCalibrations @Mock lateinit var xdripCalibrations: XdripCalibrations
@Mock lateinit var uel: UserEntryLogger @Mock lateinit var uel: UserEntryLogger
@Mock lateinit var nsUpload: NSUpload
@Mock lateinit var repository: AppRepository @Mock lateinit var repository: AppRepository
var injector: HasAndroidInjector = HasAndroidInjector { var injector: HasAndroidInjector = HasAndroidInjector {
@ -146,13 +143,13 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
callback.result = PumpEnactResult(injector).success(true).isPercent(true).percent(invocation.getArgument(0)).duration(invocation.getArgument(1)) callback.result = PumpEnactResult(injector).success(true).isPercent(true).percent(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.run() callback.run()
null null
}.`when`(commandQueue).tempBasalPercent(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(Callback::class.java)) }.`when`(commandQueue).tempBasalPercent(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(PumpSync.TemporaryBasalType::class.java), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock -> Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(4) val callback = invocation.getArgument<Callback>(4)
callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1)) callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.run() callback.run()
null null
}.`when`(commandQueue).tempBasalAbsolute(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(Callback::class.java)) }.`when`(commandQueue).tempBasalAbsolute(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(PumpSync.TemporaryBasalType::class.java), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock -> Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(2) val callback = invocation.getArgument<Callback>(2)
callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1)) callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
@ -169,7 +166,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
`when`(virtualPumpPlugin.model()).thenReturn(PumpType.GENERIC_AAPS) `when`(virtualPumpPlugin.model()).thenReturn(PumpType.GENERIC_AAPS)
`when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(0)) `when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(0))
`when`(treatmentsInterface.lastCalculationTempBasals).thenReturn(IobTotal(0)) `when`(iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended()).thenReturn(IobTotal(0))
`when`(treatmentsInterface.service).thenReturn(treatmentService) `when`(treatmentsInterface.service).thenReturn(treatmentService)
`when`(activePlugin.activeProfileInterface).thenReturn(localProfilePlugin) `when`(activePlugin.activeProfileInterface).thenReturn(localProfilePlugin)

View file

@ -11,7 +11,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
@ -35,7 +34,6 @@ class IobCobCalculatorPluginTest : TestBase() {
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
@Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin @Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin
@ -52,7 +50,7 @@ class IobCobCalculatorPluginTest : TestBase() {
@Before @Before
fun mock() { fun mock() {
iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository)
} }
@Test @Test

View file

@ -5,11 +5,11 @@ import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -32,7 +32,7 @@ class VirtualPumpPluginUTest : TestBase() {
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var dateUtil: DateUtil @Mock lateinit var dateUtil: DateUtil
@Mock lateinit var pumpSync: PumpSync @Mock lateinit var pumpSync: PumpSync
@ -41,7 +41,7 @@ class VirtualPumpPluginUTest : TestBase() {
@Before @Before
fun prepareMocks() { fun prepareMocks() {
virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, aapsSchedulers, sp, profileFunction, treatmentsPlugin, commandQueue, pumpSync, Config(), dateUtil) virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, aapsSchedulers, sp, profileFunction, iobCobCalculator, commandQueue, pumpSync, Config(), dateUtil)
} }
@Test @Test

View file

@ -48,7 +48,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
} }
} }
} }
/*
private lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin private lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin
private lateinit var sot: TreatmentsPlugin private lateinit var sot: TreatmentsPlugin
@ -59,7 +59,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
`when`(profileFunction.getProfile(ArgumentMatchers.anyLong())).thenReturn(validProfile) `when`(profileFunction.getProfile(ArgumentMatchers.anyLong())).thenReturn(validProfile)
`when`(activePluginProvider.activeInsulin).thenReturn(insulinOrefRapidActingPlugin) `when`(activePluginProvider.activeInsulin).thenReturn(insulinOrefRapidActingPlugin)
sot = TreatmentsPlugin(profileInjector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePluginProvider, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) sot = TreatmentsPlugin(profileInjector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePluginProvider, nsUpload, fabricPrivacy, dateUtil, databaseHelper, repository)
sot.service = treatmentService sot.service = treatmentService
} }
@ -102,4 +102,6 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
val iob110pct = sot.getAbsoluteIOBTempBasals(now) val iob110pct = sot.getAbsoluteIOBTempBasals(now)
Assert.assertEquals(1.1, iob110pct.basaliob / iob100pct.basaliob, 0.0001) Assert.assertEquals(1.1, iob110pct.basaliob / iob100pct.basaliob, 0.0001)
} }
*/
} }

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
@ -175,11 +176,11 @@ class CommandQueueTest : TestBaseWithProfile() {
Assert.assertEquals(0, commandQueue.size()) Assert.assertEquals(0, commandQueue.size())
// add tempbasal // add tempbasal
commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, null) commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, PumpSync.TemporaryBasalType.NORMAL, null)
Assert.assertEquals(1, commandQueue.size()) Assert.assertEquals(1, commandQueue.size())
// add tempbasal percent. it should replace previous TEMPBASAL // add tempbasal percent. it should replace previous TEMPBASAL
commandQueue.tempBasalPercent(0, 30, true, validProfile, null) commandQueue.tempBasalPercent(0, 30, true, validProfile, PumpSync.TemporaryBasalType.NORMAL, null)
Assert.assertEquals(1, commandQueue.size()) Assert.assertEquals(1, commandQueue.size())
// cancel tempbasal it should replace previous TEMPBASAL // cancel tempbasal it should replace previous TEMPBASAL
@ -211,7 +212,7 @@ class CommandQueueTest : TestBaseWithProfile() {
commandQueue.loadEvents(null) commandQueue.loadEvents(null)
Assert.assertEquals(4, commandQueue.size()) Assert.assertEquals(4, commandQueue.size())
commandQueue.clear() commandQueue.clear()
commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, null) commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, PumpSync.TemporaryBasalType.NORMAL, null)
commandQueue.pickup() commandQueue.pickup()
Assert.assertEquals(0, commandQueue.size()) Assert.assertEquals(0, commandQueue.size())
Assert.assertNotNull(commandQueue.performing) Assert.assertNotNull(commandQueue.performing)

View file

@ -12,6 +12,7 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
@ -30,7 +31,6 @@ import org.mockito.Mock
import org.mockito.Mockito import org.mockito.Mockito
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest( @PrepareForTest(
@ -93,7 +93,7 @@ class QueueThreadTest : TestBaseWithProfile() {
@Test @Test
fun commandIsPickedUp() { fun commandIsPickedUp() {
commandQueue.tempBasalAbsolute(2.0, 60, true, validProfile, null) commandQueue.tempBasalAbsolute(2.0, 60, true, validProfile, PumpSync.TemporaryBasalType.NORMAL, null)
sut.run() sut.run()
Assert.assertEquals(0, commandQueue.size()) Assert.assertEquals(0, commandQueue.size())
} }

View file

@ -72,7 +72,7 @@ class BolusWizardTest : TestBase() {
`when`(iobCobCalculator.dataLock).thenReturn(Any()) `when`(iobCobCalculator.dataLock).thenReturn(Any())
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin)
`when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(System.currentTimeMillis())) `when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(System.currentTimeMillis()))
`when`(treatmentsPlugin.lastCalculationTempBasals).thenReturn(IobTotal(System.currentTimeMillis())) `when`(iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended()).thenReturn(IobTotal(System.currentTimeMillis()))
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
val pumpDescription = PumpDescription() val pumpDescription = PumpDescription()
pumpDescription.bolusStep = pumpBolusStep pumpDescription.bolusStep = pumpBolusStep

View file

@ -35,7 +35,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable

View file

@ -23,7 +23,7 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble
import info.nightscout.androidaps.utils.extensions.friendlyDescription import info.nightscout.androidaps.extensions.friendlyDescription
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign

View file

@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerCon
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject import javax.inject.Inject

View file

@ -8,6 +8,7 @@ import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.interfaces.PumpInterface
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -61,8 +62,8 @@ class TestPumpPlugin(pluginDescription: PluginDescription,
override val batteryLevel: Int = 0 override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true) override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun stopBolusDelivering() {} override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true) override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true) override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true) override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true) override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true) override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)

View file

@ -66,6 +66,8 @@ import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.InstanceId; import info.nightscout.androidaps.utils.InstanceId;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -78,12 +80,12 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered";
private final ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private final TreatmentsInterface treatmentsPlugin; private final SP sp;
private final info.nightscout.androidaps.utils.sharedPreferences.SP sp;
private RxBusWrapper rxBus; private RxBusWrapper rxBus;
private final CommandQueueProvider commandQueue; private final CommandQueueProvider commandQueue;
private final Context context; private final Context context;
private final DatabaseHelperInterface databaseHelper; private final DatabaseHelperInterface databaseHelper;
private final PumpSync pumpSync;
private final static PumpDescription pumpDescription = new PumpDescription(); private final static PumpDescription pumpDescription = new PumpDescription();
@ -105,7 +107,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
/** /**
* This is set (in {@link #checkHistory()} whenever a connection to the pump is made and * This is set (in {@link #checkHistory()} whenever a connection to the pump is made and
* indicates if new history records on the pump have been found. This effectively blocks * indicates if new history records on the pump have been found. This effectively blocks
* high temps ({@link #setTempBasalPercent(Integer, Integer)} and boluses * high temps ({@link #setTempBasalPercent(Integer, Integer, PumpSync.TemporaryBasalType)} and boluses
* ({@link #deliverBolus(DetailedBolusInfo)} till the queue is empty and the connection * ({@link #deliverBolus(DetailedBolusInfo)} till the queue is empty and the connection
* is shut down. * is shut down.
* {@link #initializePump()} resets this since on startup the history is allowed to have * {@link #initializePump()} resets this since on startup the history is allowed to have
@ -135,11 +137,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
TreatmentsInterface treatmentsPlugin,
SP sp, SP sp,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
Context context, Context context,
DatabaseHelperInterface databaseHelper DatabaseHelperInterface databaseHelper,
PumpSync pumpSync
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
@ -152,11 +154,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
); );
this.rxBus = rxBus; this.rxBus = rxBus;
this.profileFunction = profileFunction; this.profileFunction = profileFunction;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp; this.sp = sp;
this.commandQueue = commandQueue; this.commandQueue = commandQueue;
this.context = context; this.context = context;
this.databaseHelper = databaseHelper; this.databaseHelper = databaseHelper;
this.pumpSync = pumpSync;
pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_COMBO); pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_COMBO);
} }
@ -480,10 +482,13 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()).success(false).enacted(false) return new PumpEnactResult(getInjector()).success(false).enacted(false)
.bolusDelivered(0d).carbsDelivered(0d) .bolusDelivered(0d).carbsDelivered(0d)
.comment(R.string.invalidinput); .comment(R.string.invalidinput);
} else if (detailedBolusInfo.insulin > 0) { // } else if (detailedBolusInfo.insulin > 0) {
} else {
// bolus needed, ask pump to deliver it // bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo); return deliverBolus(detailedBolusInfo);
} else { }
/* This should not happen anymore
else {
// no bolus required, carb only treatment // no bolus required, carb only treatment
treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false); treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false);
@ -496,6 +501,8 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(R.string.virtualpump_resultok); .comment(R.string.virtualpump_resultok);
} }
*/
} finally { } finally {
rxBus.send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
@ -669,6 +676,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
bolusInfo.setBolusPumpId(bolusInfo.timestamp); bolusInfo.setBolusPumpId(bolusInfo.timestamp);
bolusInfo.insulin = lastPumpBolus.amount; bolusInfo.insulin = lastPumpBolus.amount;
try { try {
/* this should not happen
if (bolusInfo.carbs > 0 && bolusInfo.carbTime != 0) { if (bolusInfo.carbs > 0 && bolusInfo.carbTime != 0) {
// split out a separate carbs record without a pumpId // split out a separate carbs record without a pumpId
DetailedBolusInfo carbInfo = new DetailedBolusInfo(); DetailedBolusInfo carbInfo = new DetailedBolusInfo();
@ -682,7 +690,15 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
bolusInfo.carbTime = 0; bolusInfo.carbTime = 0;
bolusInfo.carbs = 0; bolusInfo.carbs = 0;
} }
treatmentsPlugin.addToHistoryTreatment(bolusInfo, true); */
pumpSync.syncBolusWithPumpId(
calculateFakeBolusDate(lastPumpBolus),
lastPumpBolus.amount,
detailedBolusInfo.getBolusType(),
bolusInfo.timestamp,
PumpType.ACCU_CHEK_COMBO,
serialNumber()
);
} catch (Exception e) { } catch (Exception e) {
getAapsLogger().error("Adding treatment record failed", e); getAapsLogger().error("Adding treatment record failed", e);
if (bolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB) { if (bolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB) {
@ -712,7 +728,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
* the new value (and thus still has the old duration of e.g. 1 min) expires?) * the new value (and thus still has the old duration of e.g. 1 min) expires?)
*/ */
@NonNull @Override @NonNull @Override
public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NonNull Profile profile, boolean force, PumpSync.TemporaryBasalType tbrType) { public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NonNull Profile profile, boolean force, @NonNull PumpSync.TemporaryBasalType tbrType) {
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min."); getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10); int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10);
@ -720,7 +736,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
getAapsLogger().debug(LTag.PUMP, "Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%"); getAapsLogger().debug(LTag.PUMP, "Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
} }
return setTempBasalPercent(roundedPercentage, durationInMinutes); return setTempBasalPercent(roundedPercentage, durationInMinutes, tbrType);
} }
/** /**
@ -730,11 +746,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
* is or isn't running at the moment * is or isn't running at the moment
*/ */
@NonNull @Override @NonNull @Override
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean forceNew, PumpSync.TemporaryBasalType tbrType) { public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean forceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
return setTempBasalPercent(percent, durationInMinutes); return setTempBasalPercent(percent, durationInMinutes, tbrType);
} }
private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) { private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes, @NonNull PumpSync.TemporaryBasalType tbrType) {
getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min"); getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
if (pumpHistoryChanged && percent > 110) { if (pumpHistoryChanged && percent > 110) {
@ -770,12 +786,16 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
PumpState state = commandResult.state; PumpState state = commandResult.state;
if (state.tbrActive && state.tbrPercent == adjustedPercent if (state.tbrActive && state.tbrPercent == adjustedPercent
&& (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) { && (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) {
TemporaryBasal tempStart = new TemporaryBasal(getInjector()) pumpSync.syncTemporaryBasalWithPumpId(
.date(state.timestamp) state.timestamp,
.duration(state.tbrRemainingDuration) state.tbrPercent,
.percent(state.tbrPercent) T.mins(state.tbrRemainingDuration).msecs(),
.source(Source.USER); false,
treatmentsPlugin.addToHistoryTempBasal(tempStart); tbrType,
state.timestamp, // no pumpId available ????
PumpType.ACCU_CHEK_COMBO,
serialNumber()
);
rxBus.send(new EventComboPumpUpdateGUI()); rxBus.send(new EventComboPumpUpdateGUI());
} }
@ -801,7 +821,9 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
@NonNull @Override @NonNull @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) { public PumpEnactResult cancelTempBasal(boolean enforceNew) {
getAapsLogger().debug(LTag.PUMP, "cancelTempBasal called"); getAapsLogger().debug(LTag.PUMP, "cancelTempBasal called");
final TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); //final TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistoryIncludingConvertedExtended(System.currentTimeMillis());
PumpSync.PumpState pumpSate = pumpSync.expectedPumpState();
final PumpSync.PumpState.TemporaryBasal activeTemp = pumpSate.getTemporaryBasal();
if (enforceNew) { if (enforceNew) {
CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState);
if (!stateResult.success) { if (!stateResult.success) {
@ -816,32 +838,33 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return new PumpEnactResult(getInjector()).success(false).enacted(false); return new PumpEnactResult(getInjector()).success(false).enacted(false);
} }
if (!cancelResult.state.tbrActive) { if (!cancelResult.state.tbrActive) {
TemporaryBasal tempBasal = new TemporaryBasal(getInjector()) pumpSync.syncStopTemporaryBasalWithPumpId(
.date(cancelResult.state.timestamp) cancelResult.state.timestamp,
.duration(0) cancelResult.state.timestamp,
.source(Source.USER); PumpType.ACCU_CHEK_COMBO,
treatmentsPlugin.addToHistoryTempBasal(tempBasal); serialNumber()
);
return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true); return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true);
} else { } else {
return new PumpEnactResult(getInjector()).success(false).enacted(false); return new PumpEnactResult(getInjector()).success(false).enacted(false);
} }
} else if (activeTemp == null) { } else if (activeTemp == null) {
return new PumpEnactResult(getInjector()).success(true).enacted(false); return new PumpEnactResult(getInjector()).success(true).enacted(false);
} else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) && activeTemp.getPlannedRemainingMinutes() <= 15) { } else if ((activeTemp.getRate() >= 90 && activeTemp.getRate() <= 110) && info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) <= 15) {
// Let fake neutral temp keep run (see below) // Let fake neutral temp keep run (see below)
// Note that since this runs on the queue a connection is opened regardless, but this // Note that since this runs on the queue a connection is opened regardless, but this
// case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR). // case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR).
getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.getRate() + "% and running for another " + info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) + " mins.");
return new PumpEnactResult(getInjector()).success(true).enacted(true) return new PumpEnactResult(getInjector()).success(true).enacted(true)
.comment("cancelTempBasal skipping changing tbr since it already is at " .comment("cancelTempBasal skipping changing tbr since it already is at "
+ activeTemp.percentRate + "% and running for another " + activeTemp.getRate() + "% and running for another "
+ activeTemp.getPlannedRemainingMinutes() + " mins."); + info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) + " mins.");
} else { } else {
// Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on // Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on
// on whether the TBR we're cancelling is above or below 100%. // on whether the TBR we're cancelling is above or below 100%.
final int percentage = (activeTemp.percentRate > 100) ? 110 : 90; final int percentage = (activeTemp.getRate() > 100) ? 110 : 90;
getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: changing TBR to " + percentage + "% for 15 mins."); getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: changing TBR to " + percentage + "% for 15 mins.");
return setTempBasalPercent(percentage, 15); return setTempBasalPercent(percentage, 15, PumpSync.TemporaryBasalType.NORMAL);
} }
} }
@ -961,15 +984,19 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
return checkHistory(); return checkHistory();
} else { } else {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now); PumpSync.PumpState.TemporaryBasal aapsTbr = pumpSync.expectedPumpState().getTemporaryBasal();
if (aapsTbr == null || aapsTbr.percentRate != 0) { if (aapsTbr == null || aapsTbr.getRate() != 0) {
getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended"); getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended");
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector()) pumpSync.syncTemporaryBasalWithPumpId(
.date(now) now,
.percent(0) 0.0,
.duration(15) T.mins(15).msecs(),
.source(Source.USER); false,
treatmentsPlugin.addToHistoryTempBasal(newTempBasal); PumpSync.TemporaryBasalType.PUMP_SUSPEND,
now, // no pumpId available ????
PumpType.ACCU_CHEK_COMBO,
serialNumber()
);
} }
} }
@ -1087,38 +1114,49 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private void checkAndResolveTbrMismatch(PumpState state) { private void checkAndResolveTbrMismatch(PumpState state) {
// compare with: info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusTempBasal.updateTempBasalInDB() // compare with: info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusTempBasal.updateTempBasalInDB()
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now); //TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistoryIncludingConvertedExtended(now);
PumpSync.PumpState.TemporaryBasal aapsTbr = pumpSync.expectedPumpState().getTemporaryBasal();
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) { if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) {
getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR"); getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR");
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector()) pumpSync.syncTemporaryBasalWithPumpId(
.date(now) now,
.percent(state.tbrPercent) state.tbrPercent,
.duration(state.tbrRemainingDuration) T.mins(state.tbrRemainingDuration).msecs(),
.source(Source.USER); false,
treatmentsPlugin.addToHistoryTempBasal(newTempBasal); PumpSync.TemporaryBasalType.NORMAL,
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) { now, // no pumpId available ????
PumpType.ACCU_CHEK_COMBO,
serialNumber()
);
} else if (aapsTbr != null && info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes(aapsTbr) > 2 && !state.tbrActive) {
getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active"); getAapsLogger().debug(LTag.PUMP, "Ending AAPS-TBR since pump has no TBR active");
TemporaryBasal tempStop = new TemporaryBasal(getInjector()) pumpSync.syncStopTemporaryBasalWithPumpId(
.date(now) now,
.duration(0) now,
.source(Source.USER); PumpType.ACCU_CHEK_COMBO,
treatmentsPlugin.addToHistoryTempBasal(tempStop); serialNumber()
);
} else if (aapsTbr != null && state.tbrActive } else if (aapsTbr != null && state.tbrActive
&& (aapsTbr.percentRate != state.tbrPercent || && (aapsTbr.getRate() != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) { Math.abs(info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes(aapsTbr) - state.tbrRemainingDuration) > 2)) {
getAapsLogger().debug(LTag.PUMP, "AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR"); getAapsLogger().debug(LTag.PUMP, "AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR");
TemporaryBasal tempStop = new TemporaryBasal(getInjector()) pumpSync.syncStopTemporaryBasalWithPumpId(
.date(now - 1000) now - 1000,
.duration(0) now - 1000,
.source(Source.USER); PumpType.ACCU_CHEK_COMBO,
treatmentsPlugin.addToHistoryTempBasal(tempStop); serialNumber()
);
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector()) pumpSync.syncTemporaryBasalWithPumpId(
.date(now) now,
.percent(state.tbrPercent) state.tbrPercent,
.duration(state.tbrRemainingDuration) T.mins(state.tbrRemainingDuration).msecs(),
.source(Source.USER); false,
treatmentsPlugin.addToHistoryTempBasal(newTempBasal); PumpSync.TemporaryBasalType.NORMAL,
now, // no pumpId available ????
PumpType.ACCU_CHEK_COMBO,
serialNumber()
);
} }
} }
@ -1151,14 +1189,14 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
private boolean updateDbFromPumpHistory(@NonNull PumpHistory history) { private boolean updateDbFromPumpHistory(@NonNull PumpHistory history) {
boolean updated = false; boolean updated = false;
for (Bolus pumpBolus : history.bolusHistory) { for (Bolus pumpBolus : history.bolusHistory) {
DetailedBolusInfo dbi = new DetailedBolusInfo(); if (pumpSync.syncBolusWithPumpId(
dbi.setBolusTimestamp(calculateFakeBolusDate(pumpBolus)); calculateFakeBolusDate(pumpBolus),
dbi.setPumpType(PumpType.ACCU_CHEK_COMBO); pumpBolus.amount,
dbi.setPumpSerial(serialNumber()); DetailedBolusInfo.BolusType.NORMAL,
dbi.setBolusPumpId(dbi.timestamp); System.currentTimeMillis(),
dbi.insulin = pumpBolus.amount; PumpType.ACCU_CHEK_COMBO,
dbi.setEventType(DetailedBolusInfo.EventType.CORRECTION_BOLUS); serialNumber()
if (treatmentsPlugin.addToHistoryTreatment(dbi, true)) { )) {
updated = true; updated = true;
} }
} }

View file

@ -28,7 +28,7 @@ class ComboPluginTest : TestBase() {
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var treatmentsPlugin: TreatmentsInterface @Mock lateinit var pumpSync: PumpSync
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var context: Context @Mock lateinit var context: Context
@Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var databaseHelper: DatabaseHelperInterface
@ -47,7 +47,7 @@ class ComboPluginTest : TestBase() {
fun prepareMocks() { fun prepareMocks() {
`when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") `when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump")
`when`(resourceHelper.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") `when`(resourceHelper.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump")
comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(aapsSchedulers), resourceHelper, profileFunction, treatmentsPlugin, sp, commandQueue, context, databaseHelper) comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(aapsSchedulers), resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync)
} }
@Test @Test

View file

@ -72,7 +72,7 @@ public class Constants {
public static final int MIN_WATCHDOG_INTERVAL_IN_SECONDS = 12 * 60; public static final int MIN_WATCHDOG_INTERVAL_IN_SECONDS = 12 * 60;
//SMS Communicator //SMS Communicator
public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); public static final long SMS_CONFIRM_TIMEOUT = T.mins(5L).msecs();
//Storage [MB] //Storage [MB]
public static final long MINIMUM_FREE_SPACE = 200; public static final long MINIMUM_FREE_SPACE = 200;

Some files were not shown because too many files have changed in this diff Show more