original treatmens plugin removed, temp basals working

This commit is contained in:
Milos Kozak 2017-05-22 20:58:05 +02:00
parent 85e6375026
commit 6cd046459a
29 changed files with 610 additions and 1225 deletions

View file

@ -52,7 +52,6 @@ import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gFragment;
import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientFragment;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripFragment;
import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangeFragment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpFragment;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryFragment;
import info.nightscout.androidaps.plugins.Wear.WearFragment;
@ -113,7 +112,6 @@ public class MainApp extends Application {
if (Config.OTHERPROFILES)
pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
if (Config.APS) pluginsList.add(TempTargetRangeFragment.getPlugin());
pluginsList.add(TreatmentsFragment.getPlugin());
pluginsList.add(TreatmentsFromHistoryFragment.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyFragment.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin());

View file

@ -31,7 +31,9 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
@ -43,7 +45,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings";
public static final String DATABASE_TEMPEXBASALS = "TempBasals";
public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
public static final String DATABASE_TEMPTARGETS = "TempTargets";
@ -55,8 +56,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Long latestTreatmentChange = null;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledPost = null;
private static final ScheduledExecutorService treatmentsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTratmentPost = 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;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
@ -67,7 +74,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempExBasal.class);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
@ -85,7 +91,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempExBasal.class, true);
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
@ -114,10 +119,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getWritableDatabase().delete(DATABASE_BGREADINGS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
log.debug("Before TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPEXBASALS));
getWritableDatabase().delete(DATABASE_TEMPEXBASALS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPEXBASALS));
log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
@ -147,7 +148,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempExBasal.class, true);
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
@ -156,7 +156,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
//DbRequests can be cleared from NSClient fragment
TableUtils.createTableIfNotExists(connectionSource, TempExBasal.class);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
@ -178,6 +177,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
}
public void resetTempTargets() {
@ -196,6 +196,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTemporaryBasalChange();
}
public void resetExtededBoluses() {
@ -205,14 +206,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
e.printStackTrace();
}
scheduleExtendedBolusChange();
}
// ------------------ getDao -------------------------------------------
private Dao<TempExBasal, Long> getDaoTempBasals() throws SQLException {
return getDao(TempExBasal.class);
}
private Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
}
@ -233,11 +231,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(DbRequest.class);
}
private Dao<TemporaryBasal, String> getDaoTemporaryBasal() throws SQLException {
private Dao<TemporaryBasal, Long> getDaoTemporaryBasal() throws SQLException {
return getDao(TemporaryBasal.class);
}
private Dao<ExtendedBolus, String> getDaoExtendedBolus() throws SQLException {
private Dao<ExtendedBolus, Long> getDaoExtendedBolus() throws SQLException {
return getDao(ExtendedBolus.class);
}
@ -510,16 +508,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (latestTreatmentChange != null)
MainApp.bus().post(new EventNewHistoryData(latestTreatmentChange));
latestTreatmentChange = null;
scheduledPost = null;
scheduledTratmentPost = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledPost != null)
scheduledPost.cancel(false);
if (scheduledTratmentPost != null)
scheduledTratmentPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 5;
scheduledPost = worker.schedule(task, sec, TimeUnit.SECONDS);
scheduledTratmentPost = treatmentsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
@ -540,57 +538,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<Treatment>();
}
// ------------ TempExBasal handling ---------------
public int update(TempExBasal tempBasal) {
int updated = 0;
try {
updated = getDaoTempBasals().update(tempBasal);
latestTreatmentChange = tempBasal.timeIndex;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
return updated;
}
public void create(TempExBasal tempBasal) {
try {
getDaoTempBasals().create(tempBasal);
latestTreatmentChange = tempBasal.timeIndex;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
}
public void delete(TempExBasal tempBasal) {
try {
getDaoTempBasals().delete(tempBasal);
latestTreatmentChange = tempBasal.timeIndex;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
}
public List<TempExBasal> getTempbasalsDataFromTime(long mills, boolean ascending, boolean isExtended) {
try {
Dao<TempExBasal, Long> daoTempbasals = getDaoTempBasals();
List<TempExBasal> tempbasals;
QueryBuilder<TempExBasal, Long> queryBuilder = daoTempbasals.queryBuilder();
queryBuilder.orderBy("timeIndex", ascending);
Where where = queryBuilder.where();
where.ge("timeIndex", mills).and().eq("isExtended", isExtended);
PreparedQuery<TempExBasal> preparedQuery = queryBuilder.prepare();
tempbasals = daoTempbasals.query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<TempExBasal>();
}
// ---------------- TempTargets handling ---------------
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
@ -746,5 +693,139 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
// ------------ TemporaryBasal handling ---------------
public int update(TemporaryBasal tempBasal) {
int updated = 0;
try {
updated = getDaoTemporaryBasal().update(tempBasal);
latestTreatmentChange = tempBasal.date;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTemporaryBasalChange();
return updated;
}
public void create(TemporaryBasal tempBasal) {
try {
getDaoTemporaryBasal().create(tempBasal);
latestTreatmentChange = tempBasal.date;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTemporaryBasalChange();
}
public void delete(TemporaryBasal tempBasal) {
try {
getDaoTemporaryBasal().delete(tempBasal);
latestTreatmentChange = tempBasal.date;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTemporaryBasalChange();
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<TemporaryBasal>();
}
static public void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
MainApp.bus().post(new EventTempBasalChange());
scheduledTemBasalsPost = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemBasalsPost != null)
scheduledTemBasalsPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 5;
scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
// ------------ ExtendedBolus handling ---------------
public int update(ExtendedBolus extendedBolus) {
int updated = 0;
try {
updated = getDaoExtendedBolus().update(extendedBolus);
latestTreatmentChange = extendedBolus.date;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleExtendedBolusChange();
return updated;
}
public void create(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().create(extendedBolus);
latestTreatmentChange = extendedBolus.date;
} catch (SQLException e) {
e.printStackTrace();
}
scheduleExtendedBolusChange();
}
public void delete(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().delete(extendedBolus);
latestTreatmentChange = extendedBolus.date;
} catch (SQLException e) {
e.printStackTrace();
}
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) {
e.printStackTrace();
}
return new ArrayList<ExtendedBolus>();
}
static public void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
MainApp.bus().post(new EventExtendedBolusChange());
scheduledExtendedBolusPost = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledExtendedBolusPost != null)
scheduledExtendedBolusPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 5;
scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
}
}

View file

@ -112,7 +112,7 @@ public class ExtendedBolus implements Interval {
"}";
}
double absoluteRate() {
public double absoluteRate() {
return Round.roundTo(insulin / durationInMinutes * 60, 0.01);
}

View file

@ -1,225 +0,0 @@
package info.nightscout.androidaps.db;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPEXBASALS)
public class TempExBasal {
private static Logger log = LoggerFactory.getLogger(TempExBasal.class);
@DatabaseField(id = true)
public long timeIndex;
@DatabaseField
public Date timeStart;
@DatabaseField
public Date timeEnd;
@DatabaseField
public int percent; // In % of current basal. 100% == current basal
@DatabaseField
public Double absolute; // Absolute value in U
@DatabaseField
public int duration; // in minutes
@DatabaseField
public boolean isExtended = false; // true if set as extended bolus
@DatabaseField
public boolean isAbsolute = false; // true if if set as absolute value in U
public IobTotal iobCalc(long time) {
IobTotal result = new IobTotal(time);
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
if (profile == null)
return result;
int realDuration = getDurationToTime(time);
Double netBasalAmount = 0d;
if (realDuration > 0) {
Double netBasalRate = 0d;
Double dia_ago = time - profile.getDia() * 60 * 60 * 1000;
int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
double tempBolusSpacing = realDuration / aboutFiveMinIntervals;
for (Long j = 0L; j < aboutFiveMinIntervals; j++) {
// find middle of the interval
Long date = (long) (timeStart.getTime() + j * tempBolusSpacing * 60 * 1000 + 0.5d * tempBolusSpacing * 60 * 1000);
Double basalRate = profile.getBasal(NSProfile.secondsFromMidnight(date));
if (basalRate == null)
continue;
if (isExtended) {
netBasalRate = this.absolute;
} else {
if (this.isAbsolute) {
netBasalRate = this.absolute - basalRate;
} else {
netBasalRate = (this.percent - 100) / 100d * basalRate;
}
}
if (date > dia_ago && date <= time) {
double tempBolusSize = netBasalRate * tempBolusSpacing / 60d;
netBasalAmount += tempBolusSize;
Treatment tempBolusPart = new Treatment(insulinInterface);
tempBolusPart.insulin = tempBolusSize;
tempBolusPart.date = date;
Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, profile.getDia());
result.basaliob += aIOB.iobContrib;
result.activity += aIOB.activityContrib;
result.netbasalinsulin += tempBolusPart.insulin;
if (tempBolusPart.insulin > 0) {
result.hightempinsulin += tempBolusPart.insulin;
}
}
result.netRatio = netBasalRate; // ratio at the end of interval
}
}
result.netInsulin = netBasalAmount;
return result;
}
// Determine end of basal
public long getTimeEnd() {
long tempBasalTimePlannedEnd = getPlannedTimeEnd();
long now = new Date().getTime();
if (timeEnd != null && timeEnd.getTime() < tempBasalTimePlannedEnd) {
tempBasalTimePlannedEnd = timeEnd.getTime();
}
if (now < tempBasalTimePlannedEnd)
tempBasalTimePlannedEnd = now;
return tempBasalTimePlannedEnd;
}
public long getPlannedTimeEnd() {
return timeStart.getTime() + 60 * 1_000 * duration;
}
public int getRealDuration() {
long msecs = getTimeEnd() - timeStart.getTime();
return Math.round(msecs / 60f / 1000);
}
private int getDurationToTime(long time) {
long endTime = Math.min(time, getTimeEnd());
long msecs = endTime - timeStart.getTime();
return Math.round(msecs / 60f / 1000);
}
public long getMillisecondsFromStart() {
return new Date().getTime() - timeStart.getTime();
}
public int getPlannedRemainingMinutes() {
if (timeEnd != null) return 0;
float remainingMin = (getPlannedTimeEnd() - new Date().getTime()) / 1000f / 60;
return (remainingMin < 0) ? 0 : Math.round(remainingMin);
}
public boolean isInProgress() {
return isInProgress(new Date().getTime());
}
public double tempBasalConvertedToAbsolute(Date time) {
if (isExtended) {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
return profile.getBasal(NSProfile.secondsFromMidnight(time)) + absolute;
} else {
if (isAbsolute) return absolute;
else {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
return profile.getBasal(NSProfile.secondsFromMidnight(time)) * percent / 100;
}
}
}
public boolean isInProgress(long time) {
if (timeStart.getTime() > time) return false; // in the future
if (timeEnd == null) { // open end
if (timeStart.getTime() < time && getPlannedTimeEnd() > time)
return true; // in interval
return false;
}
// closed end
if (timeStart.getTime() < time && timeEnd.getTime() > time)
return true; // in interval
return false;
}
public String log() {
return "TempExBasal{" +
"timeIndex=" + timeIndex +
", timeStart=" + timeStart +
", timeEnd=" + timeEnd +
", percent=" + percent +
", absolute=" + absolute +
", duration=" + duration +
", isAbsolute=" + isAbsolute +
", isExtended=" + isExtended +
'}';
}
public String toString() {
String extended = isExtended ? "E " : "";
if (isAbsolute) {
return extended + DecimalFormatter.to2Decimal(absolute) + "U/h @" +
DateUtil.timeString(timeStart) +
" " + getRealDuration() + "/" + duration + "min";
} else { // percent
return percent + "% @" +
DateUtil.timeString(timeStart) +
" " + getRealDuration() + "/" + duration + "min";
}
}
public String toStringShort() {
String extended = isExtended ? "E" : "";
if (isAbsolute) {
return extended + DecimalFormatter.to2Decimal(absolute) + "U/h ";
} else { // percent
return percent + "% ";
}
}
public String toStringMedium() {
String extended = isExtended ? "E" : "";
if (isAbsolute) {
return extended + DecimalFormatter.to2Decimal(absolute) + "U/h ("
+ getRealDuration() + "/" + duration + ") ";
} else { // percent
return percent + "% (" + getRealDuration() + "/" + duration + ") ";
}
}
}

View file

@ -45,6 +45,18 @@ public class TemporaryBasal implements Interval {
@DatabaseField
public double absoluteRate = 0d;
public TemporaryBasal() {}
public TemporaryBasal(ExtendedBolus extendedBolus) {
this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source;
this._id = extendedBolus._id;
this.durationInMinutes = extendedBolus.durationInMinutes;
this.isAbsolute = true;
this.absoluteRate = extendedBolus.absoluteRate();
}
// -------- Interval interface ---------
Long cuttedEnd = null;
@ -167,7 +179,7 @@ public class TemporaryBasal implements Interval {
return match(new Date().getTime());
}
public double tempBasalConvertedToAbsolute(Date time) {
public double tempBasalConvertedToAbsolute(long time) {
if (isAbsolute) return absoluteRate;
else {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();

View file

@ -2,10 +2,12 @@ package info.nightscout.androidaps.interfaces;
import java.util.List;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.utils.OverlappingIntervals;
/**
* Created by mike on 14.06.2016.
@ -27,21 +29,23 @@ public interface TreatmentsInterface {
// real basals on pump
boolean isRealTempBasalInProgress();
TempExBasal getRealTempBasal (long time);
TemporaryBasal getRealTempBasal (long time);
void tempBasalStart(TempExBasal tempBasal);
void tempBasalStart(TemporaryBasal tempBasal);
void tempBasalStop(long time);
// basal that can be faked by extended boluses
boolean isTempBasalInProgress();
TempExBasal getTempBasal (long time);
TemporaryBasal getTempBasal (long time);
double getTempBasalAbsoluteRate();
double getTempBasalRemainingMinutes();
OverlappingIntervals<TemporaryBasal> getTemporaryBasals();
boolean isExtendedBoluslInProgress();
TempExBasal getExtendedBolus (long time);
void extendedBolusStart(TempExBasal extendedBolus);
ExtendedBolus getExtendedBolus (long time);
void extendedBolusStart(ExtendedBolus extendedBolus);
void extendedBolusStop(long time);
OverlappingIntervals<ExtendedBolus> getExtendedBoluses();
long oldestDataAvaialable();

View file

@ -25,11 +25,10 @@ import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventBolusRequested;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
@ -56,6 +55,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgError;
import info.nightscout.utils.BatteryLevel;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.OverlappingIntervals;
import info.nightscout.utils.SP;
/**
@ -553,7 +553,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
} else {
uploadTempBasalStartAbsolute(result.absolute, result.duration);
}
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@ -573,7 +572,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalStartPercent(result.percent, result.duration);
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@ -598,7 +596,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalEnd();
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@ -1179,7 +1176,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public TempExBasal getRealTempBasal(long time) {
public TemporaryBasal getRealTempBasal(long time) {
return activeTreatments.getRealTempBasal(time);
}
@ -1189,7 +1186,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public TempExBasal getTempBasal(long time) {
public TemporaryBasal getTempBasal(long time) {
return activeTreatments.getTempBasal(time);
}
@ -1204,15 +1201,18 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public void tempBasalStart(TempExBasal tempBasal) {
public OverlappingIntervals<TemporaryBasal> getTemporaryBasals() {
return activeTreatments.getTemporaryBasals();
}
@Override
public void tempBasalStart(TemporaryBasal tempBasal) {
activeTreatments.tempBasalStart(tempBasal);
MainApp.bus().post(new EventTempBasalChange());
}
@Override
public void tempBasalStop(long time) {
activeTreatments.tempBasalStop(time);
MainApp.bus().post(new EventTempBasalChange());
}
@Override
@ -1221,20 +1221,23 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public TempExBasal getExtendedBolus(long time) {
public ExtendedBolus getExtendedBolus(long time) {
return activeTreatments.getExtendedBolus(time);
}
@Override
public void extendedBolusStart(TempExBasal tempBasal) {
activeTreatments.extendedBolusStart(tempBasal);
MainApp.bus().post(new EventExtendedBolusChange());
public void extendedBolusStart(ExtendedBolus extendedBolus) {
activeTreatments.extendedBolusStart(extendedBolus);
}
@Override
public void extendedBolusStop(long time) {
activeTreatments.extendedBolusStop(time);
MainApp.bus().post(new EventExtendedBolusChange());
}
@Override
public OverlappingIntervals<ExtendedBolus> getExtendedBoluses() {
return activeTreatments.getExtendedBoluses();
}
@Override

View file

@ -16,12 +16,12 @@ import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SP;
@ -232,7 +232,7 @@ public class DetermineBasalAdapterAMAJS {
mCurrentTemp.add("rate", MainApp.getConfigBuilder().getTempBasalAbsoluteRate());
// as we have non default temps longer than 30 mintues
TempExBasal tempBasal = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
TemporaryBasal tempBasal = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
if(tempBasal != null){
mCurrentTemp.add("minutesrunning", tempBasal.getRealDuration());
}

View file

@ -67,8 +67,8 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventInitializationChanged;
@ -898,7 +898,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
calibrationButton.setVisibility(View.GONE);
}
TempExBasal activeTemp = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
cancelTempButton.setVisibility(View.VISIBLE);
cancelTempButton.setText(MainApp.instance().getString(R.string.cancel) + "\n" + activeTemp.toStringShort());
@ -1084,13 +1084,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
double lastBaseBasal = 0;
double lastTempBasal = 0;
for (long time = fromTime; time < now; time += 5 * 60 * 1000L) {
TempExBasal tb = MainApp.getConfigBuilder().getTempBasal(time);
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasal(time);
double baseBasalValue = profile.getBasal(NSProfile.secondsFromMidnight(new Date(time)));
double baseLineValue = baseBasalValue;
double tempBasalValue = 0;
double basal = 0d;
if (tb != null) {
tempBasalValue = tb.tempBasalConvertedToAbsolute(new Date(time));
tempBasalValue = tb.tempBasalConvertedToAbsolute(new Date(time).getTime());
if (tempBasalValue != lastTempBasal) {
tempBasalArray.add(new DataPoint(time, lastTempBasal));
tempBasalArray.add(new DataPoint(time, basal = tempBasalValue));

View file

@ -18,9 +18,10 @@ import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventNewBG;
@ -31,7 +32,6 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter;
@ -140,7 +140,7 @@ public class PersistentNotificationPlugin implements PluginBase{
PumpInterface pump = MainApp.getConfigBuilder();
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
TempExBasal activeTemp = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
line1 += " " + activeTemp.toStringShort();
}

View file

@ -25,7 +25,8 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
@ -42,7 +43,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotificati
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round;
@ -220,7 +221,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
@Override
public String treatmentPlugin() {
return TreatmentsPlugin.class.getName();
return TreatmentsFromHistoryPlugin.class.getName();
}
@Override
@ -400,7 +401,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
// Check if some temp is already in progress
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
// Correct basal already set ?
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()).percent == percentRate) {
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()).percentRate == percentRate) {
result.success = true;
result.percent = percentRate;
result.absolute = MainApp.getConfigBuilder().getTempBasalAbsoluteRate();
@ -670,12 +671,17 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
extended.put("PumpIOB", getDanaRPump().iob);
extended.put("LastBolus", getDanaRPump().lastBolusTime.toLocaleString());
extended.put("LastBolusAmount", getDanaRPump().lastBolusAmount);
TempExBasal tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
if (tb != null) {
extended.put("TempBasalAbsoluteRate", MainApp.getConfigBuilder().getTempBasalAbsoluteRate());
extended.put("TempBasalStart", tb.timeStart.toLocaleString());
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(new Date().getTime()));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
extended.put("IsExtended", tb.isExtended);
}
ExtendedBolus eb = MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime());
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {

View file

@ -9,7 +9,7 @@ import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
@ -69,18 +69,16 @@ public class MsgStatusBolusExtended extends MessageBase {
long now = new Date().getTime();
if (treatmentsInterface.isExtendedBoluslInProgress()) {
TempExBasal extendedBolus = treatmentsInterface.getExtendedBolus(new Date().getTime());
ExtendedBolus extendedBolus = treatmentsInterface.getExtendedBolus(new Date().getTime());
if (pump.isExtendedInProgress) {
if (extendedBolus.absolute != pump.extendedBolusAbsoluteRate) {
if (extendedBolus.absoluteRate() != pump.extendedBolusAbsoluteRate) {
// Close current extended
treatmentsInterface.extendedBolusStop(now);
treatmentsInterface.extendedBolusStop(now - 1000);
// Create new
TempExBasal newExtended = new TempExBasal();
newExtended.timeStart = new Date(now);
newExtended.absolute = pump.extendedBolusAbsoluteRate;
newExtended.isAbsolute = true;
newExtended.duration = pump.extendedBolusMinutes;
newExtended.isExtended = true;
ExtendedBolus newExtended = new ExtendedBolus();
newExtended.date = new Date(now).getTime();
newExtended.insulin = pump.extendedBolusAmount;
newExtended.durationInMinutes = pump.extendedBolusMinutes;
treatmentsInterface.extendedBolusStart(newExtended);
}
} else {
@ -90,12 +88,10 @@ public class MsgStatusBolusExtended extends MessageBase {
} else {
if (pump.isExtendedInProgress) {
// Create new
TempExBasal newExtended = new TempExBasal();
newExtended.timeStart = new Date(now);
newExtended.absolute = pump.extendedBolusAbsoluteRate;
newExtended.isAbsolute = true;
newExtended.duration = pump.extendedBolusMinutes;
newExtended.isExtended = true;
ExtendedBolus newExtended = new ExtendedBolus();
newExtended.date = new Date(now).getTime();
newExtended.insulin = pump.extendedBolusAmount;
newExtended.durationInMinutes = pump.extendedBolusMinutes;
treatmentsInterface.extendedBolusStart(newExtended);
}
}

View file

@ -9,7 +9,7 @@ import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
@ -63,18 +63,17 @@ public class MsgStatusTempBasal extends MessageBase {
long now = new Date().getTime();
if (treatmentsInterface.isTempBasalInProgress()) {
TempExBasal tempBasal = treatmentsInterface.getTempBasal(new Date().getTime());
TemporaryBasal tempBasal = treatmentsInterface.getTempBasal(new Date().getTime());
if (danaRPump.isTempBasalInProgress) {
if (tempBasal.percent != danaRPump.tempBasalPercent) {
if (tempBasal.percentRate != danaRPump.tempBasalPercent) {
// Close current temp basal
treatmentsInterface.tempBasalStop(now);
treatmentsInterface.tempBasalStop(now - 1000);
// Create new
TempExBasal newTempBasal = new TempExBasal();
newTempBasal.timeStart = new Date(now);
newTempBasal.percent = danaRPump.tempBasalPercent;
TemporaryBasal newTempBasal = new TemporaryBasal();
newTempBasal.date = new Date(now).getTime();
newTempBasal.percentRate = danaRPump.tempBasalPercent;
newTempBasal.isAbsolute = false;
newTempBasal.duration = danaRPump.tempBasalTotalSec / 60;
newTempBasal.isExtended = false;
newTempBasal.durationInMinutes = danaRPump.tempBasalTotalSec / 60;
treatmentsInterface.tempBasalStart(newTempBasal);
}
} else {
@ -84,12 +83,11 @@ public class MsgStatusTempBasal extends MessageBase {
} else {
if (danaRPump.isTempBasalInProgress) {
// Create new
TempExBasal newTempBasal = new TempExBasal();
newTempBasal.timeStart = new Date(now);
newTempBasal.percent = danaRPump.tempBasalPercent;
TemporaryBasal newTempBasal = new TemporaryBasal();
newTempBasal.date = new Date(now).getTime();
newTempBasal.percentRate = danaRPump.tempBasalPercent;
newTempBasal.isAbsolute = false;
newTempBasal.duration = danaRPump.tempBasalTotalSec / 60;
newTempBasal.isExtended = false;
newTempBasal.durationInMinutes = danaRPump.tempBasalTotalSec / 60;
treatmentsInterface.tempBasalStart(newTempBasal);
}
}

View file

@ -25,7 +25,8 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
@ -36,14 +37,14 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round;
@ -158,7 +159,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.danarpump_shortname);
if (!name.trim().isEmpty()){
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
@ -219,7 +220,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
@Override
public String treatmentPlugin() {
return TreatmentsPlugin.class.getName();
return TreatmentsFromHistoryPlugin.class.getName();
}
@Override
@ -241,7 +242,8 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
// Pump interface
public boolean isTempBasalInProgress() {
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()) != null) return true;
if (MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime()) != null && useExtendedBoluses) return true;
if (MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime()) != null && useExtendedBoluses)
return true;
return false;
}
@ -306,11 +308,11 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
return pump.currentBasal;
}
public TempExBasal getTempBasal(long time) {
TempExBasal temp = MainApp.getConfigBuilder().getTempBasal(time);
public TemporaryBasal getTempBasal(long time) {
TemporaryBasal temp = MainApp.getConfigBuilder().getTempBasal(time);
if (temp != null) return temp;
if (useExtendedBoluses)
return MainApp.getConfigBuilder().getExtendedBolus(time);
return new TemporaryBasal(MainApp.getConfigBuilder().getExtendedBolus(time));
return null;
}
@ -411,7 +413,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
// Check if some temp is already in progress
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
// Correct basal already set ?
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()).percent == percentRate) {
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()).percentRate == percentRate) {
result.success = true;
result.percent = percentRate;
result.absolute = MainApp.getConfigBuilder().getTempBasalAbsoluteRate();
@ -513,7 +515,8 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
log.error("setTempBasalPercent: Invalid input");
return result;
}
if (percent > getPumpDescription().maxHighTempPercent) percent = getPumpDescription().maxHighTempPercent;
if (percent > getPumpDescription().maxHighTempPercent)
percent = getPumpDescription().maxHighTempPercent;
if (pump.isTempBasalInProgress && pump.tempBasalPercent == percent) {
result.enacted = false;
result.success = true;
@ -681,12 +684,17 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
extended.put("PumpIOB", pump.iob);
// extended.put("LastBolus", pump.lastBolusTime.toLocaleString());
// extended.put("LastBolusAmount", pump.lastBolusAmount);
TempExBasal tb = getTempBasal(new Date().getTime());
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
if (tb != null) {
extended.put("TempBasalAbsoluteRate", MainApp.getConfigBuilder().getTempBasalAbsoluteRate());
extended.put("TempBasalStart", tb.timeStart.toLocaleString());
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(new Date().getTime()));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
extended.put("IsExtended", tb.isExtended);
}
ExtendedBolus eb = MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime());
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {
@ -758,7 +766,8 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
public Integer applyBasalConstraints(Integer percentRate) {
Integer origPercentRate = percentRate;
if (percentRate < 0) percentRate = 0;
if (percentRate > getPumpDescription().maxHighTempPercent) percentRate = getPumpDescription().maxHighTempPercent;
if (percentRate > getPumpDescription().maxHighTempPercent)
percentRate = getPumpDescription().maxHighTempPercent;
if (!Objects.equals(percentRate, origPercentRate) && Config.logConstraintsChanges && !Objects.equals(origPercentRate, Constants.basalPercentOnlyForCheckLimit))
log.debug("Limiting percent rate " + origPercentRate + "% to " + percentRate + "%");
return percentRate;
@ -813,7 +822,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
if (MainApp.getConfigBuilder().isExtendedBoluslInProgress()) {
ret += "Extended: " + MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime()).toString() + "\n";
}
if (!veryShort){
if (!veryShort) {
ret += "TDD: " + DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits + " U\n";
}
ret += "IOB: " + pump.iob + "U\n";

View file

@ -25,7 +25,8 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
@ -365,7 +366,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte
// Check if some temp is already in progress
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
// Correct basal already set ?
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()).percent == percentRate) {
if (MainApp.getConfigBuilder().getTempBasal(new Date().getTime()).percentRate == percentRate) {
result.success = true;
result.percent = percentRate;
result.absolute = MainApp.getConfigBuilder().getTempBasalAbsoluteRate();
@ -591,12 +592,17 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte
extended.put("PumpIOB", getDanaRPump().iob);
extended.put("LastBolus", getDanaRPump().lastBolusTime.toLocaleString());
extended.put("LastBolusAmount", getDanaRPump().lastBolusAmount);
TempExBasal tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
if (tb != null) {
extended.put("TempBasalAbsoluteRate", MainApp.getConfigBuilder().getTempBasalAbsoluteRate());
extended.put("TempBasalStart", tb.timeStart.toLocaleString());
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(new Date().getTime()));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
extended.put("IsExtended", tb.isExtended);
}
ExtendedBolus eb = MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime());
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryPlugin;
import info.nightscout.utils.DateUtil;
/**
@ -119,7 +119,7 @@ public class MDIPlugin implements PluginBase, PumpInterface {
@Override
public String treatmentPlugin() {
return TreatmentsPlugin.class.getName();
return TreatmentsFromHistoryPlugin.class.getName();
}
@Override

View file

@ -16,7 +16,8 @@ import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
@ -26,7 +27,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.PumpVirtual.events.EventVirtualPumpUpdateGui;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryPlugin;
import info.nightscout.utils.DateUtil;
/**
@ -138,7 +139,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
@Override
public String treatmentPlugin() {
return TreatmentsPlugin.class.getName();
return TreatmentsFromHistoryPlugin.class.getName();
}
@Override
@ -236,14 +237,12 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder();
PumpEnactResult result = cancelTempBasal();
if (!result.success)
return result;
TempExBasal tempBasal = new TempExBasal();
tempBasal.timeStart = new Date();
TemporaryBasal tempBasal = new TemporaryBasal();
tempBasal.date = new Date().getTime();
tempBasal.isAbsolute = true;
tempBasal.absolute = absoluteRate;
tempBasal.duration = durationInMinutes;
tempBasal.absoluteRate = absoluteRate;
tempBasal.durationInMinutes = durationInMinutes;
PumpEnactResult result = new PumpEnactResult();
result.success = true;
result.enacted = true;
result.isTempCancel = false;
@ -267,11 +266,11 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
if (!result.success)
return result;
}
TempExBasal tempBasal = new TempExBasal();
tempBasal.timeStart = new Date();
TemporaryBasal tempBasal = new TemporaryBasal();
tempBasal.date = new Date().getTime();
tempBasal.isAbsolute = false;
tempBasal.percent = percent;
tempBasal.duration = durationInMinutes;
tempBasal.percentRate = percent;
tempBasal.durationInMinutes = durationInMinutes;
result.success = true;
result.enacted = true;
result.percent = percent;
@ -293,12 +292,10 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
PumpEnactResult result = cancelExtendedBolus();
if (!result.success)
return result;
TempExBasal extendedBolus = new TempExBasal();
extendedBolus.timeStart = new Date();
extendedBolus.isExtended = true;
extendedBolus.absolute = insulin * 60d / durationInMinutes;
extendedBolus.duration = durationInMinutes;
extendedBolus.isAbsolute = true;
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.date = new Date().getTime();
extendedBolus.insulin = insulin;
extendedBolus.durationInMinutes = durationInMinutes;
result.success = true;
result.enacted = true;
result.bolusDelivered = insulin;
@ -367,11 +364,17 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getActiveProfile().getProfile().getActiveProfile());
} catch (Exception e) {}
TempExBasal tb;
if ((tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime())) != null) {
status.put("tempbasalpct", tb.percent);
status.put("tempbasalstart", DateUtil.toISOString(tb.timeStart));
status.put("tempbasalremainmin", tb.getPlannedRemainingMinutes());
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasal(new Date().getTime());
if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(new Date().getTime()));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
}
ExtendedBolus eb = MainApp.getConfigBuilder().getExtendedBolus(new Date().getTime());
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
}
status.put("timestamp", DateUtil.toISOString(new Date()));

View file

@ -1,73 +0,0 @@
package info.nightscout.androidaps.plugins.Treatments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsBolusFragment;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsTempBasalsFragment;
public class TreatmentsFragment extends Fragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(TreatmentsFragment.class);
private static TreatmentsPlugin treatmentsPlugin = new TreatmentsPlugin();
public static TreatmentsPlugin getPlugin() {
return treatmentsPlugin;
}
Context context;
TextView treatmentsTab;
TextView tempBasalsTab;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.treatments_fragment, container, false);
treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments);
tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals);
treatmentsTab.setOnClickListener(this);
tempBasalsTab.setOnClickListener(this);
context = getContext();
setFragment(new TreatmentsBolusFragment());
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.treatments_treatments:
setFragment(new TreatmentsBolusFragment());
break;
case R.id.treatments_tempbasals:
setFragment(new TreatmentsTempBasalsFragment());
break;
}
}
private void setFragment(Fragment selectedFragment) {
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.treatments_fragment_container, selectedFragment); // f2_container is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}

View file

@ -1,461 +0,0 @@
package info.nightscout.androidaps.plugins.Treatments;
import android.support.annotation.Nullable;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SP;
/**
* Created by mike on 05.08.2016.
*/
public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
private static Logger log = LoggerFactory.getLogger(TreatmentsPlugin.class);
public static IobTotal lastTreatmentCalculation;
public static IobTotal lastTempBasalsCalculation;
public static List<Treatment> treatments;
private static List<TempExBasal> tempBasals;
private static List<TempExBasal> extendedBoluses;
private static boolean useExtendedBoluses = false;
private static boolean fragmentEnabled = true;
private static boolean fragmentVisible = true;
private static TreatmentsPlugin treatmentsPlugin = new TreatmentsPlugin();
public static TreatmentsPlugin getPlugin() {
return treatmentsPlugin;
}
@Override
public String getFragmentClass() {
return TreatmentsFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.treatments);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.treatments_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
@Override
public boolean isEnabled(int type) {
boolean canBeEnabled = MainApp.getConfigBuilder().treatmentPlugin() == null ? true : MainApp.getConfigBuilder().treatmentPlugin().equals(getClass().getName());
return type == TREATMENT && fragmentEnabled && canBeEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == TREATMENT && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
boolean canBeEnabled = MainApp.getConfigBuilder().treatmentPlugin() == null ? true : MainApp.getConfigBuilder().treatmentPlugin().equals(getClass().getName());
return canBeEnabled;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == TREATMENT) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == TREATMENT) this.fragmentVisible = fragmentVisible;
}
@Override
public int getType() {
return PluginBase.TREATMENT;
}
public TreatmentsPlugin() {
useExtendedBoluses = SP.getBoolean("danar_useextended", false);
MainApp.bus().register(this);
initializeData();
}
public static void initializeData() {
// Treatments
double dia = Constants.defaultDIA;
if (MainApp.getConfigBuilder().getActiveProfile() != null && MainApp.getConfigBuilder().getActiveProfile().getProfile() != null)
dia = MainApp.getConfigBuilder().getActiveProfile().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
treatments = MainApp.getDbHelper().getTreatmentDataFromTime(fromMills, false);
// Temp basals
tempBasals = MainApp.getDbHelper().getTempbasalsDataFromTime(fromMills, false, false);
extendedBoluses = MainApp.getDbHelper().getTempbasalsDataFromTime(fromMills, false, true);
// Update ended
checkForExpiredExtended();
checkForExpiredTemps();
}
public static void checkForExpiredTemps() {
checkForExpired(tempBasals);
}
public static void checkForExpiredExtended() {
checkForExpired(extendedBoluses);
}
private static void checkForExpired(List<TempExBasal> list) {
long now = new Date().getTime();
for (int position = list.size() - 1; position >= 0; position--) {
TempExBasal t = list.get(position);
boolean update = false;
if (t.timeEnd == null && t.getPlannedTimeEnd() < now) {
t.timeEnd = new Date(t.getPlannedTimeEnd());
if (Config.logTempBasalsCut)
log.debug("Add timeEnd to old record");
update = true;
}
if (position > 0) {
Date startofnewer = list.get(position - 1).timeStart;
if (t.timeEnd == null) {
t.timeEnd = new Date(Math.min(startofnewer.getTime(), t.getPlannedTimeEnd()));
if (Config.logTempBasalsCut)
log.debug("Add timeEnd to old record");
update = true;
} else if (t.timeEnd.getTime() > startofnewer.getTime()) {
t.timeEnd = startofnewer;
update = true;
}
}
if (update) {
MainApp.getDbHelper().update(t);
if (Config.logTempBasalsCut) {
log.debug("Fixing unfinished temp end: " + t.log());
if (position > 0)
log.debug("Previous: " + list.get(position - 1).log());
}
}
}
}
@Override
public IobTotal getLastCalculationTreatments() {
return lastTreatmentCalculation;
}
@Override
public IobTotal getCalculationToTimeTreatments(long time) {
IobTotal total = new IobTotal(time);
if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet
return total;
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
if (profile == null)
return total;
Double dia = profile.getDia();
for (Integer pos = 0; pos < treatments.size(); pos++) {
Treatment t = treatments.get(pos);
if (t.date > time) continue;
Iob tIOB = t.iobCalc(time, dia);
total.iob += tIOB.iobContrib;
total.activity += tIOB.activityContrib;
Iob bIOB = t.iobCalc(time, dia / SP.getInt("openapsama_bolussnooze_dia_divisor", 2));
total.bolussnooze += bIOB.iobContrib;
}
return total;
}
@Override
public void updateTotalIOBTreatments() {
IobTotal total = getCalculationToTimeTreatments(new Date().getTime());
lastTreatmentCalculation = total;
}
@Override
public MealData getMealData() {
MealData result = new MealData();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null) return result;
long now = new Date().getTime();
long dia_ago = now - (new Double(1.5d * profile.getDia() * 60 * 60 * 1000l)).longValue();
for (Treatment treatment : treatments) {
long t = treatment.date;
if (t > dia_ago && t <= now) {
if (treatment.carbs >= 1) {
result.carbs += treatment.carbs;
}
if (treatment.insulin > 0 && treatment.mealBolus) {
result.boluses += treatment.insulin;
}
}
}
AutosensData autosensData = IobCobCalculatorPlugin.getLastAutosensData();
if (autosensData != null) {
result.mealCOB = autosensData.cob;
}
return result;
}
@Override
public List<Treatment> getTreatments() {
return treatments;
}
@Override
public List<Treatment> getTreatments5MinBack(long time) {
List<Treatment> in5minback = new ArrayList<>();
for (Integer pos = 0; pos < treatments.size(); pos++) {
Treatment t = treatments.get(pos);
if (t.date <= time && t.date > time - 5 * 60 * 1000)
in5minback.add(t);
}
return in5minback;
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
initializeData();
updateTotalIOBTreatments();
}
@Override
public IobTotal getLastCalculationTempBasals() {
return lastTempBasalsCalculation;
}
@Override
public IobTotal getCalculationToTimeTempBasals(long time) {
checkForExpired(tempBasals);
checkForExpired(extendedBoluses);
IobTotal total = new IobTotal(time);
for (Integer pos = 0; pos < tempBasals.size(); pos++) {
TempExBasal t = tempBasals.get(pos);
if (t.timeStart.getTime() > time) continue;
IobTotal calc = t.iobCalc(time);
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basaliob);
total.plus(calc);
}
if (useExtendedBoluses) {
for (Integer pos = 0; pos < extendedBoluses.size(); pos++) {
TempExBasal t = extendedBoluses.get(pos);
if (t.timeStart.getTime() > time) continue;
IobTotal calc = t.iobCalc(time);
total.plus(calc);
}
}
return total;
}
@Override
public void updateTotalIOBTempBasals() {
IobTotal total = getCalculationToTimeTempBasals(new Date().getTime());
lastTempBasalsCalculation = total;
}
public boolean isRealTempBasalInProgress() {
return getRealTempBasal(new Date().getTime()) != null;
}
@Override
public boolean isTempBasalInProgress() {
return getTempBasal(new Date().getTime()) != null;
}
@Nullable
public TempExBasal getRealTempBasal(long time) {
checkForExpired(tempBasals);
for (TempExBasal t : tempBasals) {
if (t.isInProgress(time)) return t;
}
return null;
}
@Nullable
@Override
public TempExBasal getTempBasal(long time) {
if (isRealTempBasalInProgress())
return getRealTempBasal(time);
if (isExtendedBoluslInProgress() && useExtendedBoluses)
return getExtendedBolus(time);
return null;
}
@Override
public boolean isExtendedBoluslInProgress() {
return getExtendedBolus(new Date().getTime()) != null; //TODO: crosscheck here
}
@Nullable
@Override
public TempExBasal getExtendedBolus(long time) {
checkForExpired(extendedBoluses);
for (TempExBasal t : extendedBoluses) {
if (t.isInProgress(time)) return t;
}
return null;
}
@Override
public void extendedBolusStart(TempExBasal extendedBolus) {
MainApp.getDbHelper().create(extendedBolus);
}
@Override
public void extendedBolusStop(long time) {
TempExBasal extendedBolus = getExtendedBolus(time);
if (extendedBolus != null) {
extendedBolus.timeEnd = new Date(time);
MainApp.getDbHelper().update(extendedBolus);
}
}
@Override
public double getTempBasalAbsoluteRate() {
PumpInterface pump = MainApp.getConfigBuilder();
TempExBasal tb = getTempBasal(new Date().getTime());
if (tb != null) {
if (tb.isAbsolute) {
return tb.absolute;
} else {
Double baseRate = pump.getBaseBasalRate();
Double tempRate = baseRate * (tb.percent / 100d);
return tempRate;
}
}
TempExBasal eb = getExtendedBolus(new Date().getTime());
if (eb != null && useExtendedBoluses) {
return pump.getBaseBasalRate() + eb.absolute;
}
return 0;
}
@Override
public double getTempBasalRemainingMinutes() {
if (isTempBasalInProgress())
return getTempBasal(new Date().getTime()).getPlannedRemainingMinutes();
if (isExtendedBoluslInProgress() && useExtendedBoluses)
return getExtendedBolus(new Date().getTime()).getPlannedRemainingMinutes();
return 0;
}
@Override
public void tempBasalStart(TempExBasal tempBasal) {
MainApp.getDbHelper().create(tempBasal);
}
@Override
public void tempBasalStop(long time) {
TempExBasal tempBasal = getTempBasal(time);
if (tempBasal != null) {
tempBasal.timeEnd = new Date(time);
MainApp.getDbHelper().update(tempBasal);
}
}
@Override
public long oldestDataAvaialable() {
long oldestTemp = new Date().getTime();
if (tempBasals.size() > 0)
oldestTemp = Math.min(oldestTemp, tempBasals.get(tempBasals.size() - 1).timeStart.getTime());
if (extendedBoluses.size() > 0)
oldestTemp = Math.min(oldestTemp, extendedBoluses.get(extendedBoluses.size() - 1).timeStart.getTime());
oldestTemp -= 15 * 60 * 1000L; // allow 15 min before
return oldestTemp;
}
public static List<TempExBasal> getMergedList() {
if (useExtendedBoluses) {
List<TempExBasal> merged = new ArrayList<TempExBasal>();
merged.addAll(tempBasals);
if (useExtendedBoluses)
merged.addAll(extendedBoluses);
class CustomComparator implements Comparator<TempExBasal> {
public int compare(TempExBasal object1, TempExBasal object2) {
return (int) (object2.timeIndex - object1.timeIndex);
}
}
Collections.sort(merged, new CustomComparator());
return merged;
} else {
return tempBasals;
}
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
initializeData();
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
initializeData();
}
public void onStatusEvent(final EventPreferenceChange s) {
if (s.isChanged("danar_useextended")) {
useExtendedBoluses = SP.getBoolean("danar_useextended", false);
initializeData();
}
}
}

View file

@ -3,22 +3,20 @@ package info.nightscout.androidaps.plugins.TreatmentsFromHistory;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsBolusFragment;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsTempBasalsFragment;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.fragments.TreatmentsBolusFragment;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.fragments.TreatmentsTemporaryBasalsFragment;
public class TreatmentsFromHistoryFragment extends Fragment {
public class TreatmentsFromHistoryFragment extends Fragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(TreatmentsFromHistoryFragment.class);
private static TreatmentsFromHistoryPlugin treatmentsPlugin = new TreatmentsFromHistoryPlugin();
@ -28,20 +26,44 @@ public class TreatmentsFromHistoryFragment extends Fragment {
}
Context context;
Fragment bolusFragment;
Fragment tempBasalsFragment;
TextView treatmentsTab;
TextView tempBasalsTab;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.treatments_fragment, container, false);
bolusFragment = new TreatmentsBolusFragment();
tempBasalsFragment = new TreatmentsTempBasalsFragment();
treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments);
tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals);
treatmentsTab.setOnClickListener(this);
tempBasalsTab.setOnClickListener(this);
context = getContext();
setFragment(new TreatmentsBolusFragment());
return view;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.treatments_treatments:
setFragment(new TreatmentsBolusFragment());
break;
case R.id.treatments_tempbasals:
setFragment(new TreatmentsTemporaryBasalsFragment());
break;
}
}
private void setFragment(Fragment selectedFragment) {
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.treatments_fragment_container, selectedFragment); // f2_container is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}

View file

@ -11,15 +11,17 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
@ -28,6 +30,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.OverlappingIntervals;
import info.nightscout.utils.SP;
/**
@ -40,8 +43,8 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
public static IobTotal lastTempBasalsCalculation;
public static List<Treatment> treatments;
private static List<TempExBasal> tempBasals;
private static List<TempExBasal> extendedBoluses;
private static OverlappingIntervals<TemporaryBasal> tempBasals = new OverlappingIntervals<>();
private static OverlappingIntervals<ExtendedBolus> extendedBoluses = new OverlappingIntervals<>();
private static boolean fragmentEnabled = true;
private static boolean fragmentVisible = true;
@ -59,7 +62,7 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
@Override
public String getName() {
return MainApp.instance().getString(R.string.treatments);
return MainApp.instance().getString(R.string.treatments) + "FromHistory"; // TODO: remove later
}
@Override
@ -117,66 +120,41 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
public TreatmentsFromHistoryPlugin() {
MainApp.bus().register(this);
initializeData();
initializeTempBasalData();
initializeTreatmentData();
initializeExtendedBolusData();
}
public static void initializeData() {
public static void initializeTreatmentData() {
// Treatments
double dia = Constants.defaultDIA;
if (MainApp.getConfigBuilder().getActiveProfile() != null && MainApp.getConfigBuilder().getActiveProfile().getProfile() != null)
dia = MainApp.getConfigBuilder().getActiveProfile().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
treatments = MainApp.getDbHelper().getTreatmentDataFromTime(fromMills, false);
// Temp basals
tempBasals = MainApp.getDbHelper().getTempbasalsDataFromTime(fromMills, false, false);
extendedBoluses = MainApp.getDbHelper().getTempbasalsDataFromTime(fromMills, false, true);
// Update ended
checkForExpiredExtended();
checkForExpiredTemps();
}
public static void checkForExpiredTemps() {
checkForExpired(tempBasals);
public static void initializeTempBasalData() {
// Treatments
double dia = Constants.defaultDIA;
if (MainApp.getConfigBuilder().getActiveProfile() != null && MainApp.getConfigBuilder().getActiveProfile().getProfile() != null)
dia = MainApp.getConfigBuilder().getActiveProfile().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
tempBasals.reset().add(MainApp.getDbHelper().getTemporaryBasalsDataFromTime(fromMills, false));
}
public static void checkForExpiredExtended() {
checkForExpired(extendedBoluses);
}
public static void initializeExtendedBolusData() {
// Treatments
double dia = Constants.defaultDIA;
if (MainApp.getConfigBuilder().getActiveProfile() != null && MainApp.getConfigBuilder().getActiveProfile().getProfile() != null)
dia = MainApp.getConfigBuilder().getActiveProfile().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
extendedBoluses.reset().add(MainApp.getDbHelper().getExtendedBolusDataFromTime(fromMills, false));
private static void checkForExpired(List<TempExBasal> list) {
long now = new Date().getTime();
for (int position = list.size() - 1; position >= 0; position--) {
TempExBasal t = list.get(position);
boolean update = false;
if (t.timeEnd == null && t.getPlannedTimeEnd() < now) {
t.timeEnd = new Date(t.getPlannedTimeEnd());
if (Config.logTempBasalsCut)
log.debug("Add timeEnd to old record");
update = true;
}
if (position > 0) {
Date startofnewer = list.get(position - 1).timeStart;
if (t.timeEnd == null) {
t.timeEnd = new Date(Math.min(startofnewer.getTime(), t.getPlannedTimeEnd()));
if (Config.logTempBasalsCut)
log.debug("Add timeEnd to old record");
update = true;
} else if (t.timeEnd.getTime() > startofnewer.getTime()) {
t.timeEnd = startofnewer;
update = true;
}
}
if (update) {
MainApp.getDbHelper().update(t);
if (Config.logTempBasalsCut) {
log.debug("Fixing unfinished temp end: " + t.log());
if (position > 0)
log.debug("Previous: " + list.get(position - 1).log());
}
}
}
}
@Override
@ -206,11 +184,10 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
total.bolussnooze += bIOB.iobContrib;
}
checkForExpired(extendedBoluses);
for (Integer pos = 0; pos < extendedBoluses.size(); pos++) {
TempExBasal t = extendedBoluses.get(pos);
if (t.timeStart.getTime() > time) continue;
IobTotal calc = t.iobCalc(time);
ExtendedBolus e = extendedBoluses.get(pos);
if (e.date > time) continue;
IobTotal calc = e.iobCalc(time);
total.plus(calc);
}
return total;
@ -274,7 +251,7 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
}
@Override
public TempExBasal getRealTempBasal(long time) {
public TemporaryBasal getRealTempBasal(long time) {
return null;
}
@ -290,7 +267,19 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
initializeData();
initializeTreatmentData();
updateTotalIOBTreatments();
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
initializeTempBasalData();
updateTotalIOBTempBasals();
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
initializeExtendedBolusData();
updateTotalIOBTreatments();
}
@ -301,11 +290,10 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
@Override
public IobTotal getCalculationToTimeTempBasals(long time) {
checkForExpired(tempBasals);
IobTotal total = new IobTotal(time);
for (Integer pos = 0; pos < tempBasals.size(); pos++) {
TempExBasal t = tempBasals.get(pos);
if (t.timeStart.getTime() > time) continue;
TemporaryBasal t = tempBasals.get(pos);
if (t.date > time) continue;
IobTotal calc = t.iobCalc(time);
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basaliob);
total.plus(calc);
@ -322,44 +310,44 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
@Nullable
@Override
public TempExBasal getTempBasal(long time) {
checkForExpired(tempBasals);
for (TempExBasal t : tempBasals) {
if (t.isInProgress(time)) return t;
}
return null;
public TemporaryBasal getTempBasal(long time) {
return (TemporaryBasal) tempBasals.getValueByInterval(time);
}
@Override
public TempExBasal getExtendedBolus(long time) {
checkForExpired(extendedBoluses);
for (TempExBasal t : extendedBoluses) {
if (t.isInProgress(time)) return t;
}
return null;
public ExtendedBolus getExtendedBolus(long time) {
return (ExtendedBolus) extendedBoluses.getValueByInterval(time);
}
@Override
public void extendedBolusStart(TempExBasal extendedBolus) {
public void extendedBolusStart(ExtendedBolus extendedBolus) {
MainApp.getDbHelper().create(extendedBolus);
}
@Override
public void extendedBolusStop(long time) {
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.date = time;
extendedBolus.durationInMinutes = 0;
MainApp.getDbHelper().create(extendedBolus);
}
@Override
public OverlappingIntervals<ExtendedBolus> getExtendedBoluses() {
return extendedBoluses;
}
@Override
public double getTempBasalAbsoluteRate() {
PumpInterface pump = MainApp.getConfigBuilder();
TempExBasal tb = getTempBasal(new Date().getTime());
TemporaryBasal tb = getTempBasal(new Date().getTime());
if (tb != null) {
if (tb.isAbsolute) {
return tb.absolute;
return tb.absoluteRate;
} else {
Double baseRate = pump.getBaseBasalRate();
Double tempRate = baseRate * (tb.percent / 100d);
Double tempRate = baseRate * (tb.percentRate / 100d);
return tempRate;
}
}
@ -374,24 +362,34 @@ public class TreatmentsFromHistoryPlugin implements PluginBase, TreatmentsInterf
}
@Override
public void tempBasalStart(TempExBasal tempBasal) {
public OverlappingIntervals<TemporaryBasal> getTemporaryBasals() {
return tempBasals;
}
@Override
public void tempBasalStart(TemporaryBasal tempBasal) {
MainApp.getDbHelper().create(tempBasal);
}
@Override
public void tempBasalStop(long time) {
TemporaryBasal temporaryBasal = new TemporaryBasal();
temporaryBasal.date = time;
temporaryBasal.durationInMinutes = 0;
MainApp.getDbHelper().create(temporaryBasal);
}
@Override
public long oldestDataAvaialable() {
long oldestTemp = new Date().getTime();
long oldestTime = new Date().getTime();
if (tempBasals.size() > 0)
oldestTemp = Math.min(oldestTemp, tempBasals.get(tempBasals.size() - 1).timeStart.getTime());
oldestTime = Math.min(oldestTime, tempBasals.get(0).date);
if (extendedBoluses.size() > 0)
oldestTemp = Math.min(oldestTemp, extendedBoluses.get(extendedBoluses.size() - 1).timeStart.getTime());
oldestTemp -= 15 * 60 * 1000L; // allow 15 min before
return oldestTemp;
oldestTime = Math.min(oldestTime, extendedBoluses.get(0).date);
if (treatments.size() > 0)
oldestTime = Math.min(oldestTime, extendedBoluses.get(treatments.size() - 1).date);
oldestTime -= 15 * 60 * 1000L; // allow 15 min before
return oldestTime;
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Treatments.fragments;
package info.nightscout.androidaps.plugins.TreatmentsFromHistory.fragments;
import android.app.Activity;
import android.content.Context;
@ -35,10 +35,9 @@ import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
@ -85,7 +84,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
holder.activity.setText(DecimalFormatter.to3Decimal(iob.activityContrib) + " U");
holder.mealOrCorrection.setText(treatments.get(position).mealBolus ? MainApp.sResources.getString(R.string.mealbolus) : MainApp.sResources.getString(R.string.correctionbous));
if (iob.iobContrib != 0)
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.colorAffectingIOB));
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive));
else
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.cardColorBackground));
holder.remove.setTag(treatments.get(position));
@ -142,7 +141,6 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
MainApp.getConfigBuilder().removeCareportalEntryFromNS(_id);
}
MainApp.getDbHelper().delete(treatment);
TreatmentsPlugin.initializeData();
updateGUI();
Answers.getInstance().logCustom(new CustomEvent("RemoveTreatment"));
}
@ -165,7 +163,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(TreatmentsPlugin.treatments);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(TreatmentsFromHistoryPlugin.treatments);
recyclerView.setAdapter(adapter);
iobTotal = (TextView) view.findViewById(R.id.treatments_iobtotal);
@ -194,8 +192,6 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
builder.setPositiveButton(this.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainApp.getDbHelper().resetTreatments();
TreatmentsPlugin.initializeData();
updateGUI();
Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
}
@ -234,11 +230,11 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.treatments), false);
if (TreatmentsPlugin.lastTreatmentCalculation != null)
iobTotal.setText(DecimalFormatter.to2Decimal(TreatmentsPlugin.lastTreatmentCalculation.iob) + " U");
if (TreatmentsPlugin.lastTreatmentCalculation != null)
activityTotal.setText(DecimalFormatter.to3Decimal(TreatmentsPlugin.lastTreatmentCalculation.activity) + " U");
recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsFromHistoryPlugin.treatments), false);
if (TreatmentsFromHistoryPlugin.lastTreatmentCalculation != null)
iobTotal.setText(DecimalFormatter.to2Decimal(TreatmentsFromHistoryPlugin.lastTreatmentCalculation.iob) + " U");
if (TreatmentsFromHistoryPlugin.lastTreatmentCalculation != null)
activityTotal.setText(DecimalFormatter.to3Decimal(TreatmentsFromHistoryPlugin.lastTreatmentCalculation.activity) + " U");
}
});
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Treatments.fragments;
package info.nightscout.androidaps.plugins.TreatmentsFromHistory.fragments;
import android.app.Activity;
import android.content.Context;
@ -25,20 +25,21 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.TreatmentsFromHistory.TreatmentsFromHistoryPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.OverlappingIntervals;
public class TreatmentsTempBasalsFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(TreatmentsTempBasalsFragment.class);
public class TreatmentsTemporaryBasalsFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(TreatmentsTemporaryBasalsFragment.class);
RecyclerView recyclerView;
LinearLayoutManager llm;
@ -49,9 +50,9 @@ public class TreatmentsTempBasalsFragment extends Fragment {
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TempBasalsViewHolder> {
List<TempExBasal> tempBasalList;
OverlappingIntervals<TemporaryBasal> tempBasalList;
RecyclerViewAdapter(List<TempExBasal> tempBasalList) {
RecyclerViewAdapter(OverlappingIntervals<TemporaryBasal> tempBasalList) {
this.tempBasalList = tempBasalList;
}
@ -63,34 +64,31 @@ public class TreatmentsTempBasalsFragment extends Fragment {
@Override
public void onBindViewHolder(TempBasalsViewHolder holder, int position) {
TempExBasal tempBasal = tempBasalList.get(position);
if (tempBasal.timeEnd != null) {
holder.date.setText(DateUtil.dateAndTimeString(tempBasal.timeStart) + " - " + DateUtil.timeString(tempBasalList.get(position).timeEnd));
TemporaryBasal tempBasal = tempBasalList.getReversed(position);
if (tempBasal.isInProgress()) {
holder.date.setText(DateUtil.dateAndTimeString(tempBasal.date));
} else {
holder.date.setText(DateUtil.dateAndTimeString(tempBasal.timeStart));
holder.date.setText(DateUtil.dateAndTimeString(tempBasal.date) + " - " + DateUtil.timeString(tempBasalList.get(position).end()));
}
holder.duration.setText(DecimalFormatter.to0Decimal(tempBasal.duration) + " min");
holder.duration.setText(DecimalFormatter.to0Decimal(tempBasal.getRealDuration()) + " min");
if (tempBasal.isAbsolute) {
holder.absolute.setText(DecimalFormatter.to0Decimal(tempBasal.tempBasalConvertedToAbsolute(tempBasal.timeStart)) + " U/h");
holder.absolute.setText(DecimalFormatter.to0Decimal(tempBasal.tempBasalConvertedToAbsolute(tempBasal.date)) + " U/h");
holder.percent.setText("");
} else {
holder.absolute.setText("");
holder.percent.setText(DecimalFormatter.to0Decimal(tempBasal.percent) + "%");
holder.percent.setText(DecimalFormatter.to0Decimal(tempBasal.percentRate) + "%");
}
holder.realDuration.setText(DecimalFormatter.to0Decimal(tempBasal.getRealDuration()) + " min");
IobTotal iob = tempBasal.iobCalc(new Date().getTime());
holder.iob.setText(DecimalFormatter.to2Decimal(iob.basaliob) + " U");
holder.netInsulin.setText(DecimalFormatter.to2Decimal(iob.netInsulin) + " U");
holder.netRatio.setText(DecimalFormatter.to2Decimal(iob.netRatio) + " U/h");
holder.extendedFlag.setVisibility(tempBasal.isExtended ? View.VISIBLE : View.GONE);
//holder.extendedFlag.setVisibility(tempBasal.isExtended ? View.VISIBLE : View.GONE);
holder.extendedFlag.setVisibility(View.GONE);
if (tempBasal.isInProgress())
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.colorInProgress));
else if (tempBasal.timeEnd == null)
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.colorNotEnded));
else if (tempBasal.iobCalc(new Date().getTime()).basaliob != 0)
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.colorAffectingIOB));
else
holder.dateLinearLayout.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.cardColorBackground));
holder.date.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive));
if (tempBasal.iobCalc(new Date().getTime()).basaliob != 0)
holder.iob.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive));
holder.remove.setTag(tempBasal);
}
@ -115,7 +113,6 @@ public class TreatmentsTempBasalsFragment extends Fragment {
TextView netInsulin;
TextView iob;
TextView extendedFlag;
LinearLayout dateLinearLayout;
TextView remove;
TempBasalsViewHolder(View itemView) {
@ -130,7 +127,6 @@ public class TreatmentsTempBasalsFragment extends Fragment {
netInsulin = (TextView) itemView.findViewById(R.id.tempbasals_netinsulin);
iob = (TextView) itemView.findViewById(R.id.tempbasals_iob);
extendedFlag = (TextView) itemView.findViewById(R.id.tempbasals_extendedflag);
dateLinearLayout = (LinearLayout) itemView.findViewById(R.id.tempbasals_datelinearlayout);
remove = (TextView) itemView.findViewById(R.id.tempbasals_remove);
remove.setOnClickListener(this);
remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
@ -138,12 +134,12 @@ public class TreatmentsTempBasalsFragment extends Fragment {
@Override
public void onClick(View v) {
final TempExBasal tempBasal = (TempExBasal) v.getTag();
final TemporaryBasal tempBasal = (TemporaryBasal) v.getTag();
switch (v.getId()) {
case R.id.tempbasals_remove:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
builder.setMessage(MainApp.sResources.getString(R.string.removerecord) + "\n" + DateUtil.dateAndTimeString(tempBasal.timeStart));
builder.setMessage(MainApp.sResources.getString(R.string.removerecord) + "\n" + DateUtil.dateAndTimeString(tempBasal.date));
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO: handle this in NS too
@ -152,8 +148,6 @@ public class TreatmentsTempBasalsFragment extends Fragment {
// MainApp.getConfigBuilder().removeCareportalEntryFromNS(_id);
//}
MainApp.getDbHelper().delete(tempBasal);
TreatmentsPlugin.initializeData();
updateGUI();
Answers.getInstance().logCustom(new CustomEvent("RemoveTempBasal"));
}
});
@ -175,7 +169,7 @@ public class TreatmentsTempBasalsFragment extends Fragment {
llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(TreatmentsPlugin.getMergedList());
RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getConfigBuilder().getTemporaryBasals());
recyclerView.setAdapter(adapter);
tempBasalTotalView = (TextView) view.findViewById(R.id.tempbasals_totaltempiob);
@ -203,15 +197,20 @@ public class TreatmentsTempBasalsFragment extends Fragment {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventNewBG ev) {
updateGUI();
}
public void updateGUI() {
Activity activity = getActivity();
if (activity != null && recyclerView != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getMergedList()), false);
if (TreatmentsPlugin.lastTempBasalsCalculation != null) {
String totalText = DecimalFormatter.to2Decimal(TreatmentsPlugin.lastTempBasalsCalculation.basaliob) + " U";
recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getConfigBuilder().getTemporaryBasals()), false);
if (MainApp.getConfigBuilder().getLastCalculationTempBasals() != null) {
String totalText = DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getLastCalculationTempBasals().basaliob) + " U";
tempBasalTotalView.setText(totalText);
}
}

View file

@ -27,18 +27,18 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
@ -68,7 +68,6 @@ public class WatchUpdaterService extends WearableListenerService implements
public static final String ACTION_CONFIRMATION_REQUEST_PATH = "/nightscout_watch_actionconfirmationrequest";
boolean wear_integration = false;
SharedPreferences mPrefs;
private static boolean lastLoopStatus;
@ -95,7 +94,9 @@ public class WatchUpdaterService extends WearableListenerService implements
}
public void googleApiConnect() {
if(googleApiClient != null && (googleApiClient.isConnected() || googleApiClient.isConnecting())) { googleApiClient.disconnect(); }
if (googleApiClient != null && (googleApiClient.isConnected() || googleApiClient.isConnecting())) {
googleApiClient.disconnect();
}
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
@ -131,15 +132,14 @@ public class WatchUpdaterService extends WearableListenerService implements
sendStatus();
} else if (ACTION_SEND_BASALS.equals(action)) {
sendBasals();
} else if (ACTION_SEND_BOLUSPROGRESS.equals(action)){
sendBolusProgress(intent.getIntExtra("progresspercent", 0), intent.hasExtra("progressstatus")?intent.getStringExtra("progressstatus"):"");
} else if (ACTION_SEND_ACTIONCONFIRMATIONREQUEST.equals(action)){
} else if (ACTION_SEND_BOLUSPROGRESS.equals(action)) {
sendBolusProgress(intent.getIntExtra("progresspercent", 0), intent.hasExtra("progressstatus") ? intent.getStringExtra("progressstatus") : "");
} else if (ACTION_SEND_ACTIONCONFIRMATIONREQUEST.equals(action)) {
String title = intent.getStringExtra("title");
String message = intent.getStringExtra("message");
String actionstring = intent.getStringExtra("actionstring");
sendActionConfirmationRequest(title, message, actionstring);
}
else {
} else {
sendData();
}
} else {
@ -192,11 +192,13 @@ public class WatchUpdaterService extends WearableListenerService implements
if (lastBG != null) {
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if(googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { googleApiConnect(); }
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
if (wear_integration) {
final DataMap dataMap = dataMapSingleBG(lastBG, glucoseStatus);
if(dataMap==null) {
if (dataMap == null) {
ToastUtils.showToastInUiThread(this, getString(R.string.noprofile));
return;
}
@ -208,23 +210,23 @@ public class WatchUpdaterService extends WearableListenerService implements
private DataMap dataMapSingleBG(BgReading lastBG, GlucoseStatus glucoseStatus) {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if(profile == null) return null;
if (profile == null) return null;
Double lowLine = SafeParse.stringToDouble(mPrefs.getString("low_mark", "0"));
Double highLine = SafeParse.stringToDouble(mPrefs.getString("high_mark", "0"));
//convert to mg/dl
if (! profile.getUnits().equals(Constants.MGDL)){
if (!profile.getUnits().equals(Constants.MGDL)) {
lowLine *= Constants.MMOLL_TO_MGDL;
highLine *= Constants.MMOLL_TO_MGDL;
}
if (lowLine < 1){
if (lowLine < 1) {
lowLine = OverviewPlugin.bgTargetLow;
}
if(highLine < 1){
if (highLine < 1) {
highLine = OverviewPlugin.bgTargetHigh;
}
@ -239,8 +241,8 @@ public class WatchUpdaterService extends WearableListenerService implements
int battery = getBatteryLevel(getApplicationContext());
dataMap.putString("sgvString", lastBG.valueToUnitsToString(profile.getUnits()));
dataMap.putDouble("timestamp", lastBG.date);
if(glucoseStatus == null) {
dataMap.putString("slopeArrow", "" );
if (glucoseStatus == null) {
dataMap.putString("slopeArrow", "");
dataMap.putString("delta", "");
dataMap.putString("avgDelta", "");
} else {
@ -250,7 +252,7 @@ public class WatchUpdaterService extends WearableListenerService implements
}
dataMap.putString("battery", "" + battery);
dataMap.putLong("sgvLevel", sgvLevel);
dataMap.putInt("batteryLevel", (battery>=30)?1:0);
dataMap.putInt("batteryLevel", (battery >= 30) ? 1 : 0);
dataMap.putDouble("sgvDouble", lastBG.value);
dataMap.putDouble("high", highLine);
dataMap.putDouble("low", lowLine);
@ -259,33 +261,32 @@ public class WatchUpdaterService extends WearableListenerService implements
private String deltastring(double deltaMGDL, double deltaMMOL, String units) {
String deltastring = "";
if (deltaMGDL >=0){
if (deltaMGDL >= 0) {
deltastring += "+";
} else{
} else {
deltastring += "-";
}
if (units.equals(Constants.MGDL)){
if (units.equals(Constants.MGDL)) {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMGDL));
}
else {
} else {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMMOL));
}
return deltastring;
}
private String slopeArrow(double delta) {
if (delta <= (-3.5*5)) {
if (delta <= (-3.5 * 5)) {
return "\u21ca";
} else if (delta <= (-2*5)) {
} else if (delta <= (-2 * 5)) {
return "\u2193";
} else if (delta <= (-1*5)) {
} else if (delta <= (-1 * 5)) {
return "\u2198";
} else if (delta <= (1*5)) {
} else if (delta <= (1 * 5)) {
return "\u2192";
} else if (delta <= (2*5)) {
} else if (delta <= (2 * 5)) {
return "\u2197";
} else if (delta <= (3.5*5)) {
} else if (delta <= (3.5 * 5)) {
return "\u2191";
} else {
return "\u21c8";
@ -294,25 +295,27 @@ public class WatchUpdaterService extends WearableListenerService implements
private void resendData() {
if(googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { googleApiConnect(); }
long startTime = System.currentTimeMillis() - (long)(60000 * 60 * 5.5);
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5);
BgReading last_bg = DatabaseHelper.lastBg();
if (last_bg == null) return;
List<BgReading> graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true);
List<BgReading> graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (!graph_bgs.isEmpty()) {
DataMap entries = dataMapSingleBG(last_bg, glucoseStatus);
if(entries==null) {
if (entries == null) {
ToastUtils.showToastInUiThread(this, getString(R.string.noprofile));
return;
}
final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
for (BgReading bg : graph_bgs) {
DataMap dataMap = dataMapSingleBG(bg, glucoseStatus);
if(dataMap != null) {
if (dataMap != null) {
dataMaps.add(dataMap);
}
}
@ -324,11 +327,12 @@ public class WatchUpdaterService extends WearableListenerService implements
}
private void sendBasals() {
if(googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { googleApiConnect(); }
if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) {
googleApiConnect();
}
long now = System.currentTimeMillis();
long startTimeWindow = now - (long)(60000 * 60 * 5.5);
long startTimeWindow = now - (long) (60000 * 60 * 5.5);
ArrayList<DataMap> basals = new ArrayList<>();
@ -337,7 +341,7 @@ public class WatchUpdaterService extends WearableListenerService implements
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if(profile==null) {
if (profile == null) {
return;
}
@ -347,24 +351,24 @@ public class WatchUpdaterService extends WearableListenerService implements
double beginBasalValue = profile.getBasal(NSProfile.secondsFromMidnight(new Date(beginBasalSegmentTime)));
double endBasalValue = beginBasalValue;
TempExBasal tb1 = MainApp.getConfigBuilder().getTempBasal(runningTime);
TempExBasal tb2 = MainApp.getConfigBuilder().getTempBasal(runningTime);
TemporaryBasal tb1 = MainApp.getConfigBuilder().getTempBasal(runningTime);
TemporaryBasal tb2 = MainApp.getConfigBuilder().getTempBasal(runningTime);
double tb_before = beginBasalValue;
double tb_amount = beginBasalValue;
long tb_start = runningTime;
if(tb1 != null){
if (tb1 != null) {
tb_before = beginBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(new Date(runningTime));
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime);
tb_start = runningTime;
}
for(;runningTime<now;runningTime+= 5*60*1000){
for (; runningTime < now; runningTime += 5 * 60 * 1000) {
//basal rate
endBasalValue = profile.getBasal(NSProfile.secondsFromMidnight(new Date(runningTime)));
if(endBasalValue != beginBasalValue){
if (endBasalValue != beginBasalValue) {
//push the segment we recently left
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
@ -389,11 +393,11 @@ public class WatchUpdaterService extends WearableListenerService implements
tb1 = tb2;
tb_start = runningTime;
tb_before = endBasalValue;
tb_amount = tb1.tempBasalConvertedToAbsolute(new Date(runningTime));
tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime);
} else if (tb1 != null && tb2 != null) {
double currentAmount = tb2.tempBasalConvertedToAbsolute(new Date(runningTime));
if(currentAmount != tb_amount){
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime);
if (currentAmount != tb_amount) {
temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount));
tb_start = runningTime;
tb_before = tb_amount;
@ -402,19 +406,19 @@ public class WatchUpdaterService extends WearableListenerService implements
}
}
}
if(beginBasalSegmentTime != runningTime){
if (beginBasalSegmentTime != runningTime) {
//push the remaining segment
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
}
if(tb1 != null){
if (tb1 != null) {
tb2 = MainApp.getConfigBuilder().getTempBasal(now); //use "now" to express current situation
if(tb2 == null) {
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
double currentAmount = tb2.tempBasalConvertedToAbsolute(new Date(now));
if(currentAmount != tb_amount){
double currentAmount = tb2.tempBasalConvertedToAbsolute(now);
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));
} else {
@ -423,9 +427,9 @@ public class WatchUpdaterService extends WearableListenerService implements
}
} else {
tb2 = MainApp.getConfigBuilder().getTempBasal(now); //use "now" to express current situation
if(tb2 != null) {
if (tb2 != null) {
//onset at the end
double currentAmount = tb2.tempBasalConvertedToAbsolute(new Date(runningTime));
double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime);
temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount));
}
}
@ -537,7 +541,7 @@ public class WatchUpdaterService extends WearableListenerService implements
TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder();
if (treatmentsInterface.isTempBasalInProgress()) {
TempExBasal activeTemp = treatmentsInterface.getTempBasal(new Date().getTime());
TemporaryBasal activeTemp = treatmentsInterface.getTempBasal(new Date().getTime());
if (shortString) {
status += activeTemp.toStringShort();
} else {
@ -550,7 +554,7 @@ public class WatchUpdaterService extends WearableListenerService implements
IobTotal bolusIob = treatmentsInterface.getLastCalculationTreatments().round();
treatmentsInterface.updateTotalIOBTempBasals();
IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round();
status += (shortString?"":(getString(R.string.treatments_iob_label_string) + " ")) + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob);
status += (shortString ? "" : (getString(R.string.treatments_iob_label_string) + " ")) + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob);
if (mPrefs.getBoolean("wear_detailediob", true)) {
status += "("
@ -558,13 +562,13 @@ public class WatchUpdaterService extends WearableListenerService implements
+ DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
}
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (!mPrefs.getBoolean("wear_showbgi", false) ||profile == null || profile.getIsf(NSProfile.secondsFromMidnight()) == null || profile.getIc(NSProfile.secondsFromMidnight()) == null) {
if (!mPrefs.getBoolean("wear_showbgi", false) || profile == null || profile.getIsf(NSProfile.secondsFromMidnight()) == null || profile.getIc(NSProfile.secondsFromMidnight()) == null) {
return status;
}
double bgi = -(bolusIob.activity + basalIob.activity)*5*profile.getIsf(NSProfile.secondsFromMidnight());
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(NSProfile.secondsFromMidnight());
status += " " + ((bgi>=0)?"+":"") + DecimalFormatter.to2Decimal(bgi);
status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi);
return status;
}
@ -585,7 +589,7 @@ public class WatchUpdaterService extends WearableListenerService implements
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static boolean shouldReportLoopStatus(boolean enabled){
public static boolean shouldReportLoopStatus(boolean enabled) {
return (lastLoopStatus != enabled);
}
@ -593,9 +597,9 @@ public class WatchUpdaterService extends WearableListenerService implements
Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if(level == -1 || scale == -1) {
if (level == -1 || scale == -1) {
return 50;
}
return (int)(((float)level / (float)scale) * 100.0f);
return (int) (((float) level / (float) scale) * 100.0f);
}
}

View file

@ -14,7 +14,7 @@ import java.util.Date;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.TempExBasal;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventPreferenceChange;
@ -109,13 +109,14 @@ public class StatuslinePlugin implements PluginBase {
if (fragmentEnabled) {
try {
MainApp.bus().register(this);
} catch (Exception e) {}
} catch (Exception e) {
}
sendStatus();
}
else{
} else {
try {
MainApp.bus().unregister(this);
} catch (Exception e) {}
} catch (Exception e) {
}
sendStatus();
}
}
@ -130,9 +131,9 @@ public class StatuslinePlugin implements PluginBase {
private void sendStatus() {
String status = ""; // sent once on disable
String status = ""; // sent once on disable
if(fragmentEnabled) {
if (fragmentEnabled) {
status = buildStatusString();
}
@ -164,7 +165,7 @@ public class StatuslinePlugin implements PluginBase {
TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder();
if (treatmentsInterface.isTempBasalInProgress()) {
TempExBasal activeTemp = treatmentsInterface.getTempBasal(new Date().getTime());
TemporaryBasal activeTemp = treatmentsInterface.getTempBasal(new Date().getTime());
if (shortString) {
status += activeTemp.toStringShort();
} else {
@ -186,13 +187,13 @@ public class StatuslinePlugin implements PluginBase {
+ DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
}
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (!mPrefs.getBoolean("xdripstatus_showbgi", false) ||profile == null || profile.getIsf(NSProfile.secondsFromMidnight()) == null || profile.getIc(NSProfile.secondsFromMidnight()) == null) {
if (!mPrefs.getBoolean("xdripstatus_showbgi", false) || profile == null || profile.getIsf(NSProfile.secondsFromMidnight()) == null || profile.getIc(NSProfile.secondsFromMidnight()) == null) {
return status;
}
double bgi = -(bolusIob.activity + basalIob.activity)*5*profile.getIsf(NSProfile.secondsFromMidnight());
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(NSProfile.secondsFromMidnight());
status += " " + ((bgi>=0)?"+":"") + DecimalFormatter.to2Decimal(bgi);
status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi);
return status;
}

View file

@ -14,35 +14,22 @@ import info.nightscout.androidaps.interfaces.Interval;
* Created by mike on 09.05.2017.
*/
public class OverlappingIntervals {
public class OverlappingIntervals<T extends Interval> {
private Handler sHandler = null;
private HandlerThread sHandlerThread = null;
private Object dataLock = new Object();
private LongSparseArray<T> rawData = new LongSparseArray<>(); // oldest at index 0
private static LongSparseArray<Interval> rawData = new LongSparseArray<>(); // oldest at index 0
public OverlappingIntervals() {
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(OverlappingIntervals.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
}
public OverlappingIntervals resetData() {
public OverlappingIntervals reset() {
rawData = new LongSparseArray<>();
return this;
}
public void add(Interval newInterval) {
public void add(T newInterval) {
rawData.put(newInterval.start(), newInterval);
merge();
}
public void add(List<Interval> list) {
for (Interval interval : list) {
public void add(List<T> list) {
for (T interval : list) {
rawData.put(interval.start(), interval);
}
merge();
@ -50,8 +37,8 @@ public class OverlappingIntervals {
private void merge() {
for (int index = 0; index < rawData.size() - 1; index++) {
Interval i = rawData.get(index);
long startOfNewer = rawData.get(index + 1).start();
Interval i = rawData.valueAt(index);
long startOfNewer = rawData.valueAt(index + 1).start();
if (i.originalEnd() > startOfNewer) {
i.cutEndTo(startOfNewer);
}
@ -61,18 +48,25 @@ public class OverlappingIntervals {
@Nullable
public Interval getValueByInterval(long time) {
int index = binarySearch(time);
if (index >= 0) return rawData.get(index);
if (index >= 0) return rawData.valueAt(index);
return null;
}
public List<Interval> getList() {
List<Interval> list = new ArrayList<>();
public List<T> getList() {
List<T> list = new ArrayList<>();
for (int i = 0; i < rawData.size(); i++)
list.add(rawData.valueAt(i));
return list;
}
private static int binarySearch(long value) {
public List<T> getReversedList() {
List<T> list = new ArrayList<>();
for (int i = rawData.size() -1; i>=0; i--)
list.add(rawData.valueAt(i));
return list;
}
private int binarySearch(long value) {
int lo = 0;
int hi = rawData.size() - 1;
@ -91,4 +85,15 @@ public class OverlappingIntervals {
return ~lo; // value not present
}
public int size() {
return rawData.size();
}
public T get(int index) {
return rawData.valueAt(index);
}
public T getReversed(int index) {
return rawData.valueAt(size() - 1 - index);
}
}

View file

@ -22,14 +22,15 @@
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="@string/tempbasals_iobtotal_label_string"
android:textStyle="bold" />
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/tempbasals_totaltempiob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>

View file

@ -5,10 +5,8 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardBackgroundColor="@color/cardColorBackground"
card_view:cardCornerRadius="6dp"
card_view:cardUseCompatPadding="true"
card_view:contentPadding="6dp">
card_view:cardBackgroundColor="?android:colorBackground"
>
<LinearLayout
android:layout_width="match_parent"
@ -16,7 +14,6 @@
android:orientation="vertical">
<LinearLayout
android:id="@+id/tempbasals_datelinearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="true"
@ -28,19 +25,16 @@
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical|right"
android:paddingLeft="5dp"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:text="{fa-clock-o}"
android:textColor="@color/cardItemLabel" />
android:text="{fa-clock-o}" />
<TextView
android:id="@+id/tempbasals_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="1.1.2000 18:00"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/cardItemLabel" />
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/tempbasals_absolute"
@ -48,8 +42,7 @@
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="0.25 U"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/cardItemLabel" />
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/tempbasals_percent"
@ -57,8 +50,7 @@
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="150%"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/cardItemLabel" />
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/tempbasals_duration"
@ -66,8 +58,7 @@
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="30 min"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/cardItemLabel" />
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/tempbasals_extendedflag"
@ -95,7 +86,6 @@
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:text="@string/tempbasals_realduration_label_string"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
@ -174,11 +164,23 @@
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/overview_quickwizard_item_remove_button"
android:layout_marginRight="10dp"
android:textAlignment="viewEnd"
android:textColor="@android:color/holo_orange_light" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_alignParentBottom="true"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
</LinearLayout>
</android.support.v7.widget.CardView>

View file

@ -37,7 +37,7 @@
<color name="colorTempTargetButton">#d43429</color>
<color name="colorInProgress">#c45026</color>
<color name="colorAffectingIOB">#830400</color>
<color name="colorActive">#1b5e20</color>
<color name="colorNotEnded">#190084</color>
<color name="colorPumpLabel">#779ECB</color>