Merge pull request #809 from MilosKozak/tdds-again-merged

Tdds again merged
This commit is contained in:
Milos Kozak 2018-03-28 17:35:23 +02:00 committed by GitHub
commit 259b5fa818
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 423 additions and 118 deletions

View file

@ -47,7 +47,7 @@
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".AgreementActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRStatsActivity" />
<activity android:name=".TDDStatsActivity" />
<activity android:name=".plugins.Overview.activities.QuickWizardListActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" />

View file

@ -1,11 +1,9 @@
package info.nightscout.androidaps.plugins.PumpDanaR.activities;
package info.nightscout.androidaps;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
@ -35,21 +33,26 @@ import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
public class DanaRStatsActivity extends Activity {
private static Logger log = LoggerFactory.getLogger(DanaRStatsActivity.class);
public class TDDStatsActivity extends Activity {
private static Logger log = LoggerFactory.getLogger(TDDStatsActivity.class);
TextView statusView, statsMessage, totalBaseBasal2;
EditText totalBaseBasal;
@ -60,10 +63,10 @@ public class DanaRStatsActivity extends Activity {
double magicNumber;
DecimalFormat decimalFormat;
List<DanaRHistoryRecord> historyList = new ArrayList<>();
List<DanaRHistoryRecord> dummies;
List<TDD> historyList = new ArrayList<>();
List<TDD> dummies;
public DanaRStatsActivity() {
public TDDStatsActivity() {
super();
}
@ -232,10 +235,10 @@ public class DanaRStatsActivity extends Activity {
statsMessage.setText(getString(R.string.danar_stats_warning_Message));
}
});
ConfigBuilderPlugin.getCommandQueue().loadHistory(RecordTypes.RECORD_TYPE_DAILY, new Callback() {
ConfigBuilderPlugin.getCommandQueue().loadTDDs( new Callback() {
@Override
public void run() {
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
loadDataFromDB();
runOnUiThread(new Runnable() {
@Override
public void run() {
@ -268,18 +271,18 @@ public class DanaRStatsActivity extends Activity {
} else {
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
loadDataFromDB();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(totalBaseBasal.getWindowToken(), 0);
}
}
});
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
loadDataFromDB();
}
private void loadDataFromDB(byte type) {
historyList = MainApp.getDbHelper().getDanaRHistoryRecordsByType(type);
private void loadDataFromDB() {
historyList = MainApp.getDbHelper().getTDDs();
//only use newest 10
historyList = historyList.subList(0, Math.min(10, historyList.size()));
@ -288,24 +291,24 @@ public class DanaRStatsActivity extends Activity {
dummies = new LinkedList();
DateFormat df = new SimpleDateFormat("dd.MM.");
for (int i = 0; i < historyList.size() - 1; i++) {
DanaRHistoryRecord elem1 = historyList.get(i);
DanaRHistoryRecord elem2 = historyList.get(i + 1);
TDD elem1 = historyList.get(i);
TDD elem2 = historyList.get(i + 1);
if (!df.format(new Date(elem1.recordDate)).equals(df.format(new Date(elem2.recordDate + 25 * 60 * 60 * 1000)))) {
DanaRHistoryRecord dummy = new DanaRHistoryRecord();
dummy.recordDate = elem1.recordDate - 24 * 60 * 60 * 1000;
dummy.recordDailyBasal = elem1.recordDailyBasal / 2;
dummy.recordDailyBolus = elem1.recordDailyBolus / 2;
if (!df.format(new Date(elem1.date)).equals(df.format(new Date(elem2.date + 25 * 60 * 60 * 1000)))) {
TDD dummy = new TDD();
dummy.date = elem1.date - 24 * 60 * 60 * 1000;
dummy.basal = elem1.basal / 2;
dummy.bolus = elem1.bolus / 2;
dummies.add(dummy);
elem1.recordDailyBasal /= 2;
elem1.recordDailyBolus /= 2;
elem1.basal /= 2;
elem1.bolus /= 2;
}
}
historyList.addAll(dummies);
Collections.sort(historyList, new Comparator<DanaRHistoryRecord>() {
Collections.sort(historyList, new Comparator<TDD>() {
@Override
public int compare(DanaRHistoryRecord lhs, DanaRHistoryRecord rhs) {
return (int) (rhs.recordDate - lhs.recordDate);
public int compare(TDD lhs, TDD rhs) {
return (int) (rhs.date - lhs.date);
}
});
@ -333,11 +336,13 @@ public class DanaRStatsActivity extends Activity {
double weighted05 = 0d;
double weighted07 = 0d;
for (DanaRHistoryRecord record : historyList) {
double tdd = record.recordDailyBolus + record.recordDailyBasal;
//TDD table
for (TDD record : historyList) {
double tdd = record.getTotal();
// Create the table row
TableRow tr = new TableRow(DanaRStatsActivity.this);
TableRow tr = new TableRow(TDDStatsActivity.this);
if (i % 2 != 0) tr.setBackgroundColor(Color.DKGRAY);
if (dummies.contains(record)) {
tr.setBackgroundColor(Color.argb(125, 255, 0, 0));
@ -348,31 +353,31 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically
TextView labelDATE = new TextView(DanaRStatsActivity.this);
TextView labelDATE = new TextView(TDDStatsActivity.this);
labelDATE.setId(200 + i);
labelDATE.setText(df.format(new Date(record.recordDate)));
labelDATE.setText(df.format(new Date(record.date)));
labelDATE.setTextColor(Color.WHITE);
tr.addView(labelDATE);
TextView labelBASAL = new TextView(DanaRStatsActivity.this);
TextView labelBASAL = new TextView(TDDStatsActivity.this);
labelBASAL.setId(300 + i);
labelBASAL.setText(DecimalFormatter.to2Decimal(record.recordDailyBasal) + " U");
labelBASAL.setText(DecimalFormatter.to2Decimal(record.basal) + " U");
labelBASAL.setTextColor(Color.WHITE);
tr.addView(labelBASAL);
TextView labelBOLUS = new TextView(DanaRStatsActivity.this);
TextView labelBOLUS = new TextView(TDDStatsActivity.this);
labelBOLUS.setId(400 + i);
labelBOLUS.setText(DecimalFormatter.to2Decimal(record.recordDailyBolus) + " U");
labelBOLUS.setText(DecimalFormatter.to2Decimal(record.bolus) + " U");
labelBOLUS.setTextColor(Color.WHITE);
tr.addView(labelBOLUS);
TextView labelTDD = new TextView(DanaRStatsActivity.this);
TextView labelTDD = new TextView(TDDStatsActivity.this);
labelTDD.setId(500 + i);
labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U");
labelTDD.setTextColor(Color.WHITE);
tr.addView(labelTDD);
TextView labelRATIO = new TextView(DanaRStatsActivity.this);
TextView labelRATIO = new TextView(TDDStatsActivity.this);
labelRATIO.setId(600 + i);
labelRATIO.setText(Math.round(100 * tdd / magicNumber) + " %");
labelRATIO.setTextColor(Color.WHITE);
@ -383,11 +388,23 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
sum = sum + tdd;
i++;
}
i = 0;
//cumulative TDDs
for (TDD record : historyList) {
if(!historyList.isEmpty() && df.format(new Date(record.date)).equals(df.format(new Date()))) {
//Today should not be included
continue;
}
i++;
sum = sum + record.getTotal();
// Create the cumtable row
TableRow ctr = new TableRow(DanaRStatsActivity.this);
TableRow ctr = new TableRow(TDDStatsActivity.this);
if (i % 2 == 0) ctr.setBackgroundColor(Color.DKGRAY);
ctr.setId(700 + i);
ctr.setLayoutParams(new TableLayout.LayoutParams(
@ -395,19 +412,19 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically
TextView labelDAYS = new TextView(DanaRStatsActivity.this);
TextView labelDAYS = new TextView(TDDStatsActivity.this);
labelDAYS.setId(800 + i);
labelDAYS.setText("" + i);
labelDAYS.setTextColor(Color.WHITE);
ctr.addView(labelDAYS);
TextView labelCUMTDD = new TextView(DanaRStatsActivity.this);
TextView labelCUMTDD = new TextView(TDDStatsActivity.this);
labelCUMTDD.setId(900 + i);
labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum / i) + " U");
labelCUMTDD.setTextColor(Color.WHITE);
ctr.addView(labelCUMTDD);
TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this);
TextView labelCUMRATIO = new TextView(TDDStatsActivity.this);
labelCUMRATIO.setId(1000 + i);
labelCUMRATIO.setText(Math.round(100 * sum / i / magicNumber) + " %");
labelCUMRATIO.setTextColor(Color.WHITE);
@ -419,7 +436,7 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT));
}
if (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).recordDate)).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24))))) {
if (isOldData(historyList)) {
statsMessage.setVisibility(View.VISIBLE);
statsMessage.setText(getString(R.string.danar_stats_olddata_Message));
@ -427,12 +444,17 @@ public class DanaRStatsActivity extends Activity {
tl.setBackgroundColor(Color.TRANSPARENT);
}
if(!historyList.isEmpty() && df.format(new Date(historyList.get(0).date)).equals(df.format(new Date()))) {
//Today should not be included
historyList.remove(0);
}
Collections.reverse(historyList);
i = 0;
for (DanaRHistoryRecord record : historyList) {
double tdd = record.recordDailyBolus + record.recordDailyBasal;
for (TDD record : historyList) {
double tdd = record.getTotal();
if (i == 0) {
weighted03 = tdd;
weighted05 = tdd;
@ -447,7 +469,7 @@ public class DanaRStatsActivity extends Activity {
}
// Create the exptable row
TableRow etr = new TableRow(DanaRStatsActivity.this);
TableRow etr = new TableRow(TDDStatsActivity.this);
if (i % 2 != 0) etr.setBackgroundColor(Color.DKGRAY);
etr.setId(1100 + i);
etr.setLayoutParams(new TableLayout.LayoutParams(
@ -455,13 +477,13 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically
TextView labelWEIGHT = new TextView(DanaRStatsActivity.this);
TextView labelWEIGHT = new TextView(TDDStatsActivity.this);
labelWEIGHT.setId(1200 + i);
labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7");
labelWEIGHT.setTextColor(Color.WHITE);
etr.addView(labelWEIGHT);
TextView labelEXPTDD = new TextView(DanaRStatsActivity.this);
TextView labelEXPTDD = new TextView(TDDStatsActivity.this);
labelEXPTDD.setId(1300 + i);
labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03)
+ " U\n" + DecimalFormatter.to2Decimal(weighted05)
@ -469,7 +491,7 @@ public class DanaRStatsActivity extends Activity {
labelEXPTDD.setTextColor(Color.WHITE);
etr.addView(labelEXPTDD);
TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this);
TextView labelEXPRATIO = new TextView(TDDStatsActivity.this);
labelEXPRATIO.setId(1400 + i);
labelEXPRATIO.setText(Math.round(100 * weighted03 / magicNumber) + " %\n"
+ Math.round(100 * weighted05 / magicNumber) + " %\n"
@ -516,4 +538,19 @@ public class DanaRStatsActivity extends Activity {
}
);
}
public static boolean isOldData(List<TDD> historyList) {
Object activePump = MainApp.getConfigBuilder().getActivePump();
PumpInterface dana = MainApp.getSpecificPlugin(DanaRPlugin.class);
PumpInterface danaRS = MainApp.getSpecificPlugin(DanaRSPlugin.class);
PumpInterface danaV2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
PumpInterface danaKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
PumpInterface insight = MainApp.getSpecificPlugin(InsightPlugin.class);
boolean startsYesterday = activePump == dana || activePump == danaRS || activePump == danaV2 || activePump == danaKorean || activePump == insight;
DateFormat df = new SimpleDateFormat("dd.MM.");
return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday?1000 * 60 * 60 * 24:0))))));
}
}

View file

@ -50,10 +50,12 @@ import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistor
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PercentageSplitter;
import info.nightscout.utils.ToastUtils;
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
@ -76,6 +78,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs";
private static final int DATABASE_VERSION = 8;
@ -124,6 +127,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
@ -227,6 +231,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
@ -236,6 +241,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
@ -323,6 +329,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleProfileSwitchChange();
}
public void resetTDDs() {
try {
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
// ------------------ getDao -------------------------------------------
@ -342,6 +356,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(DanaRHistoryRecord.class);
}
private Dao<TDD, String> getDaoTDD() throws SQLException {
return getDao(TDD.class);
}
private Dao<DbRequest, String> getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
@ -495,6 +513,34 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<BgReading>();
}
// ------------------- TDD handling -----------------------
public void createOrUpdateTDD(TDD tdd){
try {
Dao<TDD, String> dao = getDaoTDD();
dao.createOrUpdate(tdd);
} catch (SQLException e) {
ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception");
log.error("Unhandled exception", e);
}
}
public List<TDD> getTDDs() {
List<TDD> tddList;
try {
QueryBuilder<TDD, String> queryBuilder = getDaoTDD().queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(10L);
PreparedQuery<TDD> preparedQuery = queryBuilder.prepare();
tddList = getDaoTDD().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
tddList = new ArrayList<>();
}
return tddList;
}
// ------------- DbRequests handling -------------------
public void create(DbRequest dbr) {
@ -940,6 +986,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createOrUpdate(DanaRHistoryRecord record) {
try {
getDaoDanaRHistory().createOrUpdate(record);
//If it is a TDD, store it for stats also.
if(record.recordCode == RecordTypes.RECORD_TYPE_DAILY){
createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0));
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}

View file

@ -0,0 +1,46 @@
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.Objects;
/**
* Created by mike on 20.09.2017.
*/
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS)
public class TDD {
private static Logger log = LoggerFactory.getLogger(TDD.class);
@DatabaseField(id = true)
public long date;
@DatabaseField
public double bolus;
@DatabaseField
public double basal;
@DatabaseField
public double total;
public double getTotal(){
return (total > 0d) ? total:(bolus+basal);
}
public TDD() { }
public TDD(long date, double bolus, double basal, double total){
this.date = date;
this.bolus = bolus;
this.basal = basal;
this.total = total;
}
}

View file

@ -54,4 +54,7 @@ public interface PumpInterface {
String shortStatus(boolean veryShort);
boolean isFakingTempsByExtendedBoluses();
PumpEnactResult loadTDDs();
}

View file

@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.Actions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
@ -14,6 +15,7 @@ import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.HistoryBrowseActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.ExtendedBolus;
@ -31,6 +33,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.TDDStatsActivity;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SingleClickButton;
@ -52,6 +55,8 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
SingleClickButton tempBasal;
SingleClickButton tempBasalCancel;
SingleClickButton fill;
SingleClickButton tddStats;
SingleClickButton history;
public ActionsFragment() {
super();
@ -71,6 +76,9 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasal = (SingleClickButton) view.findViewById(R.id.actions_settempbasal);
tempBasalCancel = (SingleClickButton) view.findViewById(R.id.actions_canceltempbasal);
fill = (SingleClickButton) view.findViewById(R.id.actions_fill);
tddStats = view.findViewById(R.id.actions_tddstats);
history = view.findViewById(R.id.actions_historybrowser);
profileSwitch.setOnClickListener(this);
tempTarget.setOnClickListener(this);
@ -79,6 +87,8 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasal.setOnClickListener(this);
tempBasalCancel.setOnClickListener(this);
fill.setOnClickListener(this);
history.setOnClickListener(this);
tddStats.setOnClickListener(this);
updateGUI();
return view;
@ -228,6 +238,12 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
FillDialog fillDialog = new FillDialog();
fillDialog.show(manager, "FillDialog");
break;
case R.id.actions_historybrowser:
startActivity(new Intent(getContext(), HistoryBrowseActivity.class));
break;
case R.id.actions_tddstats:
startActivity(new Intent(getContext(), TDDStatsActivity.class));
break;
}
}
}

View file

@ -12,7 +12,9 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -24,6 +26,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventInitializationChanged;
@ -50,6 +53,7 @@ import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.WarningOrError
import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.Bolus;
import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.PumpHistory;
import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.PumpHistoryRequest;
import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.Tdd;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.DateUtil;
@ -1433,6 +1437,37 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf
return false;
}
@Override
public PumpEnactResult loadTDDs() {
PumpEnactResult result = new PumpEnactResult();
result.success = readHistory(new PumpHistoryRequest().tddHistory(PumpHistoryRequest.FULL));
if (result.success) {
List<Tdd> tdds = pump.tddHistory;
if (tdds != null) {
HashMap<Long, TDD> map = new HashMap<>();
for (int i = 0; i < tdds.size(); i++) {
Tdd currTdd = tdds.get(i);
if(currTdd.total < 1) continue; //cases where dummy days are introduced (e.g. Battery change with date loss)
if(map.containsKey(currTdd.timestamp)){
//duplicate days on time changes
TDD existing = map.get(currTdd.timestamp);
existing.total += currTdd.total;
} else {
map.put(currTdd.timestamp, new TDD(currTdd.timestamp, 0d, 0d, currTdd.total));
}
}
Collection<TDD> uniqueColl = map.values();
for (TDD currTdd: uniqueColl) {
MainApp.getDbHelper().createOrUpdateTDD(currTdd);
}
}
}
return result;
}
// Constraints interface
private long lowSuspendOnlyLoopEnforcedUntil = 0;
private long violationWarningRaisedForBolusAt = 0;
@ -1451,4 +1486,4 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf
maxIob.setIfSmaller(0d, String.format(MainApp.gs(R.string.limitingmaxiob), 0d, MainApp.gs(R.string.unsafeusage)), this);
return maxIob;
}
}
}

View file

@ -173,8 +173,9 @@ public class ReadHistoryCommand extends BaseCommand {
}
Calendar calendar = Calendar.getInstance();
calendar.set(year, date.getMonth() - 1, date.getDay(), 0, 0, 0);
return new Tdd(calendar.getTimeInMillis(), dailyTotal);
long time = calendar.getTimeInMillis();
time = time - time%1000;
return new Tdd(time, dailyTotal);
}
private void readTbrRecords(long requestedTime) {

View file

@ -28,6 +28,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotificati
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractDanaRExecutionService;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@ -472,6 +473,11 @@ public abstract class AbstractDanaRPlugin implements PluginBase, PumpInterface,
return pump.createConvertedProfileName();
}
@Override
public PumpEnactResult loadTDDs() {
return loadHistory(RecordTypes.RECORD_TYPE_DAILY);
}
// Reply for sms communicator
public String shortStatus(boolean veryShort) {
String ret = "";

View file

@ -11,7 +11,6 @@ import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
@ -21,12 +20,9 @@ import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.ExtendedBolus;
@ -37,7 +33,7 @@ import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.Dialogs.ProfileViewDialog;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRHistoryActivity;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRStatsActivity;
import info.nightscout.androidaps.TDDStatsActivity;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.queue.events.EventQueueChanged;
import info.nightscout.utils.DateUtil;
@ -119,7 +115,7 @@ public class DanaRFragment extends SubscriberFragment {
}
@OnClick(R.id.danar_stats) void onStatsClick() {
startActivity(new Intent(getContext(), DanaRStatsActivity.class));
startActivity(new Intent(getContext(), TDDStatsActivity.class));
}
@OnClick(R.id.danar_btconnection) void onBtConnectionClick() {

View file

@ -42,6 +42,7 @@ import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSDeviceChange;
import info.nightscout.androidaps.plugins.PumpDanaRS.services.DanaRSService;
import info.nightscout.utils.DateUtil;
@ -796,4 +797,9 @@ public class DanaRSPlugin implements PluginBase, PumpInterface, DanaRInterface,
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
@Override
public PumpEnactResult loadTDDs() {
return loadHistory(RecordTypes.RECORD_TYPE_DAILY);
}
}

View file

@ -262,6 +262,13 @@ public class InsightPlugin implements PluginBase, PumpInterface, ConstraintsInte
return false;
}
@Override
public PumpEnactResult loadTDDs() {
//TODO: read TDDs and store to DB
PumpEnactResult result = new PumpEnactResult();
return result;
}
@Override
public boolean isInitialized() {
return initialized;

View file

@ -114,6 +114,13 @@ public class MDIPlugin implements PluginBase, PumpInterface {
return false;
}
@Override
public PumpEnactResult loadTDDs() {
//no result, could read DB in the future?
PumpEnactResult result = new PumpEnactResult();
return result;
}
@Override
public boolean isInitialized() {
return true;

View file

@ -175,6 +175,13 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
return (Config.NSCLIENT || Config.G5UPLOADER) && fromNSAreCommingFakedExtendedBoluses;
}
@Override
public PumpEnactResult loadTDDs() {
//no result, could read DB in the future?
PumpEnactResult result = new PumpEnactResult();
return result;
}
@Override
public boolean isInitialized() {
return true;

View file

@ -6,9 +6,11 @@ import android.support.annotation.NonNull;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
@ -19,10 +21,10 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
@ -36,10 +38,10 @@ import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil;
@ -269,23 +271,10 @@ public class ActionStringHandler {
} else if ("tddstats".equals(act[0])) {
Object activePump = MainApp.getConfigBuilder().getActivePump();
PumpInterface dana = MainApp.getSpecificPlugin(DanaRPlugin.class);
PumpInterface danaRS = MainApp.getSpecificPlugin(DanaRSPlugin.class);
PumpInterface danaV2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
PumpInterface danaKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
if ((dana == null || dana != activePump) &&
(danaV2 == null || danaV2 != activePump) &&
(danaKorean == null || danaKorean != activePump) &&
(danaRS == null || danaRS != activePump)
) {
sendError("Pump does not support TDDs!");
return;
} else {
if (activePump!= null) {
// check if DB up to date
List<DanaRHistoryRecord> dummies = new LinkedList<DanaRHistoryRecord>();
List<DanaRHistoryRecord> historyList = getTDDList(dummies);
List<TDD> dummies = new LinkedList<TDD>();
List<TDD> historyList = getTDDList(dummies);
if (isOldData(historyList)) {
rTitle = "TDD";
@ -299,13 +288,13 @@ public class ActionStringHandler {
} else {
rMessage += "trying to fetch data from pump.";
ConfigBuilderPlugin.getCommandQueue().loadHistory(RecordTypes.RECORD_TYPE_DAILY, new Callback() {
ConfigBuilderPlugin.getCommandQueue().loadTDDs(new Callback() {
@Override
public void run() {
List<DanaRHistoryRecord> dummies = new LinkedList<DanaRHistoryRecord>();
List<DanaRHistoryRecord> historyList = getTDDList(dummies);
List<TDD> dummies = new LinkedList<TDD>();
List<TDD> historyList = getTDDList(dummies);
if (isOldData(historyList)) {
sendStatusmessage("TDD", "TDD: Still old data! Cannot load from pump.");
sendStatusmessage("TDD", "TDD: Still old data! Cannot load from pump.\n" + generateTDDMessage(historyList, dummies));
} else {
sendStatusmessage("TDD", generateTDDMessage(historyList, dummies));
}
@ -329,7 +318,7 @@ public class ActionStringHandler {
lastConfirmActionString = rAction;
}
private static String generateTDDMessage(List<DanaRHistoryRecord> historyList, List<DanaRHistoryRecord> dummies) {
private static String generateTDDMessage(List<TDD> historyList, List<TDD> dummies) {
Profile profile = MainApp.getConfigBuilder().getProfile();
@ -337,11 +326,27 @@ public class ActionStringHandler {
return "No profile loaded :(";
}
if(historyList.isEmpty()){
return "No history data!";
}
DateFormat df = new SimpleDateFormat("dd.MM.");
String message = "";
double refTDD = profile.baseBasalSum() * 2;
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
if(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date()))){
double tdd = historyList.get(0).getTotal();
historyList.remove(0);
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n";
message += "\n";
} else if (pump != null && pump instanceof DanaRPlugin) {
double tdd = DanaRPump.getInstance().dailyTotalUnits;
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n";
message += "\n";
}
int i = 0;
double sum = 0d;
double weighted03 = 0d;
@ -349,8 +354,8 @@ public class ActionStringHandler {
double weighted07 = 0d;
Collections.reverse(historyList);
for (DanaRHistoryRecord record : historyList) {
double tdd = record.recordDailyBolus + record.recordDailyBasal;
for (TDD record : historyList) {
double tdd = record.getTotal();
if (i == 0) {
weighted03 = tdd;
weighted05 = tdd;
@ -368,59 +373,63 @@ public class ActionStringHandler {
message += "0.5: " + DecimalFormatter.to2Decimal(weighted05) + "U " + (DecimalFormatter.to0Decimal(100 * weighted05 / refTDD) + "%") + "\n";
message += "0.7: " + DecimalFormatter.to2Decimal(weighted07) + "U " + (DecimalFormatter.to0Decimal(100 * weighted07 / refTDD) + "%") + "\n";
message += "\n";
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
if (pump != null && pump instanceof DanaRPlugin) {
double tdd = DanaRPump.getInstance().dailyTotalUnits;
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n";
message += "\n";
}
Collections.reverse(historyList);
//add TDDs:
Collections.reverse(historyList);
for (DanaRHistoryRecord record : historyList) {
double tdd = record.recordDailyBolus + record.recordDailyBasal;
message += df.format(new Date(record.recordDate)) + " " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + (dummies.contains(record) ? "x" : "") + "\n";
for (TDD record : historyList) {
double tdd = record.getTotal();
message += df.format(new Date(record.date)) + " " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + (dummies.contains(record) ? "x" : "") + "\n";
}
return message;
}
public static boolean isOldData(List<DanaRHistoryRecord> historyList) {
public static boolean isOldData(List<TDD> historyList) {
Object activePump = MainApp.getConfigBuilder().getActivePump();
PumpInterface dana = MainApp.getSpecificPlugin(DanaRPlugin.class);
PumpInterface danaRS = MainApp.getSpecificPlugin(DanaRSPlugin.class);
PumpInterface danaV2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
PumpInterface danaKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
PumpInterface insight = MainApp.getSpecificPlugin(InsightPlugin.class);
boolean startsYesterday = activePump == dana || activePump == danaRS || activePump == danaV2 || activePump == danaKorean || activePump == insight;
DateFormat df = new SimpleDateFormat("dd.MM.");
return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).recordDate)).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)))));
return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday?1000 * 60 * 60 * 24:0))))));
}
@NonNull
public static List<DanaRHistoryRecord> getTDDList(List<DanaRHistoryRecord> returnDummies) {
List<DanaRHistoryRecord> historyList = MainApp.getDbHelper().getDanaRHistoryRecordsByType(RecordTypes.RECORD_TYPE_DAILY);
public static List<TDD> getTDDList(List<TDD> returnDummies) {
List<TDD> historyList = MainApp.getDbHelper().getTDDs();
//only use newest 10
historyList = historyList.subList(0, Math.min(10, historyList.size()));
//fill single gaps
List<DanaRHistoryRecord> dummies = (returnDummies != null) ? returnDummies : (new LinkedList());
//fill single gaps - only needed for Dana*R data
List<TDD> dummies = (returnDummies != null) ? returnDummies : (new LinkedList());
DateFormat df = new SimpleDateFormat("dd.MM.");
for (int i = 0; i < historyList.size() - 1; i++) {
DanaRHistoryRecord elem1 = historyList.get(i);
DanaRHistoryRecord elem2 = historyList.get(i + 1);
TDD elem1 = historyList.get(i);
TDD elem2 = historyList.get(i + 1);
if (!df.format(new Date(elem1.recordDate)).equals(df.format(new Date(elem2.recordDate + 25 * 60 * 60 * 1000)))) {
DanaRHistoryRecord dummy = new DanaRHistoryRecord();
dummy.recordDate = elem1.recordDate - 24 * 60 * 60 * 1000;
dummy.recordDailyBasal = elem1.recordDailyBasal / 2;
dummy.recordDailyBolus = elem1.recordDailyBolus / 2;
if (!df.format(new Date(elem1.date)).equals(df.format(new Date(elem2.date + 25 * 60 * 60 * 1000)))) {
TDD dummy = new TDD();
dummy.date = elem1.date - 24 * 60 * 60 * 1000;
dummy.basal = elem1.basal / 2;
dummy.bolus = elem1.bolus / 2;
dummies.add(dummy);
elem1.recordDailyBasal /= 2;
elem1.recordDailyBolus /= 2;
elem1.basal /= 2;
elem1.bolus /= 2;
}
}
historyList.addAll(dummies);
Collections.sort(historyList, new Comparator<DanaRHistoryRecord>() {
Collections.sort(historyList, new Comparator<TDD>() {
@Override
public int compare(DanaRHistoryRecord lhs, DanaRHistoryRecord rhs) {
return (int) (rhs.recordDate - lhs.recordDate);
public int compare(TDD lhs, TDD rhs) {
return (int) (rhs.date - lhs.date);
}
});
return historyList;
}

View file

@ -33,6 +33,7 @@ import info.nightscout.androidaps.queue.commands.CommandCancelTempBasal;
import info.nightscout.androidaps.queue.commands.CommandExtendedBolus;
import info.nightscout.androidaps.queue.commands.CommandLoadEvents;
import info.nightscout.androidaps.queue.commands.CommandLoadHistory;
import info.nightscout.androidaps.queue.commands.CommandLoadTDDs;
import info.nightscout.androidaps.queue.commands.CommandReadStatus;
import info.nightscout.androidaps.queue.commands.CommandSMBBolus;
import info.nightscout.androidaps.queue.commands.CommandSetProfile;
@ -391,6 +392,25 @@ public class CommandQueue {
return true;
}
// returns true if command is queued
public boolean loadTDDs(Callback callback) {
if (isRunning(Command.CommandType.LOADHISTORY)) {
if (callback != null)
callback.result(executingNowError()).run();
return false;
}
// remove all unfinished
removeAll(Command.CommandType.LOADHISTORY);
// add new command to queue
add(new CommandLoadTDDs(callback));
notifyAboutNewCommand();
return true;
}
// returns true if command is queued
public boolean loadEvents(Callback callback) {
if (isRunning(Command.CommandType.LOADEVENTS)) {

View file

@ -16,7 +16,7 @@ public abstract class Command {
EXTENDEDBOLUS,
BASALPROFILE,
READSTATUS,
LOADHISTORY, // so far only Dana specific
LOADHISTORY, // TDDs and so far only Dana specific
LOADEVENTS // so far only Dana specific
}

View file

@ -0,0 +1,31 @@
package info.nightscout.androidaps.queue.commands;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.queue.Callback;
/**
* Created by mike on 10.11.2017.
*/
public class CommandLoadTDDs extends Command {
public CommandLoadTDDs(Callback callback) {
commandType = CommandType.LOADHISTORY; //belongs to the history group of commands
this.callback = callback;
}
@Override
public void execute() {
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
PumpEnactResult r = pump.loadTDDs();
if (callback != null)
callback.result(r).run();
}
@Override
public String status() {
return "LOADTDDS";
}
}

View file

@ -104,6 +104,32 @@
android:drawableTop="@drawable/icon_cp_pump_canula"
android:text="@string/primefill" />
<info.nightscout.utils.SingleClickButton
android:id="@+id/actions_historybrowser"
style="?android:attr/buttonStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_danarhistory"
android:text="@string/nav_historybrowser" />
<info.nightscout.utils.SingleClickButton
android:id="@+id/actions_tddstats"
style="?android:attr/buttonStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_danarstats"
android:text="@string/danar_stats_tdd" />
</LinearLayout>
</ScrollView>

View file

@ -34,7 +34,7 @@
android:gravity="center_horizontal"
android:textColor="@color/mdtp_white"
android:background="@drawable/pillborder"
android:text="@string/danar_stats" />
android:text="@string/danar_stats_tdd" />
<TableLayout
android:stretchColumns="0,1,2,3,4"