ExtendedBolus, TemporaryBasal -> room, DanaRS working
This commit is contained in:
parent
e26e023ebf
commit
2463f8fc47
|
@ -23,7 +23,6 @@ import info.nightscout.androidaps.logging.LTag
|
|||
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
|
||||
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
|
||||
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.ChargingStateReceiver
|
||||
import info.nightscout.androidaps.receivers.KeepAliveReceiver.KeepAliveManager
|
||||
|
@ -47,7 +46,6 @@ class MainApp : DaggerApplication() {
|
|||
@Inject lateinit var activityMonitor: ActivityMonitor
|
||||
@Inject lateinit var versionCheckersUtils: VersionCheckerUtils
|
||||
@Inject lateinit var sp: SP
|
||||
@Inject lateinit var nsUpload: NSUpload
|
||||
@Inject lateinit var config: Config
|
||||
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
|
||||
@Inject lateinit var keepAliveManager: KeepAliveManager
|
||||
|
|
|
@ -24,7 +24,7 @@ import info.nightscout.androidaps.utils.DateUtil
|
|||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.utils.ToastUtils
|
||||
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 java.text.DecimalFormat
|
||||
import javax.inject.Inject
|
||||
|
|
|
@ -80,12 +80,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
|
||||
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 ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
|
||||
|
||||
|
@ -198,8 +192,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
aapsLogger.error("Unhandled exception", e);
|
||||
}
|
||||
virtualPumpPlugin.setFakingStatus(true);
|
||||
scheduleTemporaryBasalChange();
|
||||
scheduleExtendedBolusChange();
|
||||
scheduleProfileSwitchChange();
|
||||
new java.util.Timer().schedule(
|
||||
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() {
|
||||
try {
|
||||
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
|
||||
|
@ -507,7 +476,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
openHumansUploader.enqueueTemporaryBasal(old);
|
||||
|
||||
updateEarliestDataChange(tempBasal.date);
|
||||
scheduleTemporaryBasalChange();
|
||||
// scheduleTemporaryBasalChange();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
@ -516,7 +485,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
openHumansUploader.enqueueTemporaryBasal(tempBasal);
|
||||
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
|
||||
updateEarliestDataChange(tempBasal.date);
|
||||
scheduleTemporaryBasalChange();
|
||||
// scheduleTemporaryBasalChange();
|
||||
return true;
|
||||
}
|
||||
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());
|
||||
updateEarliestDataChange(oldDate);
|
||||
updateEarliestDataChange(old.date);
|
||||
scheduleTemporaryBasalChange();
|
||||
// scheduleTemporaryBasalChange();
|
||||
return true;
|
||||
}
|
||||
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());
|
||||
updateEarliestDataChange(oldDate);
|
||||
updateEarliestDataChange(old.date);
|
||||
scheduleTemporaryBasalChange();
|
||||
// scheduleTemporaryBasalChange();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -567,7 +536,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
openHumansUploader.enqueueTemporaryBasal(tempBasal);
|
||||
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
|
||||
updateEarliestDataChange(tempBasal.date);
|
||||
scheduleTemporaryBasalChange();
|
||||
// scheduleTemporaryBasalChange();
|
||||
return true;
|
||||
}
|
||||
if (tempBasal.source == Source.USER) {
|
||||
|
@ -575,7 +544,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
openHumansUploader.enqueueTemporaryBasal(tempBasal);
|
||||
aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
|
||||
updateEarliestDataChange(tempBasal.date);
|
||||
scheduleTemporaryBasalChange();
|
||||
// scheduleTemporaryBasalChange();
|
||||
return true;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
|
@ -592,16 +561,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
} catch (SQLException e) {
|
||||
aapsLogger.error("Unhandled exception", e);
|
||||
}
|
||||
scheduleTemporaryBasalChange();
|
||||
}
|
||||
|
||||
public List<TemporaryBasal> getAllTemporaryBasals() {
|
||||
try {
|
||||
return getDaoTemporaryBasal().queryForAll();
|
||||
} catch (SQLException e) {
|
||||
aapsLogger.error("Unhandled exception", e);
|
||||
}
|
||||
return Collections.emptyList();
|
||||
// scheduleTemporaryBasalChange();
|
||||
}
|
||||
|
||||
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
|
||||
|
@ -620,44 +580,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
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",
|
||||
|
@ -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) {
|
||||
try {
|
||||
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
|
||||
|
@ -785,109 +620,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
|
||||
// ------------ 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) {
|
||||
try {
|
||||
return getDaoExtendedBolus().queryBuilder()
|
||||
|
@ -907,69 +639,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
} catch (SQLException e) {
|
||||
aapsLogger.error("Unhandled exception", e);
|
||||
}
|
||||
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;
|
||||
// scheduleExtendedBolusChange();
|
||||
}
|
||||
|
||||
/*
|
||||
|
@ -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 ---------------
|
||||
|
||||
public List<ProfileSwitch> getProfileSwitchData(long from, boolean ascending) {
|
||||
|
|
|
@ -16,6 +16,7 @@ import javax.inject.Singleton;
|
|||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
|
||||
|
||||
@Deprecated
|
||||
@Singleton
|
||||
public class DatabaseHelperProvider implements DatabaseHelperInterface {
|
||||
|
||||
|
@ -82,6 +83,7 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
|
|||
return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@NonNull @Override public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
|
||||
return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending);
|
||||
}
|
||||
|
@ -134,42 +136,14 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
|
|||
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) {
|
||||
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) {
|
||||
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) {
|
||||
MainApp.Companion.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson);
|
||||
}
|
||||
|
@ -194,10 +168,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
|
|||
return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(mills, ascending);
|
||||
}
|
||||
|
||||
@NonNull @Override public List<ExtendedBolus> getAllExtendedBoluses() {
|
||||
return MainApp.Companion.getDbHelper().getAllExtendedBoluses();
|
||||
}
|
||||
|
||||
@NonNull @Override public List<ProfileSwitch> getAllProfileSwitches() {
|
||||
return MainApp.Companion.getDbHelper().getAllProfileSwitches();
|
||||
}
|
||||
|
@ -206,10 +176,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
|
|||
return MainApp.Companion.getDbHelper().getAllTDDs();
|
||||
}
|
||||
|
||||
@NonNull @Override public List<TemporaryBasal> getAllTemporaryBasals() {
|
||||
return MainApp.Companion.getDbHelper().getAllTemporaryBasals();
|
||||
}
|
||||
|
||||
@NonNull @Override public List<OHQueueItem> getAllOHQueueItems(long maxEntries) {
|
||||
return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries);
|
||||
}
|
||||
|
|
|
@ -31,7 +31,7 @@ import info.nightscout.androidaps.queue.Callback
|
|||
import info.nightscout.androidaps.queue.CommandQueue
|
||||
import info.nightscout.androidaps.utils.*
|
||||
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 io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
|
|
|
@ -28,7 +28,7 @@ import info.nightscout.androidaps.utils.HtmlHelper
|
|||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.utils.Translator
|
||||
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 io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
|
|
|
@ -19,7 +19,7 @@ import info.nightscout.androidaps.queue.Callback
|
|||
import info.nightscout.androidaps.utils.HtmlHelper
|
||||
import info.nightscout.androidaps.utils.SafeParse
|
||||
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 java.text.DecimalFormat
|
||||
import java.util.*
|
||||
|
|
|
@ -27,7 +27,7 @@ import info.nightscout.androidaps.utils.DecimalFormatter
|
|||
import info.nightscout.androidaps.utils.HtmlHelper
|
||||
import info.nightscout.androidaps.utils.SafeParse
|
||||
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 io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
|
|
|
@ -28,13 +28,12 @@ import info.nightscout.androidaps.interfaces.ProfileFunction
|
|||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.logging.UserEntryLogger
|
||||
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.utils.*
|
||||
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.toVisibility
|
||||
import info.nightscout.androidaps.extensions.toVisibility
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
|
@ -57,7 +56,6 @@ class InsulinDialog : DialogFragmentWithDate() {
|
|||
@Inject lateinit var repository: AppRepository
|
||||
@Inject lateinit var config: Config
|
||||
@Inject lateinit var uel: UserEntryLogger
|
||||
@Inject lateinit var nsUpload: NSUpload
|
||||
|
||||
companion object {
|
||||
|
||||
|
|
|
@ -27,7 +27,7 @@ import info.nightscout.androidaps.queue.Callback
|
|||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.ToastUtils
|
||||
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.sharedPreferences.SP
|
||||
import javax.inject.Inject
|
||||
|
|
|
@ -17,7 +17,7 @@ import info.nightscout.androidaps.queue.Callback
|
|||
import info.nightscout.androidaps.utils.HtmlHelper
|
||||
import info.nightscout.androidaps.utils.SafeParse
|
||||
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 java.text.DecimalFormat
|
||||
import java.util.*
|
||||
|
|
|
@ -23,14 +23,13 @@ import info.nightscout.androidaps.interfaces.Constraint
|
|||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.logging.UserEntryLogger
|
||||
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.utils.DecimalFormatter
|
||||
import info.nightscout.androidaps.utils.HtmlHelper
|
||||
import info.nightscout.androidaps.utils.SafeParse
|
||||
import info.nightscout.androidaps.utils.ToastUtils
|
||||
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 io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
|
@ -48,7 +47,6 @@ class TreatmentDialog : DialogFragmentWithDate() {
|
|||
@Inject lateinit var ctx: Context
|
||||
@Inject lateinit var config: Config
|
||||
@Inject lateinit var uel: UserEntryLogger
|
||||
@Inject lateinit var nsUpload: NSUpload
|
||||
@Inject lateinit var repository: AppRepository
|
||||
|
||||
private val disposable = CompositeDisposable()
|
||||
|
|
|
@ -27,7 +27,6 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
|||
import info.nightscout.androidaps.interfaces.Constraint
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.interfaces.TreatmentsInterface
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.logging.LTag
|
||||
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.SafeParse
|
||||
import info.nightscout.androidaps.utils.ToastUtils
|
||||
import info.nightscout.androidaps.utils.extensions.toVisibility
|
||||
import info.nightscout.androidaps.utils.extensions.valueToUnits
|
||||
import info.nightscout.androidaps.extensions.toVisibility
|
||||
import info.nightscout.androidaps.extensions.valueToUnits
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -64,7 +63,6 @@ class WizardDialog : DaggerDialogFragment() {
|
|||
@Inject lateinit var activePlugin: ActivePluginProvider
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var repository: AppRepository
|
||||
@Inject lateinit var treatmentsPlugin: TreatmentsInterface
|
||||
@Inject lateinit var dateUtil: DateUtil
|
||||
|
||||
private var wizard: BolusWizard? = null
|
||||
|
@ -274,7 +272,7 @@ class WizardDialog : DaggerDialogFragment() {
|
|||
|
||||
// IOB calculation
|
||||
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.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -basalIob.basaliob)
|
||||
|
|
|
@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.DefaultValueHelper
|
|||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.T
|
||||
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.sharedPreferences.SP
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
|
|
@ -28,7 +28,6 @@ class IobCobCalculatorPluginHistory @Inject constructor(
|
|||
resourceHelper: ResourceHelper,
|
||||
profileFunction: ProfileFunction,
|
||||
activePlugin: ActivePluginProvider,
|
||||
treatmentsPluginHistory: TreatmentsPluginHistory,
|
||||
sensitivityOref1Plugin: SensitivityOref1Plugin,
|
||||
sensitivityAAPSPlugin: SensitivityAAPSPlugin,
|
||||
sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin,
|
||||
|
@ -36,7 +35,7 @@ class IobCobCalculatorPluginHistory @Inject constructor(
|
|||
dateUtil: DateUtil,
|
||||
repository: AppRepository
|
||||
) : 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
|
||||
}
|
||||
|
|
|
@ -6,7 +6,6 @@ import info.nightscout.androidaps.database.AppRepository
|
|||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.interfaces.UploadQueueInterface
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
|
||||
|
@ -34,10 +33,9 @@ class TreatmentsPluginHistory @Inject constructor(
|
|||
nsUpload: NSUpload,
|
||||
fabricPrivacy: FabricPrivacy,
|
||||
dateUtil: DateUtil,
|
||||
uploadQueue: UploadQueueInterface,
|
||||
databaseHelper: DatabaseHelperInterface,
|
||||
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 {
|
||||
onStart()
|
||||
|
|
|
@ -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.wear.events.EventWearConfirmAction
|
||||
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.treatments.TreatmentsPlugin
|
||||
import info.nightscout.androidaps.queue.Callback
|
||||
import info.nightscout.androidaps.queue.commands.Command
|
||||
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.HardLimits
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -72,9 +73,8 @@ open class LoopPlugin @Inject constructor(
|
|||
private val context: Context,
|
||||
private val commandQueue: CommandQueueProvider,
|
||||
private val activePlugin: ActivePluginProvider,
|
||||
private val treatmentsPlugin: TreatmentsPlugin,
|
||||
private val virtualPumpPlugin: VirtualPumpPlugin,
|
||||
private val iobCobCalculatorPlugin: IobCobCalculatorPlugin,
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
private val receiverStatusStore: ReceiverStatusStore,
|
||||
private val fabricPrivacy: FabricPrivacy,
|
||||
private val dateUtil: DateUtil,
|
||||
|
@ -119,7 +119,7 @@ open class LoopPlugin @Inject constructor(
|
|||
.subscribe({ event: EventAutosensCalculationFinished ->
|
||||
// Autosens calculation not triggered by a new BG
|
||||
if (event.cause !is EventNewBG) return@subscribe
|
||||
val glucoseValue = iobCobCalculatorPlugin.actualBg() ?: return@subscribe
|
||||
val glucoseValue = iobCobCalculator.actualBg() ?: return@subscribe
|
||||
// BG outdated
|
||||
// already looped with that value
|
||||
if (glucoseValue.timestamp <= lastBgTriggeredRun) return@subscribe
|
||||
|
@ -316,7 +316,7 @@ open class LoopPlugin @Inject constructor(
|
|||
lastRun.lastTBRRequest = 0
|
||||
lastRun.lastSMBEnact = 0
|
||||
lastRun.lastSMBRequest = 0
|
||||
buildDeviceStatus(dateUtil, this, iobCobCalculatorPlugin, profileFunction,
|
||||
buildDeviceStatus(dateUtil, this, iobCobCalculator, profileFunction,
|
||||
activePlugin.activePump, receiverStatusStore, runningConfiguration,
|
||||
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {
|
||||
repository.insert(it)
|
||||
|
@ -504,7 +504,7 @@ open class LoopPlugin @Inject constructor(
|
|||
lastRun.lastTBRRequest = lastRun.lastAPSRun
|
||||
lastRun.lastTBREnact = DateUtil.now()
|
||||
lastRun.lastOpenModeAccept = DateUtil.now()
|
||||
buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculatorPlugin, profileFunction,
|
||||
buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculator, profileFunction,
|
||||
activePlugin.activePump, receiverStatusStore, runningConfiguration,
|
||||
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {
|
||||
repository.insert(it)
|
||||
|
@ -541,7 +541,7 @@ open class LoopPlugin @Inject constructor(
|
|||
}
|
||||
aapsLogger.debug(LTag.APS, "applyAPSRequest: $request")
|
||||
val now = System.currentTimeMillis()
|
||||
val activeTemp = treatmentsPlugin.getTempBasalFromHistory(now)
|
||||
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
|
||||
if (request.usePercent && allowPercentage()) {
|
||||
if (request.percent == 100 && request.duration == 0) {
|
||||
if (activeTemp != null) {
|
||||
|
@ -552,7 +552,7 @@ open class LoopPlugin @Inject constructor(
|
|||
callback?.result(PumpEnactResult(injector).percent(request.percent).duration(0)
|
||||
.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")
|
||||
callback?.result(PumpEnactResult(injector).percent(request.percent)
|
||||
.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)
|
||||
.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")
|
||||
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)
|
||||
.comment(R.string.let_temp_basal_run))?.run()
|
||||
} 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() {
|
||||
override fun run() {
|
||||
if (!result.success) {
|
||||
|
|
|
@ -6,6 +6,7 @@ import info.nightscout.androidaps.R
|
|||
import info.nightscout.androidaps.data.IobTotal
|
||||
import info.nightscout.androidaps.data.MealData
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.iob.iobCobCalculator.GlucoseStatus
|
||||
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 org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
|
@ -37,7 +40,7 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader
|
|||
@Inject lateinit var constraintChecker: ConstraintChecker
|
||||
@Inject lateinit var sp: SP
|
||||
@Inject lateinit var profileFunction: ProfileFunction
|
||||
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var openHumansUploader: OpenHumansUploader
|
||||
|
||||
private val mScriptReader: ScriptReader
|
||||
|
@ -183,17 +186,14 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader
|
|||
this.profile.put("out_units", "mmol/L")
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
val tb = treatmentsPlugin.getTempBasalFromHistory(now)
|
||||
val tb = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
|
||||
currentTemp = JSONObject()
|
||||
currentTemp.put("temp", "absolute")
|
||||
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
|
||||
val tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis())
|
||||
if (tempBasal != null) {
|
||||
currentTemp.put("minutesrunning", tempBasal.realDuration)
|
||||
}
|
||||
if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now))
|
||||
|
||||
iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray)
|
||||
this.glucoseStatus = JSONObject()
|
||||
this.glucoseStatus.put("glucose", glucoseStatus.glucose)
|
||||
|
|
|
@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
|
|||
import info.nightscout.androidaps.utils.HardLimits
|
||||
import info.nightscout.androidaps.utils.Profiler
|
||||
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 org.json.JSONException
|
||||
import javax.inject.Inject
|
||||
|
@ -37,7 +37,6 @@ open class OpenAPSAMAPlugin @Inject constructor(
|
|||
private val profileFunction: ProfileFunction,
|
||||
private val context: Context,
|
||||
private val activePlugin: ActivePluginProvider,
|
||||
private val treatmentsPlugin: TreatmentsInterface,
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
private val hardLimits: HardLimits,
|
||||
private val profiler: Profiler,
|
||||
|
@ -161,7 +160,7 @@ open class OpenAPSAMAPlugin @Inject constructor(
|
|||
lastAPSResult = null
|
||||
lastAPSRun = 0
|
||||
} 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]
|
||||
val now = System.currentTimeMillis()
|
||||
determineBasalResultAMA.json?.put("timestamp", DateUtil.toISOString(now))
|
||||
|
|
|
@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.IobTotal
|
|||
import info.nightscout.androidaps.data.MealData
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.iob.iobCobCalculator.GlucoseStatus
|
||||
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.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.sharedPreferences.SP
|
||||
import org.json.JSONArray
|
||||
|
@ -37,7 +40,7 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader:
|
|||
@Inject lateinit var sp: SP
|
||||
@Inject lateinit var resourceHelper: ResourceHelper
|
||||
@Inject lateinit var profileFunction: ProfileFunction
|
||||
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var activePluginProvider: ActivePluginProvider
|
||||
@Inject lateinit var openHumansUploader: OpenHumansUploader
|
||||
|
||||
|
@ -227,16 +230,13 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader:
|
|||
this.profile.put("out_units", "mmol/L")
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
val tb = treatmentsPlugin.getTempBasalFromHistory(now)
|
||||
val tb = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
|
||||
currentTemp.put("temp", "absolute")
|
||||
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
|
||||
val tempBasal = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis())
|
||||
if (tempBasal != null) {
|
||||
currentTemp.put("minutesrunning", tempBasal.realDuration)
|
||||
}
|
||||
if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now))
|
||||
|
||||
iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray)
|
||||
mGlucoseStatus.put("glucose", glucoseStatus.glucose)
|
||||
mGlucoseStatus.put("noise", glucoseStatus.noise)
|
||||
|
|
|
@ -22,7 +22,7 @@ import info.nightscout.androidaps.utils.DateUtil
|
|||
import info.nightscout.androidaps.utils.HardLimits
|
||||
import info.nightscout.androidaps.utils.Profiler
|
||||
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.sharedPreferences.SP
|
||||
import javax.inject.Inject
|
||||
|
@ -38,7 +38,6 @@ open class OpenAPSSMBPlugin @Inject constructor(
|
|||
private val profileFunction: ProfileFunction,
|
||||
private val context: Context,
|
||||
private val activePlugin: ActivePluginProvider,
|
||||
private val treatmentsPlugin: TreatmentsInterface,
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
private val hardLimits: HardLimits,
|
||||
private val profiler: Profiler,
|
||||
|
@ -188,7 +187,7 @@ open class OpenAPSSMBPlugin @Inject constructor(
|
|||
} else {
|
||||
// TODO still needed with oref1?
|
||||
// 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.json?.put("timestamp", DateUtil.toISOString(now))
|
||||
determineBasalResultSMB.inputConstraints = inputConstraints
|
||||
|
|
|
@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
|||
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
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.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
|
|
|
@ -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.notifications.Notification
|
||||
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.DecimalFormatter
|
||||
import info.nightscout.androidaps.utils.HardLimits
|
||||
import info.nightscout.androidaps.utils.Round
|
||||
|
@ -37,8 +38,9 @@ class SafetyPlugin @Inject constructor(
|
|||
private val activePlugin: ActivePluginProvider,
|
||||
private val hardLimits: HardLimits,
|
||||
private val buildHelper: BuildHelper,
|
||||
private val treatmentsPlugin: TreatmentsInterface,
|
||||
private val config: Config
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
private val config: Config,
|
||||
private val dateUtil: DateUtil
|
||||
) : PluginBase(PluginDescription()
|
||||
.mainType(PluginType.CONSTRAINTS)
|
||||
.neverVisible(true)
|
||||
|
@ -68,7 +70,7 @@ class SafetyPlugin @Inject constructor(
|
|||
value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this
|
||||
}
|
||||
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
|
||||
}
|
||||
return value
|
||||
|
|
|
@ -16,12 +16,15 @@ import info.nightscout.androidaps.Constants
|
|||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.activities.ErrorHelperActivity
|
||||
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.dialogs.*
|
||||
import info.nightscout.androidaps.events.*
|
||||
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity
|
||||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.CommandQueueProvider
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.queue.Callback
|
||||
import info.nightscout.androidaps.skins.SkinProvider
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
|
||||
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.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
|
@ -52,18 +58,21 @@ class ActionsFragment : DaggerFragment() {
|
|||
@Inject lateinit var aapsSchedulers: AapsSchedulers
|
||||
@Inject lateinit var rxBus: RxBusWrapper
|
||||
@Inject lateinit var sp: SP
|
||||
@Inject lateinit var dateUtil: DateUtil
|
||||
@Inject lateinit var profileFunction: ProfileFunction
|
||||
@Inject lateinit var ctx: Context
|
||||
@Inject lateinit var resourceHelper: ResourceHelper
|
||||
@Inject lateinit var statusLightHandler: StatusLightHandler
|
||||
@Inject lateinit var fabricPrivacy: FabricPrivacy
|
||||
@Inject lateinit var activePlugin: ActivePluginProvider
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var commandQueue: CommandQueueProvider
|
||||
@Inject lateinit var buildHelper: BuildHelper
|
||||
@Inject lateinit var protectionCheck: ProtectionCheck
|
||||
@Inject lateinit var skinProvider: SkinProvider
|
||||
@Inject lateinit var config: Config
|
||||
@Inject lateinit var uel: UserEntryLogger
|
||||
@Inject lateinit var repository: AppRepository
|
||||
|
||||
private var disposable: CompositeDisposable = CompositeDisposable()
|
||||
|
||||
|
@ -154,7 +163,7 @@ class ActionsFragment : DaggerFragment() {
|
|||
}
|
||||
}
|
||||
extendedBolusCancel?.setOnClickListener {
|
||||
if (activePlugin.activeTreatments.isInHistoryExtendedBolusInProgress) {
|
||||
if (iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) {
|
||||
uel.log(Action.CANCEL_EXTENDED_BOLUS)
|
||||
commandQueue.cancelExtended(object : Callback() {
|
||||
override fun run() {
|
||||
|
@ -169,7 +178,7 @@ class ActionsFragment : DaggerFragment() {
|
|||
TempBasalDialog().show(childFragmentManager, "Actions")
|
||||
}
|
||||
cancelTempBasal?.setOnClickListener {
|
||||
if (activePlugin.activeTreatments.isTempBasalInProgress) {
|
||||
if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) != null) {
|
||||
uel.log(Action.CANCEL_TEMP_BASAL)
|
||||
commandQueue.cancelTempBasal(true, object : Callback() {
|
||||
override fun run() {
|
||||
|
@ -264,12 +273,12 @@ class ActionsFragment : DaggerFragment() {
|
|||
extendedBolus?.visibility = View.GONE
|
||||
extendedBolusCancel?.visibility = View.GONE
|
||||
} else {
|
||||
val activeExtendedBolus = activePlugin.activeTreatments.getExtendedBolusFromHistory(System.currentTimeMillis())
|
||||
if (activeExtendedBolus != null) {
|
||||
val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet()
|
||||
if (activeExtendedBolus is ValueWrapper.Existing) {
|
||||
extendedBolus?.visibility = View.GONE
|
||||
extendedBolusCancel?.visibility = View.VISIBLE
|
||||
@Suppress("SetTextI18n")
|
||||
extendedBolusCancel?.text = resourceHelper.gs(R.string.cancel) + " " + activeExtendedBolus.toStringMedium()
|
||||
extendedBolusCancel?.text = resourceHelper.gs(R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil)
|
||||
} else {
|
||||
extendedBolus?.visibility = View.VISIBLE
|
||||
extendedBolusCancel?.visibility = View.GONE
|
||||
|
@ -280,7 +289,7 @@ class ActionsFragment : DaggerFragment() {
|
|||
setTempBasal?.visibility = View.GONE
|
||||
cancelTempBasal?.visibility = View.GONE
|
||||
} else {
|
||||
val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis())
|
||||
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
|
||||
if (activeTemp != null) {
|
||||
setTempBasal?.visibility = View.GONE
|
||||
cancelTempBasal?.visibility = View.VISIBLE
|
||||
|
|
|
@ -7,7 +7,6 @@ import android.os.Bundle
|
|||
import dagger.android.HasAndroidInjector
|
||||
import info.nightscout.androidaps.Config
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.data.IobTotal
|
||||
import info.nightscout.androidaps.events.*
|
||||
import info.nightscout.androidaps.interfaces.*
|
||||
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.receivers.ReceiverStatusStore
|
||||
import info.nightscout.androidaps.services.Intents
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.DefaultValueHelper
|
||||
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.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
@ -35,6 +37,7 @@ class DataBroadcastPlugin @Inject constructor(
|
|||
resourceHelper: ResourceHelper,
|
||||
private val aapsSchedulers: AapsSchedulers,
|
||||
private val context: Context,
|
||||
private val dateUtil: DateUtil,
|
||||
private val fabricPrivacy: FabricPrivacy,
|
||||
private val rxBus: RxBusWrapper,
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
|
@ -131,8 +134,8 @@ class DataBroadcastPlugin @Inject constructor(
|
|||
|
||||
private fun iobCob(bundle: Bundle) {
|
||||
profileFunction.getProfile() ?: return
|
||||
val bolusIob: IobTotal = iobCobCalculator.calculateIobFromBolus().round()
|
||||
val basalIob: IobTotal = activePlugin.activeTreatments.lastCalculationTempBasals.round()
|
||||
val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
|
||||
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
|
||||
bundle.putDouble("bolusIob", bolusIob.iob)
|
||||
bundle.putDouble("basalIob", basalIob.basaliob)
|
||||
bundle.putDouble("iob", bolusIob.iob + basalIob.basaliob) // total IOB
|
||||
|
@ -174,12 +177,12 @@ class DataBroadcastPlugin @Inject constructor(
|
|||
bundle.putLong("basalTimeStamp", now)
|
||||
bundle.putDouble("baseBasal", profile.basal)
|
||||
bundle.putString("profile", profileFunction.getProfileName())
|
||||
activePlugin.activeTreatments.getTempBasalFromHistory(now)?.let {
|
||||
bundle.putLong("tempBasalStart", it.date)
|
||||
bundle.putInt("tempBasalDurationInMinutes", it.durationInMinutes)
|
||||
if (it.isAbsolute) bundle.putDouble("tempBasalAbsolute", it.absoluteRate) // U/h for absolute TBR
|
||||
else bundle.putInt("tempBasalPercent", it.percentRate) // % for percent type TBR
|
||||
bundle.putString("tempBasalString", it.toStringFull()) // user friendly string
|
||||
iobCobCalculator.getTempBasalIncludingConvertedExtended(now)?.let {
|
||||
bundle.putLong("tempBasalStart", it.timestamp)
|
||||
bundle.putLong("tempBasalDurationInMinutes", it.durationInMinutes)
|
||||
if (it.isAbsolute) bundle.putDouble("tempBasalAbsolute", it.rate) // U/h for absolute TBR
|
||||
else bundle.putInt("tempBasalPercent", it.rate.toInt()) // % for percent type TBR
|
||||
bundle.putString("tempBasalString", it.toStringFull(profile, dateUtil)) // user friendly string
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
|||
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
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.rx.AapsSchedulers
|
||||
import io.reactivex.Completable
|
||||
|
|
|
@ -16,7 +16,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
|
|||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.receivers.DataWorker
|
||||
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.sharedPreferences.SP
|
||||
import org.json.JSONObject
|
||||
|
|
|
@ -9,7 +9,7 @@ import info.nightscout.androidaps.interfaces.DataSyncSelector
|
|||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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 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_bolus_calculator_result_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) {
|
||||
|
@ -326,4 +328,81 @@ class DataSyncSelectorImplementation @Inject constructor(
|
|||
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
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.general.nsclient
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.Data
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
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.UserEntry
|
||||
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsBolusTransaction
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsCarbsTransaction
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
|
||||
import info.nightscout.androidaps.database.transactions.*
|
||||
import info.nightscout.androidaps.extensions.*
|
||||
import info.nightscout.androidaps.interfaces.ConfigInterface
|
||||
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
|
||||
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.safeGetLong
|
||||
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
|
||||
import info.nightscout.androidaps.utils.extensions.bolusFromJson
|
||||
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.extensions.*
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
import javax.inject.Inject
|
||||
|
||||
|
@ -92,12 +86,17 @@ class NSClientAddUpdateWorker(
|
|||
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
|
||||
ValueWithUnit(it.amount, UserEntry.Units.U)
|
||||
)
|
||||
aapsLogger.debug(LTag.DATABASE, "Inserted bolus $it")
|
||||
}
|
||||
result.invalidated.forEach {
|
||||
uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
|
||||
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
|
||||
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")
|
||||
|
@ -116,12 +115,17 @@ class NSClientAddUpdateWorker(
|
|||
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
|
||||
ValueWithUnit(it.amount, UserEntry.Units.G)
|
||||
)
|
||||
aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it")
|
||||
}
|
||||
result.invalidated.forEach {
|
||||
uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
|
||||
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
|
||||
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")
|
||||
|
@ -144,6 +148,7 @@ class NSClientAddUpdateWorker(
|
|||
ValueWithUnit(it.highTarget, UserEntry.Units.Mg_Dl, it.lowTarget != it.highTarget),
|
||||
ValueWithUnit(it.duration.toInt() / 60000, UserEntry.Units.M, true)
|
||||
)
|
||||
aapsLogger.debug(LTag.DATABASE, "Inserted TemporaryTarget $it")
|
||||
}
|
||||
result.invalidated.forEach {
|
||||
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.duration.toInt() / 60000, UserEntry.Units.M, true)
|
||||
)
|
||||
aapsLogger.debug(LTag.DATABASE, "Invalidated TemporaryTarget $it")
|
||||
}
|
||||
result.ended.forEach {
|
||||
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.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")
|
||||
|
@ -187,6 +197,7 @@ class NSClientAddUpdateWorker(
|
|||
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
|
||||
ValueWithUnit(it.type.text, UserEntry.Units.TherapyEvent)
|
||||
)
|
||||
aapsLogger.debug(LTag.DATABASE, "Inserted TherapyEvent $it")
|
||||
}
|
||||
result.invalidated.forEach {
|
||||
uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS,
|
||||
|
@ -194,13 +205,83 @@ class NSClientAddUpdateWorker(
|
|||
ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true),
|
||||
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")
|
||||
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 ->
|
||||
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 ->
|
||||
databaseHelper.createProfileSwitchFromJsonIfNotExists(json)
|
||||
}
|
||||
|
|
|
@ -14,7 +14,7 @@ import info.nightscout.androidaps.logging.LTag
|
|||
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg
|
||||
import info.nightscout.androidaps.receivers.DataWorker
|
||||
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 javax.inject.Inject
|
||||
|
||||
|
|
|
@ -9,10 +9,8 @@ import info.nightscout.androidaps.R
|
|||
import info.nightscout.androidaps.database.AppRepository
|
||||
import info.nightscout.androidaps.database.entities.UserEntry
|
||||
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsBolusTransaction
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsCarbsTransaction
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction
|
||||
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
|
||||
import info.nightscout.androidaps.database.transactions.*
|
||||
import info.nightscout.androidaps.extensions.*
|
||||
import info.nightscout.androidaps.interfaces.ConfigInterface
|
||||
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
|
||||
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.utils.JsonHelper
|
||||
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
|
||||
import info.nightscout.androidaps.utils.extensions.bolusFromNsIdForInvalidating
|
||||
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.extensions.*
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
import javax.inject.Inject
|
||||
|
||||
|
@ -114,7 +109,7 @@ class NSClientRemoveWorker(
|
|||
}
|
||||
}
|
||||
|
||||
// room Bolus
|
||||
// room Carbs
|
||||
val carbs = carbsFromNsIdForInvalidating(nsId)
|
||||
repository.runTransactionForResult(SyncNsCarbsTransaction(carbs))
|
||||
.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
|
||||
databaseHelper.deleteTempBasalById(nsId)
|
||||
databaseHelper.deleteExtendedBolusById(nsId)
|
||||
databaseHelper.deleteProfileSwitchById(nsId)
|
||||
}
|
||||
|
||||
|
|
|
@ -37,8 +37,10 @@ import info.nightscout.androidaps.database.transactions.UpdateNsIdBolusCalculato
|
|||
import info.nightscout.androidaps.database.transactions.UpdateNsIdBolusTransaction;
|
||||
import info.nightscout.androidaps.database.transactions.UpdateNsIdCarbsTransaction;
|
||||
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.UpdateNsIdGlucoseValueTransaction;
|
||||
import info.nightscout.androidaps.database.transactions.UpdateNsIdTemporaryBasalTransaction;
|
||||
import info.nightscout.androidaps.database.transactions.UpdateNsIdTemporaryTargetTransaction;
|
||||
import info.nightscout.androidaps.database.transactions.UpdateNsIdTherapyEventTransaction;
|
||||
import info.nightscout.androidaps.db.DbRequest;
|
||||
|
@ -139,7 +141,7 @@ public class NSClientService extends DaggerService {
|
|||
private final ArrayList<Long> reconnections = new ArrayList<>();
|
||||
private final int WATCHDOG_INTERVAL_MINUTES = 2;
|
||||
private final int WATCHDOG_RECONNECT_IN = 15;
|
||||
private final int WATCHDOG_MAXCONNECTIONS = 5;
|
||||
private final int WATCHDOG_MAX_CONNECTIONS = 5;
|
||||
|
||||
public NSClientService() {
|
||||
super();
|
||||
|
@ -340,6 +342,38 @@ public class NSClientService extends DaggerService {
|
|||
dataSyncSelector.processChangedBolusCalculatorResultsCompat();
|
||||
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) {
|
||||
DeviceStatus deviceStatus = (DeviceStatus) ack.getOriginalObject();
|
||||
deviceStatus.getInterfaceIDs().setNightscoutId(ack.getId());
|
||||
|
@ -424,6 +458,22 @@ public class NSClientService extends DaggerService {
|
|||
dataSyncSelector.processChangedBolusCalculatorResultsCompat();
|
||||
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
|
||||
if (ack.getResult()) {
|
||||
uploadQueue.removeByMongoId(ack.getAction(), ack.get_id());
|
||||
|
@ -549,8 +599,8 @@ public class NSClientService extends DaggerService {
|
|||
reconnections.remove(r);
|
||||
}
|
||||
}
|
||||
rxBus.send(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS));
|
||||
if (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_MAX_CONNECTIONS) {
|
||||
Notification n = new Notification(Notification.NS_MALFUNCTION, resourceHelper.gs(R.string.nsmalfunction), Notification.URGENT);
|
||||
rxBus.send(new EventNewNotification(n));
|
||||
rxBus.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
|
||||
|
@ -990,6 +1040,8 @@ public class NSClientService extends DaggerService {
|
|||
dataSyncSelector.processChangedBolusesCompat();
|
||||
dataSyncSelector.processChangedCarbsCompat();
|
||||
dataSyncSelector.processChangedBolusCalculatorResultsCompat();
|
||||
dataSyncSelector.processChangedTemporaryBasalsCompat();
|
||||
dataSyncSelector.processChangedExtendedBolusesCompat();
|
||||
dataSyncSelector.processChangedGlucoseValuesCompat();
|
||||
dataSyncSelector.processChangedTempTargetsCompat();
|
||||
dataSyncSelector.processChangedFoodsCompat();
|
||||
|
|
|
@ -28,7 +28,7 @@ import info.nightscout.androidaps.interfaces.PluginType
|
|||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.logging.LTag
|
||||
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.rx.AapsSchedulers
|
||||
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()) })
|
||||
.map { enqueueTherapyEvent(it); increaseCounter() }
|
||||
.ignoreElements()
|
||||
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) })
|
||||
.map { enqueueExtendedBolus(it); increaseCounter() }
|
||||
.ignoreElements()
|
||||
// .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) })
|
||||
// .map { enqueueExtendedBolus(it); increaseCounter() }
|
||||
// .ignoreElements()
|
||||
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllProfileSwitches()) })
|
||||
.map { enqueueProfileSwitch(it); increaseCounter() }
|
||||
.ignoreElements()
|
||||
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) })
|
||||
.map { enqueueTotalDailyDose(it); increaseCounter() }
|
||||
.ignoreElements()
|
||||
.andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) })
|
||||
.map { enqueueTemporaryBasal(it); increaseCounter() }
|
||||
.ignoreElements()
|
||||
// .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) })
|
||||
// .map { enqueueTemporaryBasal(it); increaseCounter() }
|
||||
// .ignoreElements()
|
||||
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) })
|
||||
.map { enqueueTempTarget(it); increaseCounter() }
|
||||
.ignoreElements()
|
||||
|
|
|
@ -36,6 +36,7 @@ import info.nightscout.androidaps.database.interfaces.end
|
|||
import info.nightscout.androidaps.databinding.OverviewFragmentBinding
|
||||
import info.nightscout.androidaps.dialogs.*
|
||||
import info.nightscout.androidaps.events.*
|
||||
import info.nightscout.androidaps.extensions.*
|
||||
import info.nightscout.androidaps.interfaces.*
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.alertDialogs.OKDialog
|
||||
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
|
||||
import info.nightscout.androidaps.utils.extensions.directionToIcon
|
||||
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.extensions.*
|
||||
import info.nightscout.androidaps.utils.protection.ProtectionCheck
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
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 activePlugin: ActivePluginProvider
|
||||
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculator
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var dexcomPlugin: DexcomPlugin
|
||||
@Inject lateinit var dexcomMediator: DexcomPlugin.DexcomMediator
|
||||
@Inject lateinit var xdripPlugin: XdripPlugin
|
||||
|
@ -412,7 +410,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
}
|
||||
|
||||
private fun onClickQuickWizard() {
|
||||
val actualBg = iobCobCalculatorPlugin.actualBg()
|
||||
val actualBg = iobCobCalculator.actualBg()
|
||||
val profile = profileFunction.getProfile()
|
||||
val profileName = profileFunction.getProfileName()
|
||||
val pump = activePlugin.activePump
|
||||
|
@ -447,11 +445,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun processButtonsVisibility() {
|
||||
val lastBG = iobCobCalculatorPlugin.lastBg()
|
||||
val lastBG = iobCobCalculator.lastBg()
|
||||
val pump = activePlugin.activePump
|
||||
val profile = profileFunction.getProfile()
|
||||
val profileName = profileFunction.getProfileName()
|
||||
val actualBG = iobCobCalculatorPlugin.actualBg()
|
||||
val actualBG = iobCobCalculator.actualBg()
|
||||
|
||||
// QuickWizard button
|
||||
val quickWizardEntry = quickWizard.getActive()
|
||||
|
@ -563,8 +561,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
binding.loopPumpStatusLayout.loopLayout.visibility = View.VISIBLE
|
||||
|
||||
val profile = profileFunction.getProfile() ?: return
|
||||
val actualBG = iobCobCalculatorPlugin.actualBg()
|
||||
val lastBG = iobCobCalculatorPlugin.lastBg()
|
||||
val actualBG = iobCobCalculator.actualBg()
|
||||
val lastBG = iobCobCalculator.lastBg()
|
||||
val pump = activePlugin.activePump
|
||||
val units = profileFunction.getUnits()
|
||||
val lowLine = defaultValueHelper.determineLowLine()
|
||||
|
@ -703,13 +701,13 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
}
|
||||
|
||||
// Basal, TBR
|
||||
val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis())
|
||||
binding.infoLayout.baseBasal.text = activeTemp?.let { "T:" + activeTemp.toStringVeryShort() }
|
||||
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
|
||||
binding.infoLayout.baseBasal.text = activeTemp?.let { "T:" + activeTemp.toStringShort() }
|
||||
?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)
|
||||
binding.infoLayout.basalLayout.setOnClickListener {
|
||||
var fullText = "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}"
|
||||
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 {
|
||||
OKDialog.show(it, resourceHelper.gs(R.string.basal), fullText)
|
||||
}
|
||||
|
@ -718,23 +716,23 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
?: resourceHelper.gc(R.color.defaulttextcolor))
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
// Extended bolus
|
||||
val extendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis())
|
||||
val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet()
|
||||
binding.infoLayout.extendedBolus.text =
|
||||
if (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses)
|
||||
resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.absoluteRate())
|
||||
if (extendedBolus is ValueWrapper.Existing && !pump.isFakingTempsByExtendedBoluses)
|
||||
resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.value.rate)
|
||||
else ""
|
||||
binding.infoLayout.extendedBolus.setOnClickListener {
|
||||
if (extendedBolus != null) activity?.let {
|
||||
OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), extendedBolus.toString())
|
||||
if (extendedBolus is ValueWrapper.Existing) activity?.let {
|
||||
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
|
||||
binding.loopPumpStatusLayout.activeProfile.text = profileFunction.getProfileNameWithDuration()
|
||||
|
@ -749,8 +747,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
processButtonsVisibility()
|
||||
|
||||
// iob
|
||||
val bolusIob = iobCobCalculatorPlugin.calculateIobFromBolus().round()
|
||||
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round()
|
||||
val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
|
||||
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
|
||||
binding.infoLayout.iob.text = resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob)
|
||||
|
||||
binding.infoLayout.iobLayout.setOnClickListener {
|
||||
|
@ -769,7 +767,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
|
||||
// cob
|
||||
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) {
|
||||
cobText = resourceHelper.gs(R.string.format_carbs, cobInfo.displayCob!!.toInt())
|
||||
if (cobInfo.futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(cobInfo.futureCarbs) + ")"
|
||||
|
@ -813,7 +811,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
}
|
||||
|
||||
binding.infoLayout.sensitivity.text =
|
||||
iobCobCalculatorPlugin.getLastAutosensData("Overview")?.let { autosensData ->
|
||||
iobCobCalculator.getLastAutosensData("Overview")?.let { autosensData ->
|
||||
String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100)
|
||||
} ?: ""
|
||||
}
|
||||
|
@ -823,7 +821,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
if (_binding == null) return@launch
|
||||
val menuChartSettings = overviewMenus.setting
|
||||
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()
|
||||
|
||||
// do preparation in different thread
|
||||
|
@ -890,7 +888,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
|
|||
// ------------------ 2nd graph
|
||||
synchronized(graphLock) {
|
||||
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 useIobForScale = false
|
||||
var useCobForScale = false
|
||||
|
|
|
@ -6,6 +6,7 @@ import dagger.android.HasAndroidInjector
|
|||
import info.nightscout.androidaps.Config
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.events.EventRefreshOverview
|
||||
import info.nightscout.androidaps.extensions.*
|
||||
import info.nightscout.androidaps.interfaces.OverviewInterface
|
||||
import info.nightscout.androidaps.interfaces.PluginBase
|
||||
import info.nightscout.androidaps.interfaces.PluginDescription
|
||||
|
|
|
@ -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.utils.DecimalFormatter
|
||||
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.sharedPreferences.SP
|
||||
import javax.inject.Inject
|
||||
|
|
|
@ -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.iob.iobCobCalculator.AutosensResult
|
||||
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 java.util.*
|
||||
import javax.inject.Inject
|
||||
|
@ -259,8 +259,8 @@ class GraphData(
|
|||
|
||||
// Extended bolus
|
||||
if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) {
|
||||
treatmentsPlugin.extendedBolusesFromHistory.list
|
||||
.filterTimeframe(fromTime, endTime)
|
||||
repository.getExtendedBolusDataFromTimeToTime(fromTime, endTime, true).blockingGet()
|
||||
.map { ExtendedBolusDataPoint(it) }
|
||||
.filter { it.duration != 0L }
|
||||
.forEach {
|
||||
it.y = getNearestBg(it.x.toLong())
|
||||
|
@ -529,9 +529,9 @@ class GraphData(
|
|||
while (time <= toTime) {
|
||||
// if align Dev Scale with BGI scale, then calculate BGI value, else bgi = 0.0
|
||||
val bgi: Double = if (devBgiScale) {
|
||||
val profile = profileFunction.getProfile(time)
|
||||
val profile = profileFunction.getProfile(time) ?: continue
|
||||
total = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile)
|
||||
total.activity * (profile?.getIsfMgdl(time) ?: 0.0) * 5.0
|
||||
total.activity * profile.getIsfMgdl(time) * 5.0
|
||||
} else 0.0
|
||||
|
||||
iobCobCalculator.getAutosensData(time)?.let { autosensData ->
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
|
@ -15,15 +15,14 @@ import info.nightscout.androidaps.events.*
|
|||
import info.nightscout.androidaps.interfaces.*
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.IobCobCalculatorPlugin
|
||||
import info.nightscout.androidaps.utils.DecimalFormatter
|
||||
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.ResourceHelper
|
||||
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 javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
@ -150,14 +149,14 @@ class PersistentNotificationPlugin @Inject constructor(
|
|||
line1aa = resourceHelper.gs(R.string.missed_bg_readings)
|
||||
line1 = line1aa
|
||||
}
|
||||
val activeTemp = activePlugins.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis())
|
||||
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
|
||||
if (activeTemp != null) {
|
||||
line1 += " " + activeTemp.toStringShort()
|
||||
line1aa += " " + activeTemp.toStringShort() + "."
|
||||
}
|
||||
//IOB
|
||||
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()
|
||||
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"
|
||||
|
|
|
@ -41,7 +41,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv
|
|||
import info.nightscout.androidaps.queue.Callback
|
||||
import info.nightscout.androidaps.receivers.DataWorker
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -322,7 +322,7 @@ class SmsCommunicatorPlugin @Inject constructor(
|
|||
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 + ", "
|
||||
val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
|
||||
val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round()
|
||||
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
|
||||
val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB")
|
||||
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 "
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
package info.nightscout.androidaps.plugins.general.tidepool.comm
|
||||
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.data.Intervals
|
||||
import info.nightscout.androidaps.database.AppRepository
|
||||
import info.nightscout.androidaps.database.entities.TemporaryBasal
|
||||
import info.nightscout.androidaps.db.ProfileSwitch
|
||||
import info.nightscout.androidaps.db.TemporaryBasal
|
||||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
|
@ -146,18 +145,19 @@ class UploadChunk @Inject constructor(
|
|||
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>()
|
||||
for (tbr in tbrList.list) {
|
||||
if (tbr.date in start..end && tbr.durationInMinutes != 0)
|
||||
results.add(BasalElement(tbr, profileFunction))
|
||||
for (tbr in tbrList) {
|
||||
if (tbr.timestamp in start..end)
|
||||
profileFunction.getProfile(tbr.timestamp)?.let {
|
||||
results.add(BasalElement(tbr, it))
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
private fun getBasals(start: Long, end: Long): List<BasalElement> {
|
||||
val temporaryBasals = treatmentsPlugin.temporaryBasalsFromHistory
|
||||
temporaryBasals.merge()
|
||||
val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(start, end, true).blockingGet()
|
||||
val selection = fromTemporaryBasals(temporaryBasals, start, end) // TODO do not upload running TBR
|
||||
if (selection.isNotEmpty())
|
||||
rxBus.send(EventTidepoolStatus("${selection.size} TBRs selected for upload"))
|
||||
|
|
|
@ -1,32 +1,38 @@
|
|||
package info.nightscout.androidaps.plugins.general.tidepool.elements
|
||||
|
||||
import com.google.gson.annotations.Expose
|
||||
import info.nightscout.androidaps.db.TemporaryBasal
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
import info.nightscout.androidaps.database.entities.TemporaryBasal
|
||||
import info.nightscout.androidaps.extensions.convertedToAbsolute
|
||||
import java.util.*
|
||||
|
||||
class BasalElement(tbr: TemporaryBasal, private val profileFunction: ProfileFunction)
|
||||
: BaseElement(tbr.date, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.date).toByteArray()).toString()) {
|
||||
class BasalElement(tbr: TemporaryBasal, private val profile: Profile)
|
||||
: BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString()) {
|
||||
|
||||
internal var timestamp: Long = 0 // not exposed
|
||||
|
||||
@Expose
|
||||
internal var deliveryType = "automated"
|
||||
|
||||
@Expose
|
||||
internal var duration: Long = 0
|
||||
|
||||
@Expose
|
||||
internal var rate = -1.0
|
||||
|
||||
@Expose
|
||||
internal var scheduleName = "AAPS"
|
||||
|
||||
@Expose
|
||||
internal var clockDriftOffset: Long = 0
|
||||
|
||||
@Expose
|
||||
internal var conversionOffset: Long = 0
|
||||
|
||||
init {
|
||||
type = "basal"
|
||||
timestamp = tbr.date
|
||||
rate = tbr.tempBasalConvertedToAbsolute(tbr.date, profileFunction.getProfile(tbr.date))
|
||||
duration = tbr.end() - tbr.start()
|
||||
timestamp = tbr.timestamp
|
||||
rate = tbr.convertedToAbsolute(tbr.timestamp, profile)
|
||||
duration = tbr.duration
|
||||
}
|
||||
}
|
|
@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements
|
|||
import com.google.gson.annotations.Expose
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
import info.nightscout.androidaps.database.entities.TherapyEvent
|
||||
import info.nightscout.androidaps.utils.extensions.toConstant
|
||||
import info.nightscout.androidaps.extensions.toConstant
|
||||
import java.util.*
|
||||
|
||||
class BloodGlucoseElement(therapyEvent: TherapyEvent)
|
||||
|
|
|
@ -33,7 +33,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP
|
|||
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
|
||||
import info.nightscout.androidaps.queue.Callback
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
|
|
@ -32,13 +32,14 @@ import dagger.android.AndroidInjection;
|
|||
import info.nightscout.androidaps.Config;
|
||||
import info.nightscout.androidaps.Constants;
|
||||
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.Profile;
|
||||
import info.nightscout.androidaps.database.AppRepository;
|
||||
import info.nightscout.androidaps.database.entities.Bolus;
|
||||
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.IobCobCalculator;
|
||||
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.bus.RxBusWrapper;
|
||||
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.events.EventWearConfirmAction;
|
||||
import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction;
|
||||
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
|
||||
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.utils.DecimalFormatter;
|
||||
import info.nightscout.androidaps.utils.DefaultValueHelper;
|
||||
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.sharedPreferences.SP;
|
||||
|
||||
|
@ -75,7 +75,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
@Inject public ActivePluginProvider activePlugin;
|
||||
@Inject public LoopPlugin loopPlugin;
|
||||
@Inject public IobCobCalculator iobCobCalculator;
|
||||
@Inject public TreatmentsPlugin treatmentsPlugin;
|
||||
@Inject public AppRepository repository;
|
||||
@Inject ReceiverStatusStore receiverStatusStore;
|
||||
@Inject Config config;
|
||||
|
@ -437,8 +436,8 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
double beginBasalValue = profile.getBasal(beginBasalSegmentTime);
|
||||
double endBasalValue = beginBasalValue;
|
||||
|
||||
TemporaryBasal tb1 = treatmentsPlugin.getTempBasalFromHistory(runningTime);
|
||||
TemporaryBasal tb2 = treatmentsPlugin.getTempBasalFromHistory(runningTime); //TODO for Adrian ... what's the meaning?
|
||||
TemporaryBasal tb1 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime);
|
||||
TemporaryBasal tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime); //TODO for Adrian ... what's the meaning?
|
||||
double tb_before = beginBasalValue;
|
||||
double tb_amount = beginBasalValue;
|
||||
long tb_start = runningTime;
|
||||
|
@ -447,7 +446,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
tb_before = beginBasalValue;
|
||||
Profile profileTB = profileFunction.getProfile(runningTime);
|
||||
if (profileTB != null) {
|
||||
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime, profileTB);
|
||||
tb_amount = TemporaryBasalExtensionKt.convertedToAbsolute(tb1, runningTime, profileTB);
|
||||
tb_start = runningTime;
|
||||
}
|
||||
}
|
||||
|
@ -469,7 +468,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
}
|
||||
|
||||
//temps
|
||||
tb2 = treatmentsPlugin.getTempBasalFromHistory(runningTime);
|
||||
tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime);
|
||||
|
||||
if (tb1 == null && tb2 == null) {
|
||||
//no temp stays no temp
|
||||
|
@ -484,10 +483,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
tb1 = tb2;
|
||||
tb_start = runningTime;
|
||||
tb_before = endBasalValue;
|
||||
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime, profileTB);
|
||||
tb_amount = TemporaryBasalExtensionKt.convertedToAbsolute(tb1, runningTime, profileTB);
|
||||
|
||||
} else if (tb1 != null && tb2 != null) {
|
||||
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime, profileTB);
|
||||
double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, runningTime, profileTB);
|
||||
if (currentAmount != tb_amount) {
|
||||
temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount));
|
||||
tb_start = runningTime;
|
||||
|
@ -502,14 +501,14 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
|
||||
}
|
||||
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) {
|
||||
//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));
|
||||
} else {
|
||||
//express currently running temp by painting it a bit into the future
|
||||
Profile profileNow = profileFunction.getProfile(now);
|
||||
double currentAmount = tb2.tempBasalConvertedToAbsolute(now, profileNow);
|
||||
double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, now, profileNow);
|
||||
if (currentAmount != 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));
|
||||
|
@ -518,11 +517,11 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
}
|
||||
}
|
||||
} else {
|
||||
tb2 = treatmentsPlugin.getTempBasalFromHistory(now); //use "now" to express current situation
|
||||
tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now); //use "now" to express current situation
|
||||
if (tb2 != null) {
|
||||
//onset at the end
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
@ -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) {
|
||||
List<GlucoseValueDataPoint> predArray =
|
||||
finalLastRun.getConstraintsProcessed().getPredictions()
|
||||
.stream().map( bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper))
|
||||
.stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (!predArray.isEmpty()) {
|
||||
|
@ -688,7 +687,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
|
|||
iobSum = iobDetail = cobString = currentBasal = bgiString = "";
|
||||
if (profile != null) {
|
||||
IobTotal bolusIob = iobCobCalculator.calculateIobFromBolus().round();
|
||||
IobTotal basalIob = treatmentsPlugin.getLastCalculationTempBasals().round();
|
||||
IobTotal basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round();
|
||||
|
||||
iobSum = DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob + 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)
|
||||
return "";
|
||||
|
||||
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
|
||||
TemporaryBasal activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis());
|
||||
if (activeTemp != null) {
|
||||
basalStringResult = activeTemp.toStringShort();
|
||||
basalStringResult = TemporaryBasalExtensionKt.toStringShort(activeTemp);
|
||||
} else {
|
||||
if (sp.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false)) {
|
||||
basalStringResult = "100%";
|
||||
} else {
|
||||
basalStringResult = DecimalFormatter.INSTANCE.to2Decimal(profile.getBasal()) + "U/h";
|
||||
}
|
||||
basalStringResult = DecimalFormatter.INSTANCE.to2Decimal(profile.getBasal()) + "U/h";
|
||||
}
|
||||
return basalStringResult;
|
||||
}
|
||||
|
|
|
@ -13,6 +13,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
|
|||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.utils.DecimalFormatter
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.extensions.toStringShort
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -121,13 +122,13 @@ class StatusLinePlugin @Inject constructor(
|
|||
lastLoopStatus = true
|
||||
}
|
||||
//Temp basal
|
||||
val activeTemp = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis())
|
||||
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
|
||||
if (activeTemp != null) {
|
||||
status += activeTemp.toStringShort() + " "
|
||||
}
|
||||
//IOB
|
||||
val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
|
||||
val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round()
|
||||
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
|
||||
status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U"
|
||||
if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) {
|
||||
status += ("("
|
||||
|
|
|
@ -6,8 +6,8 @@ import info.nightscout.androidaps.interfaces.InsulinInterface
|
|||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.utils.extensions.storeInt
|
||||
import info.nightscout.androidaps.utils.extensions.putInt
|
||||
import info.nightscout.androidaps.extensions.storeInt
|
||||
import info.nightscout.androidaps.extensions.putInt
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
import org.json.JSONObject
|
||||
|
|
|
@ -9,9 +9,12 @@ import info.nightscout.androidaps.data.IobTotal
|
|||
import info.nightscout.androidaps.data.MealData
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
import info.nightscout.androidaps.database.AppRepository
|
||||
import info.nightscout.androidaps.database.ValueWrapper
|
||||
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.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.interfaces.*
|
||||
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.SensitivityOref1Plugin
|
||||
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.DecimalFormatter
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -52,7 +56,6 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
resourceHelper: ResourceHelper,
|
||||
private val profileFunction: ProfileFunction,
|
||||
private val activePlugin: ActivePluginProvider,
|
||||
private val treatmentsPlugin: TreatmentsPlugin,
|
||||
private val sensitivityOref1Plugin: SensitivityOref1Plugin,
|
||||
private val sensitivityAAPSPlugin: SensitivityAAPSPlugin,
|
||||
private val sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin,
|
||||
|
@ -173,7 +176,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
return autosensDataTable
|
||||
}
|
||||
|
||||
fun adjustToReferenceTime(someTime: Long): Long {
|
||||
private fun adjustToReferenceTime(someTime: Long): Long {
|
||||
if (referenceTime == -1L) {
|
||||
referenceTime = someTime
|
||||
return someTime
|
||||
|
@ -377,11 +380,25 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
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 {
|
||||
val profile = profileFunction.getProfile(from)
|
||||
var dia = Constants.defaultDIA
|
||||
if (profile != null) dia = profile.dia
|
||||
val oldestDataAvailable = treatmentsPlugin.oldestDataAvailable()
|
||||
val oldestDataAvailable = oldestDataAvailable()
|
||||
val getBGDataFrom: Long
|
||||
if (limitDataToOldestAvailable) {
|
||||
getBGDataFrom = max(oldestDataAvailable, (from - T.hours(1).msecs() * (24 + dia)).toLong())
|
||||
|
@ -390,7 +407,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
return getBGDataFrom
|
||||
}
|
||||
|
||||
override fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile?): IobTotal {
|
||||
override fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile): IobTotal {
|
||||
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) }
|
||||
}
|
||||
|
||||
fun calculateFromTreatmentsAndTemps(fromTime: Long, profile: Profile?): IobTotal {
|
||||
fun calculateFromTreatmentsAndTemps(fromTime: Long, profile: Profile): IobTotal {
|
||||
val now = System.currentTimeMillis()
|
||||
val time = roundUpTime(fromTime)
|
||||
val cacheHit = iobTable[time]
|
||||
|
@ -407,16 +424,18 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
return cacheHit
|
||||
} // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
|
||||
val bolusIob = calculateIobFromBolusToTime(time).round()
|
||||
val basalIob = treatmentsPlugin.getCalculationToTimeTempBasals(time, true, now).round()
|
||||
val basalIob = calculateIobToTimeFromTempBasalsIncludingConvertedExtended(time).round()
|
||||
// OpenAPSSMB only
|
||||
// Add expected zero temp basal for next 240 minutes
|
||||
val basalIobWithZeroTemp = basalIob.copy()
|
||||
val t = TemporaryBasal(injector)
|
||||
.date(now + 60 * 1000L)
|
||||
.duration(240)
|
||||
.absolute(0.0)
|
||||
if (t.date < time) {
|
||||
val calc = t.iobCalc(time, profile)
|
||||
val t = TemporaryBasal(
|
||||
timestamp = now + 60 * 1000L,
|
||||
duration = 240,
|
||||
rate = 0.0,
|
||||
isAbsolute = true,
|
||||
type = TemporaryBasal.Type.NORMAL)
|
||||
if (t.timestamp < time) {
|
||||
val calc = t.iobCalc(time, profile, activePlugin.activeInsulin)
|
||||
basalIobWithZeroTemp.plus(calc)
|
||||
}
|
||||
basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round()
|
||||
|
@ -437,7 +456,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
return cacheHit
|
||||
} // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
|
||||
val bolusIob = calculateIobFromBolusToTime(time).round()
|
||||
val basalIob = treatmentsPlugin.getAbsoluteIOBTempBasals(time).round()
|
||||
val basalIob = calculateAbsoluteIobTempBasals(time).round()
|
||||
val iobTotal = IobTotal.combine(bolusIob, basalIob).round()
|
||||
if (time < System.currentTimeMillis()) {
|
||||
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 {
|
||||
val now = DateUtil.now()
|
||||
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
|
||||
// Add expected zero temp basal for next 240 minutes
|
||||
val basalIobWithZeroTemp = basalIob.copy()
|
||||
val t = TemporaryBasal(injector)
|
||||
.date(now + 60 * 1000L)
|
||||
.duration(240)
|
||||
.absolute(0.0)
|
||||
if (t.date < time) {
|
||||
val profile = profileFunction.getProfile(t.date)
|
||||
val t = TemporaryBasal(
|
||||
timestamp = now + 60 * 1000L,
|
||||
duration = 240,
|
||||
rate = 0.0,
|
||||
isAbsolute = true,
|
||||
type = TemporaryBasal.Type.NORMAL)
|
||||
if (t.timestamp < time) {
|
||||
val profile = profileFunction.getProfile(t.timestamp)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
@ -484,11 +505,11 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
if (retVal == null) {
|
||||
//log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString());
|
||||
retVal = BasalData()
|
||||
val tb = treatmentsPlugin.getTempBasalFromHistory(time)
|
||||
val tb = getTempBasalIncludingConvertedExtended(time)
|
||||
retVal.basal = profile.getBasal(time)
|
||||
if (tb != null) {
|
||||
retVal.isTempBasalRunning = true
|
||||
retVal.tempBasalAbsolute = tb.tempBasalConvertedToAbsolute(time, profile)
|
||||
retVal.tempBasalAbsolute = tb.convertedToAbsolute(time, profile)
|
||||
} else {
|
||||
retVal.isTempBasalRunning = false
|
||||
retVal.tempBasalAbsolute = retVal.basal
|
||||
|
@ -784,31 +805,29 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
* Time range to the past for IOB calculation
|
||||
* @return milliseconds
|
||||
*/
|
||||
fun range(): Long {
|
||||
val dia = profileFunction.getProfile()?.dia ?: Constants.defaultDIA
|
||||
return (60 * 60 * 1000L * (24 + dia)).toLong()
|
||||
}
|
||||
fun range(): Long = ((profileFunction.getProfile()?.dia
|
||||
?: Constants.defaultDIA) * 60 * 60 * 1000).toLong()
|
||||
|
||||
override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil._now())
|
||||
|
||||
override fun calculateIobFromBolusToTime(timestamp: Long): IobTotal {
|
||||
val total = IobTotal(timestamp)
|
||||
override fun calculateIobFromBolusToTime(toTime: Long): IobTotal {
|
||||
val total = IobTotal(toTime)
|
||||
val profile = profileFunction.getProfile() ?: return total
|
||||
val dia = profile.dia
|
||||
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 ->
|
||||
if (t.isValid && t.timestamp < timestamp) {
|
||||
val tIOB = t.iobCalc(activePlugin, timestamp, dia)
|
||||
if (t.isValid && t.timestamp < toTime) {
|
||||
val tIOB = t.iobCalc(activePlugin, toTime, dia)
|
||||
total.iob += tIOB.iobContrib
|
||||
total.activity += tIOB.activityContrib
|
||||
if (t.amount > 0 && t.timestamp > total.lastBolusTime) total.lastBolusTime = t.timestamp
|
||||
if (t.type != Bolus.Type.SMB) {
|
||||
// instead of dividing the DIA that only worked on the bilinear curves,
|
||||
// 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 bIOB = t.iobCalc(activePlugin, snoozeTime, dia)
|
||||
total.bolussnooze += bIOB.iobContrib
|
||||
|
@ -816,8 +835,146 @@ open class IobCobCalculatorPlugin @Inject constructor(
|
|||
}
|
||||
}
|
||||
|
||||
total.plus(treatmentsPlugin.getCalculationToTimeExtendedBoluses(timestamp))
|
||||
total.plus(calculateIobToTimeFromExtendedBoluses(toTime))
|
||||
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
|
||||
}
|
||||
}
|
|
@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
|
|||
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
|
||||
import info.nightscout.androidaps.utils.*
|
||||
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.sharedPreferences.SP
|
||||
import java.util.*
|
||||
|
|
|
@ -10,24 +10,29 @@ import info.nightscout.androidaps.R
|
|||
import info.nightscout.androidaps.databinding.VirtualpumpFragmentBinding
|
||||
import info.nightscout.androidaps.events.EventExtendedBolusChange
|
||||
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.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.T
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
import info.nightscout.androidaps.extensions.toStringFull
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
import javax.inject.Inject
|
||||
|
||||
class VirtualPumpFragment : DaggerFragment() {
|
||||
|
||||
@Inject lateinit var rxBus: RxBusWrapper
|
||||
@Inject lateinit var resourceHelper: ResourceHelper
|
||||
@Inject lateinit var dateUtil: DateUtil
|
||||
@Inject lateinit var fabricPrivacy: FabricPrivacy
|
||||
@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
|
||||
|
||||
private val disposable = CompositeDisposable()
|
||||
|
@ -88,10 +93,11 @@ class VirtualPumpFragment : DaggerFragment() {
|
|||
@Synchronized
|
||||
private fun updateGui() {
|
||||
if (_binding == null) return
|
||||
val profile = profileFunction.getProfile() ?: return
|
||||
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.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble())
|
||||
|
|
|
@ -9,9 +9,6 @@ import info.nightscout.androidaps.R
|
|||
import info.nightscout.androidaps.data.DetailedBolusInfo
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
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.interfaces.*
|
||||
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.pump.common.defs.PumpType
|
||||
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.InstanceId.instanceId
|
||||
import info.nightscout.androidaps.utils.T
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -50,7 +48,7 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
private val aapsSchedulers: AapsSchedulers,
|
||||
private val sp: SP,
|
||||
private val profileFunction: ProfileFunction,
|
||||
private val treatmentsPlugin: TreatmentsPlugin,
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
commandQueue: CommandQueueProvider,
|
||||
private val pumpSync: PumpSync,
|
||||
private val config: Config,
|
||||
|
@ -223,11 +221,6 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
|
||||
override fun stopBolusDelivering() {}
|
||||
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)
|
||||
result.success = true
|
||||
result.enacted = true
|
||||
|
@ -235,7 +228,16 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
result.absolute = absoluteRate
|
||||
result.duration = durationInMinutes
|
||||
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")
|
||||
rxBus.send(EventVirtualPumpUpdateGui())
|
||||
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 {
|
||||
val tempBasal = TemporaryBasal(injector)
|
||||
.date(System.currentTimeMillis())
|
||||
.percent(percent)
|
||||
.duration(durationInMinutes)
|
||||
.source(Source.USER)
|
||||
val result = PumpEnactResult(injector)
|
||||
result.success = true
|
||||
result.enacted = true
|
||||
|
@ -256,7 +253,16 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
result.isTempCancel = false
|
||||
result.duration = durationInMinutes
|
||||
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")
|
||||
rxBus.send(EventVirtualPumpUpdateGui())
|
||||
lastDataTime = System.currentTimeMillis()
|
||||
|
@ -266,18 +272,21 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
|
||||
val result = cancelExtendedBolus()
|
||||
if (!result.success) return result
|
||||
val extendedBolus = ExtendedBolus(injector)
|
||||
.date(System.currentTimeMillis())
|
||||
.insulin(insulin)
|
||||
.durationInMinutes(durationInMinutes)
|
||||
.source(Source.USER)
|
||||
result.success = true
|
||||
result.enacted = true
|
||||
result.bolusDelivered = insulin
|
||||
result.isTempCancel = false
|
||||
result.duration = durationInMinutes
|
||||
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")
|
||||
rxBus.send(EventVirtualPumpUpdateGui())
|
||||
lastDataTime = System.currentTimeMillis()
|
||||
|
@ -289,11 +298,14 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
result.success = true
|
||||
result.isTempCancel = true
|
||||
result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
|
||||
if (treatmentsPlugin.isTempBasalInProgress) {
|
||||
if (pumpSync.expectedPumpState().temporaryBasal != null) {
|
||||
result.enacted = true
|
||||
val tempStop = TemporaryBasal(injector).date(System.currentTimeMillis()).source(Source.USER)
|
||||
treatmentsPlugin.addToHistoryTempBasal(tempStop)
|
||||
//tempBasal = null;
|
||||
pumpSync.syncStopTemporaryBasalWithPumpId(
|
||||
timestamp = dateUtil._now(),
|
||||
endPumpId = dateUtil._now(),
|
||||
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
|
||||
pumpSerial = serialNumber()
|
||||
)
|
||||
aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result")
|
||||
rxBus.send(EventVirtualPumpUpdateGui())
|
||||
}
|
||||
|
@ -303,10 +315,13 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
|
||||
override fun cancelExtendedBolus(): PumpEnactResult {
|
||||
val result = PumpEnactResult(injector)
|
||||
if (treatmentsPlugin.isInHistoryExtendedBolusInProgress) {
|
||||
val exStop = ExtendedBolus(injector, System.currentTimeMillis())
|
||||
exStop.source = Source.USER
|
||||
treatmentsPlugin.addToHistoryExtendedBolus(exStop)
|
||||
if (pumpSync.expectedPumpState().extendedBolus != null) {
|
||||
pumpSync.syncStopExtendedBolusWithPumpId(
|
||||
timestamp = dateUtil._now(),
|
||||
endPumpId = dateUtil._now(),
|
||||
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
|
||||
pumpSerial = serialNumber()
|
||||
)
|
||||
}
|
||||
result.success = true
|
||||
result.enacted = true
|
||||
|
@ -335,16 +350,16 @@ open class VirtualPumpPlugin @Inject constructor(
|
|||
extended.put("ActiveProfile", profileName)
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
val tb = treatmentsPlugin.getTempBasalFromHistory(now)
|
||||
val tb = iobCobCalculator.getTempBasal(now)
|
||||
if (tb != null) {
|
||||
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile))
|
||||
extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date))
|
||||
extended.put("TempBasalAbsoluteRate", tb.convertedToAbsolute(now, profile))
|
||||
extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.timestamp))
|
||||
extended.put("TempBasalRemaining", tb.plannedRemainingMinutes)
|
||||
}
|
||||
val eb = treatmentsPlugin.getExtendedBolusFromHistory(now)
|
||||
val eb = iobCobCalculator.getExtendedBolus(now)
|
||||
if (eb != null) {
|
||||
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate())
|
||||
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date))
|
||||
extended.put("ExtendedBolusAbsoluteRate", eb.rate)
|
||||
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp))
|
||||
extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes)
|
||||
}
|
||||
status.put("timestamp", DateUtil.toISOString(now))
|
||||
|
|
|
@ -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.IobCobCalculatorPlugin.Companion.percentile
|
||||
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.sharedPreferences.SP
|
||||
import org.json.JSONException
|
||||
|
|
|
@ -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.IobCobCalculatorPlugin.Companion.percentile
|
||||
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.sharedPreferences.SP
|
||||
import org.json.JSONException
|
||||
|
|
|
@ -18,7 +18,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
|
|||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
|
||||
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.sharedPreferences.SP
|
||||
import org.json.JSONException
|
||||
|
|
|
@ -24,9 +24,9 @@ import info.nightscout.androidaps.utils.DateUtil
|
|||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
|
||||
import info.nightscout.androidaps.utils.extensions.directionToIcon
|
||||
import info.nightscout.androidaps.utils.extensions.toVisibility
|
||||
import info.nightscout.androidaps.utils.extensions.valueToUnitsString
|
||||
import info.nightscout.androidaps.extensions.directionToIcon
|
||||
import info.nightscout.androidaps.extensions.toVisibility
|
||||
import info.nightscout.androidaps.extensions.valueToUnitsString
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
|
|
@ -21,15 +21,12 @@ import info.nightscout.androidaps.interfaces.PluginDescription
|
|||
import info.nightscout.androidaps.interfaces.PluginType
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
|
||||
import info.nightscout.androidaps.receivers.DataWorker
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.utils.XDripBroadcast
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
|
@ -73,10 +70,6 @@ class DexcomPlugin @Inject constructor(
|
|||
dexcomMediator.requestPermissionIfNeeded()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
// cannot be inner class because of needed injection
|
||||
class DexcomWorker(
|
||||
context: Context,
|
||||
|
|
|
@ -57,6 +57,9 @@ class RandomBgPlugin @Inject constructor(
|
|||
companion object {
|
||||
|
||||
const val interval = 5L // minutes
|
||||
const val min = 70 // mgdl
|
||||
const val max = 190 // mgdl
|
||||
const val period = 30.0 // minutes
|
||||
}
|
||||
|
||||
init {
|
||||
|
@ -93,12 +96,10 @@ class RandomBgPlugin @Inject constructor(
|
|||
|
||||
private fun handleNewData() {
|
||||
if (!isEnabled(PluginType.BGSOURCE)) return
|
||||
val min = 70
|
||||
val max = 190
|
||||
|
||||
val cal = GregorianCalendar()
|
||||
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>()
|
||||
glucoseValues += CgmSourceTransaction.TransactionGlucoseValue(
|
||||
|
|
|
@ -15,7 +15,6 @@ import info.nightscout.androidaps.interfaces.PluginDescription
|
|||
import info.nightscout.androidaps.interfaces.PluginType
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -49,7 +48,6 @@ class TomatoPlugin @Inject constructor(
|
|||
@Inject lateinit var tomatoPlugin: TomatoPlugin
|
||||
@Inject lateinit var aapsLogger: AAPSLogger
|
||||
@Inject lateinit var sp: SP
|
||||
@Inject lateinit var nsUpload: NSUpload
|
||||
@Inject lateinit var repository: AppRepository
|
||||
@Inject lateinit var broadcastToXDrip: XDripBroadcast
|
||||
|
||||
|
|
|
@ -11,11 +11,13 @@ import info.nightscout.androidaps.R
|
|||
import info.nightscout.androidaps.databinding.TreatmentsFragmentBinding
|
||||
import info.nightscout.androidaps.events.EventExtendedBolusChange
|
||||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.plugins.treatments.fragments.*
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
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.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
@ -28,9 +30,10 @@ class TreatmentsFragment : DaggerFragment() {
|
|||
@Inject lateinit var resourceHelper: ResourceHelper
|
||||
@Inject lateinit var fabricPrivacy: FabricPrivacy
|
||||
@Inject lateinit var activePlugin: ActivePluginProvider
|
||||
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var aapsSchedulers: AapsSchedulers
|
||||
@Inject lateinit var buildHelper: BuildHelper
|
||||
@Inject lateinit var dateUtil: DateUtil
|
||||
|
||||
private val disposable = CompositeDisposable()
|
||||
|
||||
|
@ -124,6 +127,6 @@ class TreatmentsFragment : DaggerFragment() {
|
|||
|
||||
private fun updateGui() {
|
||||
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()
|
||||
}
|
||||
}
|
|
@ -1,13 +1,10 @@
|
|||
package info.nightscout.androidaps.plugins.treatments;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.google.firebase.analytics.FirebaseAnalytics;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
@ -17,25 +14,15 @@ import javax.inject.Singleton;
|
|||
import dagger.android.HasAndroidInjector;
|
||||
import info.nightscout.androidaps.Constants;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.activities.ErrorHelperActivity;
|
||||
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.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.ProfileSwitch;
|
||||
import info.nightscout.androidaps.db.Source;
|
||||
import info.nightscout.androidaps.db.TemporaryBasal;
|
||||
import info.nightscout.androidaps.db.Treatment;
|
||||
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.DatabaseHelperInterface;
|
||||
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.ProfileFunction;
|
||||
import info.nightscout.androidaps.interfaces.ProfileStore;
|
||||
import info.nightscout.androidaps.interfaces.PumpInterface;
|
||||
import info.nightscout.androidaps.interfaces.TreatmentServiceInterface;
|
||||
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.LTag;
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
|
||||
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
|
||||
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
|
||||
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.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.rx.AapsSchedulers;
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP;
|
||||
|
@ -78,7 +56,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
private final ProfileFunction profileFunction;
|
||||
private final ActivePluginProvider activePlugin;
|
||||
private final NSUpload nsUpload;
|
||||
private final UploadQueueInterface uploadQueue;
|
||||
private final FabricPrivacy fabricPrivacy;
|
||||
private final DateUtil dateUtil;
|
||||
private final DatabaseHelperInterface databaseHelper;
|
||||
|
@ -88,8 +65,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
|
||||
protected TreatmentServiceInterface service;
|
||||
|
||||
private final Intervals<TemporaryBasal> tempBasals = new NonOverlappingIntervals<>();
|
||||
private final Intervals<ExtendedBolus> extendedBoluses = new NonOverlappingIntervals<>();
|
||||
private final ProfileIntervals<ProfileSwitch> profiles = new ProfileIntervals<>();
|
||||
|
||||
@Inject
|
||||
|
@ -106,7 +81,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
NSUpload nsUpload,
|
||||
FabricPrivacy fabricPrivacy,
|
||||
DateUtil dateUtil,
|
||||
UploadQueueInterface uploadQueue,
|
||||
DatabaseHelperInterface databaseHelper,
|
||||
AppRepository repository
|
||||
) {
|
||||
|
@ -131,7 +105,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
this.fabricPrivacy = fabricPrivacy;
|
||||
this.dateUtil = dateUtil;
|
||||
this.nsUpload = nsUpload;
|
||||
this.uploadQueue = uploadQueue;
|
||||
this.databaseHelper = databaseHelper;
|
||||
this.repository = repository;
|
||||
}
|
||||
|
@ -141,32 +114,12 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
this.service = new TreatmentService(getInjector());
|
||||
initializeData(range());
|
||||
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
|
||||
.toObservable(EventReloadProfileSwitchData.class)
|
||||
.observeOn(aapsSchedulers.getIo())
|
||||
.subscribe(event -> initializeProfileSwitchData(range()),
|
||||
fabricPrivacy::logException
|
||||
));
|
||||
disposable.add(rxBus
|
||||
.toObservable(EventReloadTempBasalData.class)
|
||||
.observeOn(aapsSchedulers.getIo())
|
||||
.subscribe(event -> {
|
||||
getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTempBasalData");
|
||||
initializeTempBasalData(range());
|
||||
},
|
||||
fabricPrivacy::logException
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -188,27 +141,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
}
|
||||
|
||||
public void initializeData(long range) {
|
||||
initializeTempBasalData(range);
|
||||
initializeExtendedBolusData(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) {
|
||||
getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData");
|
||||
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
|
||||
* 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
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) {
|
||||
throw new IllegalStateException("Migrate to new DB");
|
||||
//log.debug("Adding new ExtentedBolus record" + extendedBolus.log());
|
||||
/*
|
||||
boolean newRecordCreated = databaseHelper.createOrUpdate(extendedBolus);
|
||||
if (newRecordCreated) {
|
||||
if (extendedBolus.durationInMinutes == 0) {
|
||||
|
@ -525,26 +239,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
nsUpload.uploadExtendedBolus(extendedBolus);
|
||||
}
|
||||
return newRecordCreated;
|
||||
*/
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Intervals<ExtendedBolus> getExtendedBolusesFromHistory() {
|
||||
synchronized (extendedBoluses) {
|
||||
return new NonOverlappingIntervals<>(extendedBoluses);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public NonOverlappingIntervals<TemporaryBasal> getTemporaryBasalsFromHistory() {
|
||||
synchronized (tempBasals) {
|
||||
return new NonOverlappingIntervals<>(tempBasals);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) {
|
||||
throw new IllegalStateException("Migrate to new DB");
|
||||
/*
|
||||
//log.debug("Adding new TemporaryBasal record" + tempBasal.toString());
|
||||
boolean newRecordCreated = databaseHelper.createOrUpdate(tempBasal);
|
||||
if (newRecordCreated) {
|
||||
|
@ -556,17 +258,25 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date));
|
||||
}
|
||||
return newRecordCreated;
|
||||
*/
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) {
|
||||
throw new IllegalStateException("Migrate to new DB");
|
||||
/*
|
||||
UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout);
|
||||
|
||||
return new TreatmentUpdateReturn(resultRecord.getSuccess(), resultRecord.getNewRecord());
|
||||
*/
|
||||
}
|
||||
|
||||
// return true if new record is created
|
||||
@Deprecated
|
||||
@Override
|
||||
public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) {
|
||||
throw new IllegalStateException("Migrate to new DB");
|
||||
/*
|
||||
boolean medtronicPump = activePlugin.getActivePump() instanceof MedtronicPumpPlugin;
|
||||
|
||||
getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump);
|
||||
|
@ -627,27 +337,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
|
|||
}
|
||||
|
||||
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
|
||||
|
|
|
@ -28,7 +28,6 @@ import info.nightscout.androidaps.logging.AAPSLogger
|
|||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.logging.UserEntryLogger
|
||||
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.treatments.events.EventTreatmentUpdateGui
|
||||
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.alertDialogs.OKDialog
|
||||
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
|
||||
import info.nightscout.androidaps.utils.extensions.iobCalc
|
||||
import info.nightscout.androidaps.utils.extensions.toVisibility
|
||||
import info.nightscout.androidaps.extensions.iobCalc
|
||||
import info.nightscout.androidaps.extensions.toVisibility
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -274,7 +273,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
|
|||
ml.bolus?.let { bolus ->
|
||||
holder.binding.bolusDate.text = dateUtil.timeString(bolus.timestamp)
|
||||
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.bolusInvalid.visibility = bolus.isValid.not().toVisibility()
|
||||
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)
|
||||
holder.binding.mealOrCorrection.text =
|
||||
when (ml.bolus.type) {
|
||||
Bolus.Type.SMB -> "SMB"
|
||||
Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus)
|
||||
Bolus.Type.SMB -> "SMB"
|
||||
Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus)
|
||||
Bolus.Type.PRIMING -> resourceHelper.gs(R.string.prime)
|
||||
}
|
||||
}
|
||||
|
@ -293,8 +292,8 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
|
|||
ml.carbs?.let { carbs ->
|
||||
holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp)
|
||||
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.carbsNs.visibility = (NSUpload.isIdValid(carbs.interfaceIDs.nightscoutId)).toVisibility()
|
||||
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 = (carbs.interfaceIDs.nightscoutId != null).toVisibility()
|
||||
holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility()
|
||||
holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility()
|
||||
}
|
||||
|
|
|
@ -32,7 +32,7 @@ import info.nightscout.androidaps.utils.T
|
|||
import info.nightscout.androidaps.utils.Translator
|
||||
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
|
|
@ -11,45 +11,52 @@ import androidx.recyclerview.widget.LinearLayoutManager
|
|||
import androidx.recyclerview.widget.RecyclerView
|
||||
import dagger.android.support.DaggerFragment
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.data.Intervals
|
||||
import info.nightscout.androidaps.database.entities.UserEntry.*
|
||||
import info.nightscout.androidaps.database.AppRepository
|
||||
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.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.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
|
||||
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.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.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.T
|
||||
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.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Inject
|
||||
|
||||
class TreatmentsExtendedBolusesFragment : DaggerFragment() {
|
||||
|
||||
private val disposable = CompositeDisposable()
|
||||
|
||||
private val millsToThePast = T.days(30).msecs()
|
||||
|
||||
@Inject lateinit var activePlugin: ActivePluginProvider
|
||||
@Inject lateinit var rxBus: RxBusWrapper
|
||||
@Inject lateinit var resourceHelper: ResourceHelper
|
||||
@Inject lateinit var aapsLogger: AAPSLogger
|
||||
@Inject lateinit var fabricPrivacy: FabricPrivacy
|
||||
@Inject lateinit var nsUpload: NSUpload
|
||||
@Inject lateinit var uploadQueue: UploadQueueInterface
|
||||
@Inject lateinit var profileFunction: ProfileFunction
|
||||
@Inject lateinit var dateUtil: DateUtil
|
||||
@Inject lateinit var aapsSchedulers: AapsSchedulers
|
||||
@Inject lateinit var databaseHelper: DatabaseHelperInterface
|
||||
@Inject lateinit var uel: UserEntryLogger
|
||||
@Inject lateinit var repository: AppRepository
|
||||
|
||||
private var _binding: TreatmentsExtendedbolusFragmentBinding? = null
|
||||
|
||||
|
@ -58,18 +65,54 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
|
|||
private val binding get() = _binding!!
|
||||
|
||||
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
|
||||
savedInstanceState: Bundle?): View {
|
||||
_binding = TreatmentsExtendedbolusFragmentBinding.inflate(inflater, container, false)
|
||||
return binding.root
|
||||
}
|
||||
savedInstanceState: Bundle?): View =
|
||||
TreatmentsExtendedbolusFragmentBinding.inflate(inflater, container, false).also { _binding = it }.root
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
binding.recyclerview.setHasFixedSize(true)
|
||||
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 {
|
||||
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) {
|
||||
val extendedBolus = extendedBolusList.getReversed(position)
|
||||
holder.binding.ph.visibility = if (extendedBolus.source == Source.PUMP) View.VISIBLE else View.GONE
|
||||
holder.binding.ns.visibility = if (NSUpload.isIdValid(extendedBolus._id)) View.VISIBLE else View.GONE
|
||||
if (extendedBolus.isEndingEvent) {
|
||||
holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.date)
|
||||
holder.binding.duration.text = resourceHelper.gs(R.string.cancel)
|
||||
holder.binding.insulin.text = ""
|
||||
holder.binding.realDuration.text = ""
|
||||
holder.binding.iob.text = ""
|
||||
holder.binding.insulinSoFar.text = ""
|
||||
holder.binding.ratio.text = ""
|
||||
val extendedBolus = extendedBolusList[position]
|
||||
holder.binding.ph.visibility = (extendedBolus.interfaceIDs.nightscoutId != null).toVisibility()
|
||||
holder.binding.invalid.visibility = extendedBolus.isValid.not().toVisibility()
|
||||
@SuppressLint("SetTextI18n")
|
||||
if (extendedBolus.isInProgress(dateUtil)) {
|
||||
holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp)
|
||||
holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive))
|
||||
} else {
|
||||
@SuppressLint("SetTextI18n")
|
||||
if (extendedBolus.isInProgress) holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.date)
|
||||
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)
|
||||
holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp) + " - " + dateUtil.timeString(extendedBolus.end)
|
||||
holder.binding.date.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
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int {
|
||||
return extendedBolusList.size()
|
||||
}
|
||||
override fun getItemCount(): Int = extendedBolusList.size
|
||||
|
||||
inner class ExtendedBolusesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
|
||||
|
||||
|
@ -117,17 +150,17 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
|
|||
init {
|
||||
binding.remove.setOnClickListener { v: View ->
|
||||
val extendedBolus = v.tag as ExtendedBolus
|
||||
context?.let {
|
||||
OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord),
|
||||
context?.let { context ->
|
||||
OKDialog.showConfirmation(context, resourceHelper.gs(R.string.removerecord),
|
||||
"""
|
||||
${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 ->
|
||||
uel.log(Action.EXTENDED_BOLUS_REMOVED)
|
||||
val id = extendedBolus._id
|
||||
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
|
||||
else uploadQueue.removeByMongoId("dbAdd", id)
|
||||
databaseHelper.delete(extendedBolus)
|
||||
disposable += repository.runTransactionForResult(InvalidateExtendedBolusTransaction(extendedBolus.id))
|
||||
.subscribe(
|
||||
{ aapsLogger.debug(LTag.DATABASE, "Removed extended bolus $extendedBolus") },
|
||||
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating extended bolus", it) })
|
||||
}, 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)
|
||||
}
|
||||
}
|
|
@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
|
|||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
|
||||
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.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
|
|
@ -37,10 +37,10 @@ import info.nightscout.androidaps.utils.T
|
|||
import info.nightscout.androidaps.utils.Translator
|
||||
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
|
||||
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
|
||||
import info.nightscout.androidaps.utils.extensions.friendlyDescription
|
||||
import info.nightscout.androidaps.utils.extensions.highValueToUnitsToString
|
||||
import info.nightscout.androidaps.utils.extensions.lowValueToUnitsToString
|
||||
import info.nightscout.androidaps.utils.extensions.toVisibility
|
||||
import info.nightscout.androidaps.extensions.friendlyDescription
|
||||
import info.nightscout.androidaps.extensions.highValueToUnitsToString
|
||||
import info.nightscout.androidaps.extensions.lowValueToUnitsToString
|
||||
import info.nightscout.androidaps.extensions.toVisibility
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.androidaps.utils.sharedPreferences.SP
|
||||
|
@ -151,7 +151,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
|
|||
_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 currentlyActiveTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null
|
||||
|
|
|
@ -10,33 +10,43 @@ import androidx.recyclerview.widget.LinearLayoutManager
|
|||
import androidx.recyclerview.widget.RecyclerView
|
||||
import dagger.android.support.DaggerFragment
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.data.Intervals
|
||||
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.interfaces.end
|
||||
import info.nightscout.androidaps.database.transactions.InvalidateTemporaryBasalTransaction
|
||||
import info.nightscout.androidaps.databinding.TreatmentsTempbasalsFragmentBinding
|
||||
import info.nightscout.androidaps.databinding.TreatmentsTempbasalsItemBinding
|
||||
import info.nightscout.androidaps.db.Source
|
||||
import info.nightscout.androidaps.db.TemporaryBasal
|
||||
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
|
||||
import info.nightscout.androidaps.events.EventTempBasalChange
|
||||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.logging.LTag
|
||||
import info.nightscout.androidaps.logging.UserEntryLogger
|
||||
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.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.T
|
||||
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.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.abs
|
||||
|
||||
class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
|
||||
|
||||
private val disposable = CompositeDisposable()
|
||||
|
||||
@Inject lateinit var aapsLogger: AAPSLogger
|
||||
@Inject lateinit var rxBus: RxBusWrapper
|
||||
@Inject lateinit var resourceHelper: ResourceHelper
|
||||
@Inject lateinit var fabricPrivacy: FabricPrivacy
|
||||
|
@ -45,9 +55,12 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
|
|||
@Inject lateinit var dateUtil: DateUtil
|
||||
@Inject lateinit var aapsSchedulers: AapsSchedulers
|
||||
@Inject lateinit var uel: UserEntryLogger
|
||||
@Inject lateinit var repository: AppRepository
|
||||
|
||||
private var _binding: TreatmentsTempbasalsFragmentBinding? = null
|
||||
|
||||
private val millsToThePast = T.days(30).msecs()
|
||||
|
||||
// This property is only valid between onCreateView and
|
||||
// onDestroyView.
|
||||
private val binding get() = _binding!!
|
||||
|
@ -59,23 +72,37 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
|
|||
super.onViewCreated(view, savedInstanceState)
|
||||
binding.recyclerview.setHasFixedSize(true)
|
||||
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
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
swapAdapter()
|
||||
|
||||
disposable.add(rxBus
|
||||
.toObservable(EventTempBasalChange::class.java)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.subscribe({ updateGui() }, fabricPrivacy::logException)
|
||||
.subscribe({ swapAdapter() }, fabricPrivacy::logException)
|
||||
)
|
||||
disposable.add(rxBus
|
||||
.toObservable(EventAutosensCalculationFinished::class.java)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.subscribe({ updateGui() }, fabricPrivacy::logException)
|
||||
.subscribe({ swapAdapter() }, fabricPrivacy::logException)
|
||||
)
|
||||
updateGui()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
|
@ -87,69 +114,44 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
|
|||
@Synchronized
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
binding.recyclerview.adapter = null // avoid leaks
|
||||
_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 =
|
||||
TempBasalsViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_tempbasals_item, viewGroup, false))
|
||||
|
||||
override fun onBindViewHolder(holder: TempBasalsViewHolder, position: Int) {
|
||||
val tempBasal = tempBasalList.getReversed(position)
|
||||
holder.binding.ph.visibility = if (tempBasal.source == Source.PUMP) View.VISIBLE else View.GONE
|
||||
holder.binding.ns.visibility = if (NSUpload.isIdValid(tempBasal._id)) View.VISIBLE else View.GONE
|
||||
if (tempBasal.isEndingEvent) {
|
||||
holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.date)
|
||||
holder.binding.duration.text = resourceHelper.gs(R.string.cancel)
|
||||
holder.binding.absolute.text = ""
|
||||
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)
|
||||
val tempBasal = tempBasalList[position]
|
||||
holder.binding.ns.visibility = (tempBasal.interfaceIDs.nightscoutId != null).toVisibility()
|
||||
holder.binding.invalid.visibility = tempBasal.isValid.not().toVisibility()
|
||||
holder.binding.ph.visibility = (tempBasal.interfaceIDs.pumpId != null).toVisibility()
|
||||
if (tempBasal.isInProgress) {
|
||||
holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.timestamp)
|
||||
holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive))
|
||||
} else {
|
||||
if (tempBasal.isInProgress) {
|
||||
holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.date)
|
||||
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.date.text = dateUtil.dateAndTimeRangeString(tempBasal.timestamp, tempBasal.end)
|
||||
holder.binding.date.setTextColor(holder.binding.duration.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
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int {
|
||||
return tempBasalList.size()
|
||||
}
|
||||
override fun getItemCount(): Int = tempBasalList.size
|
||||
|
||||
@Deprecated("remove remove functionality after finish")
|
||||
inner class TempBasalsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
|
||||
|
||||
val binding = TreatmentsTempbasalsItemBinding.bind(itemView)
|
||||
|
@ -157,15 +159,20 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
|
|||
init {
|
||||
binding.remove.setOnClickListener { v: View ->
|
||||
val tempBasal = v.tag as TemporaryBasal
|
||||
val profile = profileFunction.getProfile(dateUtil._now())
|
||||
?: return@setOnClickListener
|
||||
context?.let {
|
||||
OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord),
|
||||
"""
|
||||
${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull()}
|
||||
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.date)}
|
||||
${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull(profile, dateUtil)}
|
||||
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)}
|
||||
""".trimIndent(),
|
||||
{ _: DialogInterface?, _: Int ->
|
||||
uel.log(Action.TT_REMOVED, ValueWithUnit(tempBasal.date, Units.Timestamp))
|
||||
activePlugin.activeTreatments.removeTempBasal(tempBasal)
|
||||
uel.log(Action.TB_REMOVED, ValueWithUnit(tempBasal.timestamp, Units.Timestamp))
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
|
@ -15,6 +15,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.*
|
|||
import info.nightscout.androidaps.databinding.TreatmentsUserEntryFragmentBinding
|
||||
import info.nightscout.androidaps.databinding.TreatmentsUserEntryItemBinding
|
||||
import info.nightscout.androidaps.events.EventPreferenceChange
|
||||
import info.nightscout.androidaps.extensions.colorId
|
||||
import info.nightscout.androidaps.interfaces.ImportExportPrefsInterface
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.UserEntryLogger
|
||||
|
|
|
@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.DateUtil
|
|||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.LocalAlertUtils
|
||||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.utils.extensions.buildDeviceStatus
|
||||
import info.nightscout.androidaps.extensions.buildDeviceStatus
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.abs
|
||||
|
||||
|
|
|
@ -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.PrefsStatus
|
||||
import info.nightscout.androidaps.utils.ToastUtils
|
||||
import info.nightscout.androidaps.utils.extensions.runOnUiThread
|
||||
import info.nightscout.androidaps.extensions.runOnUiThread
|
||||
import java.util.*
|
||||
|
||||
object PrefImportSummaryDialog {
|
||||
|
|
|
@ -9,7 +9,7 @@ import android.view.View
|
|||
import android.widget.TextView
|
||||
import androidx.annotation.DrawableRes
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.utils.extensions.runOnUiThread
|
||||
import info.nightscout.androidaps.extensions.runOnUiThread
|
||||
|
||||
object TwoMessagesAlertDialog {
|
||||
|
||||
|
|
|
@ -1,71 +1,48 @@
|
|||
package info.nightscout.androidaps.utils.stats
|
||||
|
||||
import android.content.Context
|
||||
import android.text.Spanned
|
||||
import android.util.LongSparseArray
|
||||
import dagger.android.HasAndroidInjector
|
||||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.database.AppRepository
|
||||
import info.nightscout.androidaps.database.entities.Bolus
|
||||
import info.nightscout.androidaps.db.TDD
|
||||
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.UploadQueueInterface
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
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.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.HtmlHelper
|
||||
import info.nightscout.androidaps.utils.MidnightTime
|
||||
import info.nightscout.androidaps.utils.T
|
||||
import info.nightscout.androidaps.extensions.convertedToAbsolute
|
||||
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
|
||||
|
||||
class TddCalculator @Inject constructor(
|
||||
injector: HasAndroidInjector,
|
||||
aapsLogger: AAPSLogger,
|
||||
rxBus: RxBusWrapper,
|
||||
resourceHelper: ResourceHelper,
|
||||
context: Context,
|
||||
aapsSchedulers: AapsSchedulers,
|
||||
sp: SP,
|
||||
private val aapsLogger: AAPSLogger,
|
||||
private val resourceHelper: ResourceHelper,
|
||||
private val activePlugin: ActivePluginProvider,
|
||||
private val profileFunction: ProfileFunction,
|
||||
fabricPrivacy: FabricPrivacy,
|
||||
nsUpload: NSUpload,
|
||||
private val dateUtil: DateUtil,
|
||||
uploadQueue: UploadQueueInterface,
|
||||
databaseHelper: DatabaseHelperInterface,
|
||||
private val iobCobCalculator: IobCobCalculator,
|
||||
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> {
|
||||
val range = T.days(days + 1).msecs()
|
||||
val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs())
|
||||
val endTime = MidnightTime.calc(DateUtil.now())
|
||||
initializeData(range)
|
||||
|
||||
val result = LongSparseArray<TDD>()
|
||||
repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet()
|
||||
.filter { it.type != Bolus.Type.PRIMING }
|
||||
.forEach { t->
|
||||
val midnight = MidnightTime.calc(t.timestamp)
|
||||
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
|
||||
tdd.bolus += t.amount
|
||||
result.put(midnight, tdd)
|
||||
}
|
||||
repository.getCarbsDataFromTimeToTimeExpanded(startTime, endTime, true).blockingGet().forEach { t->
|
||||
.forEach { t ->
|
||||
val midnight = MidnightTime.calc(t.timestamp)
|
||||
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
|
||||
tdd.bolus += t.amount
|
||||
result.put(midnight, tdd)
|
||||
}
|
||||
repository.getCarbsDataFromTimeToTimeExpanded(startTime, endTime, true).blockingGet().forEach { t ->
|
||||
val midnight = MidnightTime.calc(t.timestamp)
|
||||
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
|
||||
tdd.carbs += t.amount
|
||||
|
@ -75,15 +52,15 @@ class TddCalculator @Inject constructor(
|
|||
for (t in startTime until endTime step T.mins(5).msecs()) {
|
||||
val midnight = MidnightTime.calc(t)
|
||||
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
|
||||
val tbr = getTempBasalFromHistory(t)
|
||||
val profile = profileFunction.getProfile(t, this) ?: continue
|
||||
val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t)
|
||||
val tbr = iobCobCalculator.getTempBasalIncludingConvertedExtended(t)
|
||||
val profile = profileFunction.getProfile(t) ?: continue
|
||||
val absoluteRate = tbr?.convertedToAbsolute(t, profile) ?: profile.getBasal(t)
|
||||
tdd.basal += absoluteRate / 60.0 * 5.0
|
||||
|
||||
if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) {
|
||||
// they are not included in TBRs
|
||||
val eb = getExtendedBolusFromHistory(t)
|
||||
val absoluteEbRate = eb?.absoluteRate() ?: 0.0
|
||||
val eb = iobCobCalculator.getExtendedBolus(t)
|
||||
val absoluteEbRate = eb?.rate ?: 0.0
|
||||
tdd.bolus += absoluteEbRate / 60.0 * 5.0
|
||||
}
|
||||
result.put(midnight, tdd)
|
||||
|
|
|
@ -23,7 +23,6 @@ import info.nightscout.androidaps.logging.UserEntryLogger
|
|||
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
|
||||
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
|
||||
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
|
||||
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
|
||||
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.T
|
||||
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.sharedPreferences.SP
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
@ -62,7 +61,6 @@ class BolusWizard @Inject constructor(
|
|||
@Inject lateinit var carbTimer: CarbTimer
|
||||
@Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider
|
||||
@Inject lateinit var repository: AppRepository
|
||||
@Inject lateinit var nsUpload: NSUpload
|
||||
|
||||
private val disposable = CompositeDisposable()
|
||||
|
||||
|
@ -205,7 +203,7 @@ class BolusWizard @Inject constructor(
|
|||
// Insulin from IOB
|
||||
// IOB calculation
|
||||
val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
|
||||
val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round()
|
||||
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
|
||||
|
||||
insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0
|
||||
insulinFromBasalIOB = if (includeBasalIOB) -basalIob.basaliob else 0.0
|
||||
|
|
|
@ -6,16 +6,15 @@ import info.nightscout.androidaps.data.Profile
|
|||
import info.nightscout.androidaps.database.AppRepository
|
||||
import info.nightscout.androidaps.database.ValueWrapper
|
||||
import info.nightscout.androidaps.database.entities.GlucoseValue
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
|
||||
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.JsonHelper.safeGetInt
|
||||
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 org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
@ -27,9 +26,8 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
|
|||
@Inject lateinit var aapsLogger: AAPSLogger
|
||||
@Inject lateinit var sp: SP
|
||||
@Inject lateinit var profileFunction: ProfileFunction
|
||||
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Inject lateinit var loopPlugin: LoopPlugin
|
||||
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
|
||||
@Inject lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Inject lateinit var repository: AppRepository
|
||||
@Inject lateinit var dateUtil: DateUtil
|
||||
@Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider
|
||||
|
@ -89,7 +87,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
|
|||
// COB
|
||||
var cob = 0.0
|
||||
if (useCOB() == YES) {
|
||||
val cobInfo = iobCobCalculatorPlugin.getCobInfo(_synchronized, "QuickWizard COB")
|
||||
val cobInfo = iobCobCalculator.getCobInfo(_synchronized, "QuickWizard COB")
|
||||
if (cobInfo.displayCob != null) cob = cobInfo.displayCob!!
|
||||
}
|
||||
// Bolus IOB
|
||||
|
@ -98,7 +96,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
|
|||
bolusIOB = true
|
||||
}
|
||||
// Basal IOB
|
||||
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round()
|
||||
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
|
||||
var basalIOB = false
|
||||
if (useBasalIOB() == YES) {
|
||||
basalIOB = true
|
||||
|
|
|
@ -141,8 +141,6 @@
|
|||
|
||||
</LinearLayout>
|
||||
|
||||
<include layout="@layout/datetime" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
|
|
|
@ -1,10 +1,34 @@
|
|||
<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"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
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
|
||||
android:id="@+id/recyclerview"
|
||||
android:layout_width="match_parent"
|
||||
|
|
|
@ -55,73 +55,9 @@
|
|||
android:textAppearance="?android:attr/textAppearanceSmall"
|
||||
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/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_weight="1"
|
||||
android:text="" />
|
||||
|
@ -156,6 +92,25 @@
|
|||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="top"
|
||||
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:text="@string/tempbasals_iob_label_string"
|
||||
android:textAppearance="?android:attr/textAppearanceSmall" />
|
||||
|
@ -171,15 +126,35 @@
|
|||
tools:ignore="HardcodedText" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/remove"
|
||||
android:layout_width="0dp"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginEnd="10dp"
|
||||
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:textAlignment="viewEnd"
|
||||
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>
|
||||
|
||||
<View
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
<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"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
|
@ -9,26 +10,24 @@
|
|||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="10dp"
|
||||
android:paddingBottom="10dp">
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
<CheckBox
|
||||
android:id="@+id/show_invalidated"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="10dp"
|
||||
android:text="@string/tempbasals_iobtotal_label_string"
|
||||
android:textAppearance="?android:attr/textAppearanceSmall"
|
||||
android:layout_gravity="end|center_vertical"
|
||||
android:checked="false"
|
||||
android:paddingEnd="5dp"
|
||||
tools:ignore="RtlSymmetry" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/total_temp_iob"
|
||||
<ImageView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="10dp"
|
||||
android:textAppearance="?android:attr/textAppearanceSmall"
|
||||
android:textStyle="bold"
|
||||
tools:ignore="RtlSymmetry" />
|
||||
android:layout_gravity="center_vertical"
|
||||
android:contentDescription="@string/show_removed"
|
||||
app:srcCompat="@drawable/ic_visibility" />
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
|
|
@ -38,16 +38,7 @@
|
|||
tools:ignore="HardcodedText" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/absolute"
|
||||
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:id="@+id/rate"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingStart="10dp"
|
||||
|
@ -65,93 +56,24 @@
|
|||
tools:ignore="HardcodedText,RtlSymmetry" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/extended_flag"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:gravity="end"
|
||||
android:paddingEnd="5dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/extended_flag"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="5dp"
|
||||
android:text="E"
|
||||
android:textColor="@color/colorSetExtendedButton"
|
||||
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
|
||||
android:id="@+id/ph"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginEnd="10dp"
|
||||
android:layout_marginStart="5dp"
|
||||
android:text="PH"
|
||||
android:textColor="@color/colorSetTempButton"
|
||||
tools:ignore="HardcodedText" />
|
||||
|
@ -160,11 +82,17 @@
|
|||
android:id="@+id/ns"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginEnd="10dp"
|
||||
android:layout_marginStart="5dp"
|
||||
android:text="NS"
|
||||
android:textColor="@color/colorSetTempButton"
|
||||
tools:ignore="HardcodedText" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginEnd="10dp"
|
||||
tools:ignore="RtlSymmetry" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
|
@ -192,24 +120,51 @@
|
|||
tools:ignore="HardcodedText" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/remove"
|
||||
android:layout_width="0dp"
|
||||
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:textAlignment="viewEnd"
|
||||
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>
|
||||
|
||||
<View
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="2dip"
|
||||
android:layout_marginBottom="5dp"
|
||||
android:layout_marginLeft="5dp"
|
||||
android:layout_marginRight="5dp"
|
||||
android:layout_marginTop="5dp"
|
||||
android:layout_marginRight="5dp"
|
||||
android:layout_marginBottom="5dp"
|
||||
android:background="@color/list_delimiter" />
|
||||
|
||||
</LinearLayout>
|
||||
|
|
|
@ -38,7 +38,6 @@
|
|||
android:contentDescription="@string/show_removed"
|
||||
app:srcCompat="@drawable/ic_visibility" />
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
|
|
|
@ -44,6 +44,8 @@
|
|||
<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_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_maxbolus_title">Max allowed bolus [U]</string>
|
||||
|
|
|
@ -4,11 +4,7 @@ import dagger.android.AndroidInjector
|
|||
import dagger.android.HasAndroidInjector
|
||||
import info.nightscout.androidaps.data.Profile
|
||||
import info.nightscout.androidaps.db.ProfileSwitch
|
||||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
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.interfaces.*
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.DefaultValueHelper
|
||||
|
@ -26,6 +22,7 @@ open class TestBaseWithProfile : TestBase() {
|
|||
@Mock lateinit var activePluginProvider: ActivePluginProvider
|
||||
@Mock lateinit var resourceHelper: ResourceHelper
|
||||
@Mock lateinit var treatmentsInterface: TreatmentsInterface
|
||||
@Mock lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Mock lateinit var fabricPrivacy: FabricPrivacy
|
||||
@Mock lateinit var profileFunction: ProfileFunction
|
||||
@Mock lateinit var defaultValueHelper: DefaultValueHelper
|
||||
|
|
|
@ -6,6 +6,7 @@ import info.nightscout.androidaps.data.Profile
|
|||
import info.nightscout.androidaps.data.PumpEnactResult
|
||||
import info.nightscout.androidaps.interfaces.PumpDescription
|
||||
import info.nightscout.androidaps.interfaces.PumpInterface
|
||||
import info.nightscout.androidaps.interfaces.PumpSync
|
||||
import info.nightscout.androidaps.plugins.common.ManufacturerType
|
||||
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
|
||||
import info.nightscout.androidaps.utils.TimeChangeType
|
||||
|
@ -50,8 +51,8 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : PumpInterface {
|
|||
override val batteryLevel: Int = 0
|
||||
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
|
||||
override fun stopBolusDelivering() {}
|
||||
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
|
||||
override fun setTempBasalPercent(percent: Int, 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, tbrType: PumpSync.TemporaryBasalType): 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 cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
|
||||
|
|
|
@ -30,13 +30,12 @@ class QuickWizardTest : TestBase() {
|
|||
@Mock lateinit var profileFunction: ProfileFunction
|
||||
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Mock lateinit var loopPlugin: LoopPlugin
|
||||
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
|
||||
|
||||
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}"
|
||||
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}"
|
||||
var array: JSONArray = JSONArray("[$data1,$data2]")
|
||||
private var array: JSONArray = JSONArray("[$data1,$data2]")
|
||||
|
||||
val injector = HasAndroidInjector {
|
||||
AndroidInjector {
|
||||
|
@ -44,9 +43,7 @@ class QuickWizardTest : TestBase() {
|
|||
it.aapsLogger = aapsLogger
|
||||
it.sp = sp
|
||||
it.profileFunction = profileFunction
|
||||
it.treatmentsPlugin = treatmentsPlugin
|
||||
it.loopPlugin = loopPlugin
|
||||
it.iobCobCalculatorPlugin = iobCobCalculatorPlugin
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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.pump.combo.ComboPlugin
|
||||
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.virtual.VirtualPumpPlugin
|
||||
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
|
||||
|
@ -61,8 +62,8 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
|
|||
@Mock lateinit var sp: SP
|
||||
@Mock lateinit var commandQueue: CommandQueueProvider
|
||||
@Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
|
||||
@Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage
|
||||
@Mock lateinit var context: Context
|
||||
@Mock lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Mock lateinit var glimpPlugin: GlimpPlugin
|
||||
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
|
||||
@Mock lateinit var profiler: Profiler
|
||||
|
@ -139,16 +140,16 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
|
|||
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)
|
||||
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)
|
||||
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)
|
||||
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, 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)
|
||||
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), treatmentsInterface, Config())
|
||||
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, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider)
|
||||
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), iobCobCalculator, Config(), dateUtil)
|
||||
val constraintsPluginsList = ArrayList<PluginBase>()
|
||||
constraintsPluginsList.add(safetyPlugin)
|
||||
constraintsPluginsList.add(objectivesPlugin)
|
||||
|
|
|
@ -13,7 +13,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
|||
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
|
||||
import info.nightscout.androidaps.plugins.configBuilder.RunningConfiguration
|
||||
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.treatments.TreatmentsPlugin
|
||||
import info.nightscout.androidaps.receivers.ReceiverStatusStore
|
||||
|
@ -44,10 +43,9 @@ class LoopPluginTest : TestBase() {
|
|||
@Mock lateinit var activePlugin: ActivePluginProvider
|
||||
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
|
||||
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
|
||||
@Mock lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Mock lateinit var fabricPrivacy: FabricPrivacy
|
||||
@Mock lateinit var receiverStatusStore: ReceiverStatusStore
|
||||
@Mock lateinit var nsUpload: NSUpload
|
||||
@Mock lateinit var notificationManager: NotificationManager
|
||||
@Mock lateinit var repository: AppRepository
|
||||
@Mock lateinit var dateUtil: DateUtil
|
||||
|
@ -58,7 +56,7 @@ class LoopPluginTest : TestBase() {
|
|||
val injector = HasAndroidInjector { AndroidInjector { } }
|
||||
@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`(context.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(notificationManager)
|
||||
}
|
||||
|
|
|
@ -76,7 +76,7 @@ class SafetyPluginTest : TestBaseWithProfile() {
|
|||
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
|
||||
`when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription)
|
||||
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() {
|
||||
|
|
|
@ -19,7 +19,6 @@ import info.nightscout.androidaps.interfaces.*
|
|||
import info.nightscout.androidaps.logging.UserEntryLogger
|
||||
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
|
||||
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.OneTimePasswordValidationResult
|
||||
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo
|
||||
|
@ -66,14 +65,12 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
|
|||
@Mock lateinit var activePlugin: ActivePluginProvider
|
||||
@Mock lateinit var commandQueue: CommandQueueProvider
|
||||
@Mock lateinit var loopPlugin: LoopPlugin
|
||||
@Mock lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
|
||||
@Mock lateinit var localProfilePlugin: LocalProfilePlugin
|
||||
@Mock lateinit var treatmentService: TreatmentService
|
||||
@Mock lateinit var otp: OneTimePassword
|
||||
@Mock lateinit var xdripCalibrations: XdripCalibrations
|
||||
@Mock lateinit var uel: UserEntryLogger
|
||||
@Mock lateinit var nsUpload: NSUpload
|
||||
@Mock lateinit var repository: AppRepository
|
||||
|
||||
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.run()
|
||||
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 ->
|
||||
val callback = invocation.getArgument<Callback>(4)
|
||||
callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
|
||||
callback.run()
|
||||
null
|
||||
}.`when`(commandQueue).tempBasalAbsolute(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), ArgumentMatchers.any(Callback::class.java))
|
||||
}.`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 ->
|
||||
val callback = invocation.getArgument<Callback>(2)
|
||||
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`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(0))
|
||||
`when`(treatmentsInterface.lastCalculationTempBasals).thenReturn(IobTotal(0))
|
||||
`when`(iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended()).thenReturn(IobTotal(0))
|
||||
`when`(treatmentsInterface.service).thenReturn(treatmentService)
|
||||
|
||||
`when`(activePlugin.activeProfileInterface).thenReturn(localProfilePlugin)
|
||||
|
|
|
@ -11,7 +11,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
|||
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
|
||||
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
|
||||
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
|
||||
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
|
||||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.T
|
||||
|
@ -35,7 +34,6 @@ class IobCobCalculatorPluginTest : TestBase() {
|
|||
@Mock lateinit var resourceHelper: ResourceHelper
|
||||
@Mock lateinit var profileFunction: ProfileFunction
|
||||
@Mock lateinit var activePlugin: ActivePluginProvider
|
||||
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
|
||||
@Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
|
||||
@Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin
|
||||
|
@ -52,7 +50,7 @@ class IobCobCalculatorPluginTest : TestBase() {
|
|||
|
||||
@Before
|
||||
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
|
||||
|
|
|
@ -5,11 +5,11 @@ import info.nightscout.androidaps.Config
|
|||
import info.nightscout.androidaps.R
|
||||
import info.nightscout.androidaps.TestBase
|
||||
import info.nightscout.androidaps.interfaces.CommandQueueProvider
|
||||
import info.nightscout.androidaps.interfaces.IobCobCalculator
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.interfaces.PumpSync
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
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.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
|
@ -32,7 +32,7 @@ class VirtualPumpPluginUTest : TestBase() {
|
|||
@Mock lateinit var resourceHelper: ResourceHelper
|
||||
@Mock lateinit var sp: SP
|
||||
@Mock lateinit var profileFunction: ProfileFunction
|
||||
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin
|
||||
@Mock lateinit var iobCobCalculator: IobCobCalculator
|
||||
@Mock lateinit var commandQueue: CommandQueueProvider
|
||||
@Mock lateinit var dateUtil: DateUtil
|
||||
@Mock lateinit var pumpSync: PumpSync
|
||||
|
@ -41,7 +41,7 @@ class VirtualPumpPluginUTest : TestBase() {
|
|||
|
||||
@Before
|
||||
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
|
||||
|
|
|
@ -48,7 +48,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
private lateinit var insulinOrefRapidActingPlugin: InsulinOrefRapidActingPlugin
|
||||
private lateinit var sot: TreatmentsPlugin
|
||||
|
||||
|
@ -59,7 +59,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
|
|||
`when`(profileFunction.getProfile(ArgumentMatchers.anyLong())).thenReturn(validProfile)
|
||||
`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
|
||||
}
|
||||
|
||||
|
@ -102,4 +102,6 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
|
|||
val iob110pct = sot.getAbsoluteIOBTempBasals(now)
|
||||
Assert.assertEquals(1.1, iob110pct.basaliob / iob100pct.basaliob, 0.0001)
|
||||
}
|
||||
|
||||
*/
|
||||
}
|
|
@ -15,6 +15,7 @@ import info.nightscout.androidaps.database.entities.Bolus
|
|||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.Constraint
|
||||
import info.nightscout.androidaps.interfaces.ProfileFunction
|
||||
import info.nightscout.androidaps.interfaces.PumpSync
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
|
||||
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
|
||||
|
@ -175,11 +176,11 @@ class CommandQueueTest : TestBaseWithProfile() {
|
|||
Assert.assertEquals(0, commandQueue.size())
|
||||
|
||||
// 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())
|
||||
|
||||
// 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())
|
||||
|
||||
// cancel tempbasal it should replace previous TEMPBASAL
|
||||
|
@ -211,7 +212,7 @@ class CommandQueueTest : TestBaseWithProfile() {
|
|||
commandQueue.loadEvents(null)
|
||||
Assert.assertEquals(4, commandQueue.size())
|
||||
commandQueue.clear()
|
||||
commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, null)
|
||||
commandQueue.tempBasalAbsolute(0.0, 30, true, validProfile, PumpSync.TemporaryBasalType.NORMAL, null)
|
||||
commandQueue.pickup()
|
||||
Assert.assertEquals(0, commandQueue.size())
|
||||
Assert.assertNotNull(commandQueue.performing)
|
||||
|
|
|
@ -12,6 +12,7 @@ import info.nightscout.androidaps.database.AppRepository
|
|||
import info.nightscout.androidaps.interfaces.ActivePluginProvider
|
||||
import info.nightscout.androidaps.interfaces.Constraint
|
||||
import info.nightscout.androidaps.interfaces.PumpDescription
|
||||
import info.nightscout.androidaps.interfaces.PumpSync
|
||||
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
|
||||
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils
|
||||
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
|
||||
|
@ -30,7 +31,6 @@ import org.mockito.Mock
|
|||
import org.mockito.Mockito
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest
|
||||
import org.powermock.modules.junit4.PowerMockRunner
|
||||
import java.util.*
|
||||
|
||||
@RunWith(PowerMockRunner::class)
|
||||
@PrepareForTest(
|
||||
|
@ -93,7 +93,7 @@ class QueueThreadTest : TestBaseWithProfile() {
|
|||
|
||||
@Test
|
||||
fun commandIsPickedUp() {
|
||||
commandQueue.tempBasalAbsolute(2.0, 60, true, validProfile, null)
|
||||
commandQueue.tempBasalAbsolute(2.0, 60, true, validProfile, PumpSync.TemporaryBasalType.NORMAL, null)
|
||||
sut.run()
|
||||
Assert.assertEquals(0, commandQueue.size())
|
||||
}
|
||||
|
|
|
@ -72,7 +72,7 @@ class BolusWizardTest : TestBase() {
|
|||
`when`(iobCobCalculator.dataLock).thenReturn(Any())
|
||||
`when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin)
|
||||
`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)
|
||||
val pumpDescription = PumpDescription()
|
||||
pumpDescription.bolusStep = pumpBolusStep
|
||||
|
|
|
@ -35,7 +35,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
|
|||
import info.nightscout.androidaps.utils.HtmlHelper
|
||||
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
|
||||
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.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
|
|
@ -23,7 +23,7 @@ import info.nightscout.androidaps.queue.Callback
|
|||
import info.nightscout.androidaps.utils.DateUtil
|
||||
import info.nightscout.androidaps.utils.JsonHelper
|
||||
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 io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.rxkotlin.plusAssign
|
||||
|
|
|
@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerCon
|
|||
import info.nightscout.androidaps.utils.FabricPrivacy
|
||||
import info.nightscout.androidaps.utils.ToastUtils
|
||||
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 io.reactivex.disposables.CompositeDisposable
|
||||
import javax.inject.Inject
|
||||
|
|
|
@ -8,6 +8,7 @@ import info.nightscout.androidaps.interfaces.PluginBase
|
|||
import info.nightscout.androidaps.interfaces.PluginDescription
|
||||
import info.nightscout.androidaps.interfaces.PumpDescription
|
||||
import info.nightscout.androidaps.interfaces.PumpInterface
|
||||
import info.nightscout.androidaps.interfaces.PumpSync
|
||||
import info.nightscout.androidaps.logging.AAPSLogger
|
||||
import info.nightscout.androidaps.plugins.common.ManufacturerType
|
||||
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
|
||||
|
@ -61,8 +62,8 @@ class TestPumpPlugin(pluginDescription: PluginDescription,
|
|||
override val batteryLevel: Int = 0
|
||||
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
|
||||
override fun stopBolusDelivering() {}
|
||||
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
|
||||
override fun setTempBasalPercent(percent: Int, 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, tbrType: PumpSync.TemporaryBasalType): 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 cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
|
||||
|
|
|
@ -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.utils.DateUtil;
|
||||
import info.nightscout.androidaps.utils.InstanceId;
|
||||
|
||||
import info.nightscout.androidaps.utils.T;
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper;
|
||||
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";
|
||||
|
||||
private final ProfileFunction profileFunction;
|
||||
private final TreatmentsInterface treatmentsPlugin;
|
||||
private final info.nightscout.androidaps.utils.sharedPreferences.SP sp;
|
||||
private final SP sp;
|
||||
private RxBusWrapper rxBus;
|
||||
private final CommandQueueProvider commandQueue;
|
||||
private final Context context;
|
||||
private final DatabaseHelperInterface databaseHelper;
|
||||
private final PumpSync pumpSync;
|
||||
|
||||
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
|
||||
* 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
|
||||
* is shut down.
|
||||
* {@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,
|
||||
ResourceHelper resourceHelper,
|
||||
ProfileFunction profileFunction,
|
||||
TreatmentsInterface treatmentsPlugin,
|
||||
SP sp,
|
||||
CommandQueueProvider commandQueue,
|
||||
Context context,
|
||||
DatabaseHelperInterface databaseHelper
|
||||
DatabaseHelperInterface databaseHelper,
|
||||
PumpSync pumpSync
|
||||
) {
|
||||
super(new PluginDescription()
|
||||
.mainType(PluginType.PUMP)
|
||||
|
@ -152,11 +154,11 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
);
|
||||
this.rxBus = rxBus;
|
||||
this.profileFunction = profileFunction;
|
||||
this.treatmentsPlugin = treatmentsPlugin;
|
||||
this.sp = sp;
|
||||
this.commandQueue = commandQueue;
|
||||
this.context = context;
|
||||
this.databaseHelper = databaseHelper;
|
||||
this.pumpSync = pumpSync;
|
||||
|
||||
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)
|
||||
.bolusDelivered(0d).carbsDelivered(0d)
|
||||
.comment(R.string.invalidinput);
|
||||
} else if (detailedBolusInfo.insulin > 0) {
|
||||
// } else if (detailedBolusInfo.insulin > 0) {
|
||||
} else {
|
||||
// bolus needed, ask pump to deliver it
|
||||
return deliverBolus(detailedBolusInfo);
|
||||
} else {
|
||||
}
|
||||
/* This should not happen anymore
|
||||
else {
|
||||
// no bolus required, carb only treatment
|
||||
treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false);
|
||||
|
||||
|
@ -496,6 +501,8 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
|
||||
.comment(R.string.virtualpump_resultok);
|
||||
}
|
||||
|
||||
*/
|
||||
} finally {
|
||||
rxBus.send(new EventComboPumpUpdateGUI());
|
||||
}
|
||||
|
@ -669,6 +676,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
bolusInfo.setBolusPumpId(bolusInfo.timestamp);
|
||||
bolusInfo.insulin = lastPumpBolus.amount;
|
||||
try {
|
||||
/* this should not happen
|
||||
if (bolusInfo.carbs > 0 && bolusInfo.carbTime != 0) {
|
||||
// split out a separate carbs record without a pumpId
|
||||
DetailedBolusInfo carbInfo = new DetailedBolusInfo();
|
||||
|
@ -682,7 +690,15 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
bolusInfo.carbTime = 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) {
|
||||
getAapsLogger().error("Adding treatment record failed", e);
|
||||
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?)
|
||||
*/
|
||||
@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.");
|
||||
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
|
||||
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 + "%");
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
@NonNull @Override
|
||||
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean forceNew, PumpSync.TemporaryBasalType tbrType) {
|
||||
return setTempBasalPercent(percent, durationInMinutes);
|
||||
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean forceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
|
||||
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");
|
||||
|
||||
if (pumpHistoryChanged && percent > 110) {
|
||||
|
@ -770,12 +786,16 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
PumpState state = commandResult.state;
|
||||
if (state.tbrActive && state.tbrPercent == adjustedPercent
|
||||
&& (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) {
|
||||
TemporaryBasal tempStart = new TemporaryBasal(getInjector())
|
||||
.date(state.timestamp)
|
||||
.duration(state.tbrRemainingDuration)
|
||||
.percent(state.tbrPercent)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(tempStart);
|
||||
pumpSync.syncTemporaryBasalWithPumpId(
|
||||
state.timestamp,
|
||||
state.tbrPercent,
|
||||
T.mins(state.tbrRemainingDuration).msecs(),
|
||||
false,
|
||||
tbrType,
|
||||
state.timestamp, // no pumpId available ????
|
||||
PumpType.ACCU_CHEK_COMBO,
|
||||
serialNumber()
|
||||
);
|
||||
|
||||
rxBus.send(new EventComboPumpUpdateGUI());
|
||||
}
|
||||
|
@ -801,7 +821,9 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
@NonNull @Override
|
||||
public PumpEnactResult cancelTempBasal(boolean enforceNew) {
|
||||
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) {
|
||||
CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState);
|
||||
if (!stateResult.success) {
|
||||
|
@ -816,32 +838,33 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
|
|||
return new PumpEnactResult(getInjector()).success(false).enacted(false);
|
||||
}
|
||||
if (!cancelResult.state.tbrActive) {
|
||||
TemporaryBasal tempBasal = new TemporaryBasal(getInjector())
|
||||
.date(cancelResult.state.timestamp)
|
||||
.duration(0)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(tempBasal);
|
||||
pumpSync.syncStopTemporaryBasalWithPumpId(
|
||||
cancelResult.state.timestamp,
|
||||
cancelResult.state.timestamp,
|
||||
PumpType.ACCU_CHEK_COMBO,
|
||||
serialNumber()
|
||||
);
|
||||
return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true);
|
||||
} else {
|
||||
return new PumpEnactResult(getInjector()).success(false).enacted(false);
|
||||
}
|
||||
} else if (activeTemp == null) {
|
||||
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)
|
||||
// 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).
|
||||
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)
|
||||
.comment("cancelTempBasal skipping changing tbr since it already is at "
|
||||
+ activeTemp.percentRate + "% and running for another "
|
||||
+ activeTemp.getPlannedRemainingMinutes() + " mins.");
|
||||
+ activeTemp.getRate() + "% and running for another "
|
||||
+ info.nightscout.androidaps.extensions.PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) + " mins.");
|
||||
} else {
|
||||
// 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%.
|
||||
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.");
|
||||
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();
|
||||
} else {
|
||||
long now = System.currentTimeMillis();
|
||||
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);
|
||||
if (aapsTbr == null || aapsTbr.percentRate != 0) {
|
||||
PumpSync.PumpState.TemporaryBasal aapsTbr = pumpSync.expectedPumpState().getTemporaryBasal();
|
||||
if (aapsTbr == null || aapsTbr.getRate() != 0) {
|
||||
getAapsLogger().debug(LTag.PUMP, "Creating 15m zero temp since pump is suspended");
|
||||
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
|
||||
.date(now)
|
||||
.percent(0)
|
||||
.duration(15)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
|
||||
pumpSync.syncTemporaryBasalWithPumpId(
|
||||
now,
|
||||
0.0,
|
||||
T.mins(15).msecs(),
|
||||
false,
|
||||
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) {
|
||||
// compare with: info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusTempBasal.updateTempBasalInDB()
|
||||
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) {
|
||||
getAapsLogger().debug(LTag.PUMP, "Creating temp basal from pump TBR");
|
||||
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
|
||||
.date(now)
|
||||
.percent(state.tbrPercent)
|
||||
.duration(state.tbrRemainingDuration)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
|
||||
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
|
||||
pumpSync.syncTemporaryBasalWithPumpId(
|
||||
now,
|
||||
state.tbrPercent,
|
||||
T.mins(state.tbrRemainingDuration).msecs(),
|
||||
false,
|
||||
PumpSync.TemporaryBasalType.NORMAL,
|
||||
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");
|
||||
TemporaryBasal tempStop = new TemporaryBasal(getInjector())
|
||||
.date(now)
|
||||
.duration(0)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(tempStop);
|
||||
pumpSync.syncStopTemporaryBasalWithPumpId(
|
||||
now,
|
||||
now,
|
||||
PumpType.ACCU_CHEK_COMBO,
|
||||
serialNumber()
|
||||
);
|
||||
} else if (aapsTbr != null && state.tbrActive
|
||||
&& (aapsTbr.percentRate != state.tbrPercent ||
|
||||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) {
|
||||
&& (aapsTbr.getRate() != state.tbrPercent ||
|
||||
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");
|
||||
TemporaryBasal tempStop = new TemporaryBasal(getInjector())
|
||||
.date(now - 1000)
|
||||
.duration(0)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(tempStop);
|
||||
pumpSync.syncStopTemporaryBasalWithPumpId(
|
||||
now - 1000,
|
||||
now - 1000,
|
||||
PumpType.ACCU_CHEK_COMBO,
|
||||
serialNumber()
|
||||
);
|
||||
|
||||
TemporaryBasal newTempBasal = new TemporaryBasal(getInjector())
|
||||
.date(now)
|
||||
.percent(state.tbrPercent)
|
||||
.duration(state.tbrRemainingDuration)
|
||||
.source(Source.USER);
|
||||
treatmentsPlugin.addToHistoryTempBasal(newTempBasal);
|
||||
pumpSync.syncTemporaryBasalWithPumpId(
|
||||
now,
|
||||
state.tbrPercent,
|
||||
T.mins(state.tbrRemainingDuration).msecs(),
|
||||
false,
|
||||
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) {
|
||||
boolean updated = false;
|
||||
for (Bolus pumpBolus : history.bolusHistory) {
|
||||
DetailedBolusInfo dbi = new DetailedBolusInfo();
|
||||
dbi.setBolusTimestamp(calculateFakeBolusDate(pumpBolus));
|
||||
dbi.setPumpType(PumpType.ACCU_CHEK_COMBO);
|
||||
dbi.setPumpSerial(serialNumber());
|
||||
dbi.setBolusPumpId(dbi.timestamp);
|
||||
dbi.insulin = pumpBolus.amount;
|
||||
dbi.setEventType(DetailedBolusInfo.EventType.CORRECTION_BOLUS);
|
||||
if (treatmentsPlugin.addToHistoryTreatment(dbi, true)) {
|
||||
if (pumpSync.syncBolusWithPumpId(
|
||||
calculateFakeBolusDate(pumpBolus),
|
||||
pumpBolus.amount,
|
||||
DetailedBolusInfo.BolusType.NORMAL,
|
||||
System.currentTimeMillis(),
|
||||
PumpType.ACCU_CHEK_COMBO,
|
||||
serialNumber()
|
||||
)) {
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -28,7 +28,7 @@ class ComboPluginTest : TestBase() {
|
|||
@Mock lateinit var profileFunction: ProfileFunction
|
||||
@Mock lateinit var activePlugin: ActivePluginProvider
|
||||
@Mock lateinit var commandQueue: CommandQueueProvider
|
||||
@Mock lateinit var treatmentsPlugin: TreatmentsInterface
|
||||
@Mock lateinit var pumpSync: PumpSync
|
||||
@Mock lateinit var sp: SP
|
||||
@Mock lateinit var context: Context
|
||||
@Mock lateinit var databaseHelper: DatabaseHelperInterface
|
||||
|
@ -47,7 +47,7 @@ class ComboPluginTest : TestBase() {
|
|||
fun prepareMocks() {
|
||||
`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")
|
||||
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
|
||||
|
|
|
@ -72,7 +72,7 @@ public class Constants {
|
|||
public static final int MIN_WATCHDOG_INTERVAL_IN_SECONDS = 12 * 60;
|
||||
|
||||
//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]
|
||||
public static final long MINIMUM_FREE_SPACE = 200;
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue