Merge branch 'history' of https://github.com/MilosKozak/AndroidAPS into history

This commit is contained in:
Milos Kozak 2017-06-04 22:38:42 +02:00
commit 8934d2d6b9
109 changed files with 3114 additions and 1275 deletions

View file

@ -11,15 +11,15 @@ public class Config {
public static final boolean LOOPENABLED = APS;
public static final boolean WEAR = BuildConfig.WEAR;
public static final boolean NSCLIENT = BuildConfig.NSCLIENTOLNY;
public static final boolean DANAR = true && BuildConfig.PUMPDRIVERS;
public static final boolean DANARv2 = true;
public static final boolean DANARv2 = true && BuildConfig.PUMPDRIVERS;
public static final boolean ACTION = !BuildConfig.NSCLIENTOLNY;
public static final boolean VIRTUALPUMP = !BuildConfig.NSCLIENTOLNY;
public static final boolean MDI = !BuildConfig.NSCLIENTOLNY;
public static final boolean OTHERPROFILES = !BuildConfig.NSCLIENTOLNY;
public static final boolean TEMPBASALS = !BuildConfig.NSCLIENTOLNY;
public static final boolean SAFETY = !BuildConfig.NSCLIENTOLNY;
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY;
@ -41,6 +41,7 @@ public class Config {
public static final boolean logPumpActions = true;
public static final boolean logSMSComm = true;
public static final boolean logCongigBuilderActions = true;
public static final boolean logAutosensData = false;
// DanaR specific
public static final boolean logDanaBTComm = true;

View file

@ -19,7 +19,6 @@ import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.util.AttributeSet;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
@ -163,7 +162,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
log.debug("Requesting ignore battery optimization");
OKDialog.show(this, getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() {
OKDialog.show(getParent(), getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() {
@Override
public void run() {
@ -296,7 +295,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle(getString(R.string.app_name) + " " + BuildConfig.VERSION);
if (BuildConfig.NSCLIENTOLNY)
if (Config.NSCLIENT)
builder.setIcon(R.mipmap.yellowowl);
else
builder.setIcon(R.mipmap.blueowl);

View file

@ -114,9 +114,12 @@ public class MainApp extends Application {
pluginsList.add(TreatmentsFragment.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyFragment.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceXdripFragment.getPlugin());
pluginsList.add(SourceNSClientFragment.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceMM640gFragment.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceGlimpFragment.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorFragment.getPlugin());

View file

@ -2,9 +2,7 @@ package info.nightscout.androidaps.Services;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import org.json.JSONArray;
@ -22,19 +20,16 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin;
@ -84,7 +79,7 @@ public class DataService extends IntentService {
glimpEnabled = true;
}
boolean isNSProfile = ConfigBuilderPlugin.getActiveProfile().getClass().equals(NSProfilePlugin.class);
boolean isNSProfile = ConfigBuilderPlugin.getActiveProfileInterface().getClass().equals(NSProfilePlugin.class);
boolean nsUploadOnly = SP.getBoolean(R.string.key_ns_upload_only, false);
@ -325,25 +320,12 @@ public class DataService extends IntentService {
try {
String activeProfile = bundles.getString("activeprofile");
String profile = bundles.getString("profile");
NSProfile nsProfile = new NSProfile(new JSONObject(profile), activeProfile);
MainApp.bus().post(new EventNewBasalProfile(nsProfile, "NSClient"));
ProfileStore profileStore = new ProfileStore(new JSONObject(profile));
NSProfilePlugin.storeNewProfile(profileStore);
MainApp.bus().post(new EventNewBasalProfile());
PumpInterface pump = MainApp.getConfigBuilder();
if (pump != null) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (SP.getBoolean("syncprofiletopump", false)) {
if (pump.setNewBasalProfile(nsProfile) == PumpInterface.SUCCESS) {
SmsCommunicatorPlugin smsCommunicatorPlugin = (SmsCommunicatorPlugin) MainApp.getSpecificPlugin(SmsCommunicatorPlugin.class);
if (smsCommunicatorPlugin != null && smsCommunicatorPlugin.isEnabled(PluginBase.GENERAL)) {
smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.sResources.getString(R.string.profile_set_ok));
}
}
}
} else {
log.error("No active pump selected");
}
if (Config.logIncommingData)
log.debug("Received profile: " + activeProfile + " " + profile);
log.debug("Received profileStore: " + activeProfile + " " + profile);
} catch (JSONException e) {
e.printStackTrace();
}
@ -462,6 +444,7 @@ public class DataService extends IntentService {
MainApp.getDbHelper().deleteTempBasalById(_id);
MainApp.getDbHelper().deleteExtendedBolusById(_id);
MainApp.getDbHelper().deleteCareportalEventById(_id);
MainApp.getDbHelper().deleteProfileSwitchById(_id);
}
private void handleAddChangeDataFromNS(String trstring) throws JSONException {
@ -472,6 +455,7 @@ public class DataService extends IntentService {
handleAddChangeExtendedBolusRecord(trJson);
handleAddChangeCareportalEventRecord(trJson);
handleAddChangeTreatmentRecord(trJson);
handleAddChangeProfileSwitchRecord(trJson);
}
public void handleDanaRHistoryRecords(JSONObject trJson) {
@ -517,7 +501,8 @@ public class DataService extends IntentService {
if (trJson.has("eventType") && (
trJson.getString("eventType").equals(CareportalEvent.SITECHANGE) ||
trJson.getString("eventType").equals(CareportalEvent.INSULINCHANGE) ||
trJson.getString("eventType").equals(CareportalEvent.SENSORCHANGE)
trJson.getString("eventType").equals(CareportalEvent.SENSORCHANGE) ||
trJson.getString("eventType").equals(CareportalEvent.PUMPBATTERYCHANGE)
)) {
if (Config.logIncommingData)
log.debug("Processing CareportalEvent record: " + trJson.toString());
@ -525,6 +510,14 @@ public class DataService extends IntentService {
}
}
public void handleAddChangeProfileSwitchRecord(JSONObject trJson) throws JSONException {
if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.PROFILESWITCH)) {
if (Config.logIncommingData)
log.debug("Processing ProfileSwitch record: " + trJson.toString());
MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson);
}
}
private void handleNewSMS(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;

View file

@ -1,13 +1,10 @@
package info.nightscout.androidaps.data;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round;

View file

@ -1,7 +1,5 @@
package info.nightscout.utils;
package info.nightscout.androidaps.data;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
@ -14,6 +12,8 @@ import info.nightscout.androidaps.interfaces.Interval;
* Created by mike on 09.05.2017.
*/
// Zero duration means end of interval
public class OverlappingIntervals<T extends Interval> {
private LongSparseArray<T> rawData = new LongSparseArray<>(); // oldest at index 0

View file

@ -0,0 +1,347 @@
package info.nightscout.androidaps.data;
import com.crashlytics.android.Crashlytics;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
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.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils;
public class Profile {
private static Logger log = LoggerFactory.getLogger(Profile.class);
private JSONObject json;
private String units = null;
double dia = Constants.defaultDIA;
TimeZone timeZone = TimeZone.getDefault();
JSONArray isf;
JSONArray ic;
JSONArray basal;
JSONArray targetLow;
JSONArray targetHigh;
public Profile(JSONObject json, String units) {
this(json);
if (this.units == null) {
if (units != null)
this.units = units;
else {
Crashlytics.log("Profile failover failed too");
this.units = Constants.MGDL;
}
}
}
public Profile(JSONObject json) {
this.json = json;
try {
if (json.has("units"))
units = json.getString("units").toLowerCase();
if (json.has("dia"))
dia = json.getDouble("dia");
if (json.has("dia"))
dia = json.getDouble("dia");
if (json.has("timezone"))
timeZone = TimeZone.getTimeZone(json.getString("timezone"));
isf = json.getJSONArray("sens");
if (getIsf(0) == null) {
int defaultISF = units.equals(Constants.MGDL) ? 400 : 20;
isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultISF + "\",\"timeAsSeconds\":\"0\"}]");
Notification noisf = new Notification(Notification.ISF_MISSING, MainApp.sResources.getString(R.string.isfmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noisf));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.ISF_MISSING));
}
ic = json.getJSONArray("carbratio");
if (getIc(0) == null) {
int defaultIC = 25;
isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultIC + "\",\"timeAsSeconds\":\"0\"}]");
Notification noic = new Notification(Notification.IC_MISSING, MainApp.sResources.getString(R.string.icmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noic));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.IC_MISSING));
}
basal = json.getJSONArray("basal");
if (getBasal(0) == null) {
double defaultBasal = 0.1d;
isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultBasal + "\",\"timeAsSeconds\":\"0\"}]");
Notification nobasal = new Notification(Notification.BASAL_MISSING, MainApp.sResources.getString(R.string.basalmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(nobasal));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.BASAL_MISSING));
}
targetLow = json.getJSONArray("target_low");
if (getTargetLow(0) == null) {
double defaultLow = units.equals(Constants.MGDL) ? 120 : 6;
isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultLow + "\",\"timeAsSeconds\":\"0\"}]");
Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notarget));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING));
}
targetHigh = json.getJSONArray("target_high");
if (getTargetHigh(0) == null) {
double defaultHigh = units.equals(Constants.MGDL) ? 160 : 8;
isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultHigh + "\",\"timeAsSeconds\":\"0\"}]");
Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notarget));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING));
}
} catch (JSONException e) {
e.printStackTrace();
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.invalidprofile));
}
}
public String log() {
String ret = "\n";
for (Integer hour = 0; hour < 24; hour++) {
double value = getBasal(hour * 60 * 60);
ret += "NS basal value for " + hour + ":00 is " + value + "\n";
}
ret += "NS units: " + getUnits();
return ret;
}
public JSONObject getData() {
return json;
}
public Double getDia() {
return dia;
}
// mmol or mg/dl
public String getUnits() {
return units;
}
public TimeZone getTimeZone() {
return timeZone;
}
private Double getValueToTime(JSONArray array, Integer timeAsSeconds) {
Double lastValue = null;
for (Integer index = 0; index < array.length(); index++) {
try {
JSONObject o = array.getJSONObject(index);
Integer tas = o.getInt("timeAsSeconds");
Double value = o.getDouble("value");
if (lastValue == null) lastValue = value;
if (timeAsSeconds < tas) {
break;
}
lastValue = value;
} catch (JSONException e) {
e.printStackTrace();
}
}
return lastValue;
}
private String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) {
String retValue = "";
for (Integer index = 0; index < array.length(); index++) {
try {
JSONObject o = array.getJSONObject(index);
retValue += o.getString("time");
retValue += " ";
retValue += format.format(o.getDouble("value"));
if (array2 != null) {
JSONObject o2 = array2.getJSONObject(index);
retValue += " - ";
retValue += format.format(o2.getDouble("value"));
}
retValue += " " + units;
retValue += "\n";
} catch (JSONException e) {
e.printStackTrace();
}
}
return retValue;
}
public Double getIsf() {
return getIsf(secondsFromMidnight(new Date().getTime()));
}
public Double getIsf(long time) {
return getIsf(secondsFromMidnight(time));
}
public Double getIsf(Integer timeAsSeconds) {
return getValueToTime(isf, timeAsSeconds);
}
public String getIsfList() {
return getValuesList(isf, null, new DecimalFormat("0.0"), getUnits() + "/U");
}
public Double getIc() {
return getIc(secondsFromMidnight(new Date().getTime()));
}
public Double getIc(long time) {
return getIc(secondsFromMidnight(time));
}
public Double getIc(Integer timeAsSeconds) {
return getValueToTime(ic, timeAsSeconds);
}
public String getIcList() {
return getValuesList(ic, null, new DecimalFormat("0.0"), getUnits() + "/U");
}
public Double getBasal() {
return getBasal(secondsFromMidnight(new Date().getTime()));
}
public Double getBasal(long time) {
return getBasal(secondsFromMidnight(time));
}
public Double getBasal(Integer timeAsSeconds) {
return getValueToTime(basal, timeAsSeconds);
}
public String getBasalList() {
return getValuesList(basal, null, new DecimalFormat("0.00"), "U");
}
public class BasalValue {
public BasalValue(Integer timeAsSeconds, Double value) {
this.timeAsSeconds = timeAsSeconds;
this.value = value;
}
public Integer timeAsSeconds;
public Double value;
}
public BasalValue[] getBasalValues() {
try {
BasalValue[] ret = new BasalValue[basal.length()];
for (Integer index = 0; index < basal.length(); index++) {
JSONObject o = basal.getJSONObject(index);
Integer tas = o.getInt("timeAsSeconds");
Double value = o.getDouble("value");
ret[index] = new BasalValue(tas, value);
}
return ret;
} catch (JSONException e) {
e.printStackTrace();
}
return new BasalValue[0];
}
public Double getTargetLow() {
return getTargetLow(secondsFromMidnight(new Date().getTime()));
}
public Double getTargetLow(long time) {
return getTargetLow(secondsFromMidnight(time));
}
public Double getTargetLow(Integer timeAsSeconds) {
return getValueToTime(targetLow, timeAsSeconds);
}
public Double getTargetHigh() {
return getTargetHigh(secondsFromMidnight(new Date().getTime()));
}
public Double getTargetHigh(long time) {
return getTargetHigh(secondsFromMidnight(time));
}
public Double getTargetHigh(Integer timeAsSeconds) {
return getValueToTime(targetHigh, timeAsSeconds);
}
public String getTargetList() {
return getValuesList(targetLow, targetHigh, new DecimalFormat("0.0"), getUnits());
}
public double getMaxDailyBasal() {
Double max = 0d;
for (Integer hour = 0; hour < 24; hour++) {
double value = getBasal(hour * 60 * 60);
if (value > max) max = value;
}
return max;
}
public static Integer secondsFromMidnight() {
Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static Integer secondsFromMidnight(Date date) {
Calendar c = Calendar.getInstance();
long now = date.getTime();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static Integer secondsFromMidnight(long date) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = date - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static Double toMgdl(Double value, String units) {
if (units.equals(Constants.MGDL)) return value;
else return value * Constants.MMOLL_TO_MGDL;
}
public static Double fromMgdlToUnits(Double value, String units) {
if (units.equals(Constants.MGDL)) return value;
else return value * Constants.MGDL_TO_MMOLL;
}
public static Double toUnits(Double valueInMgdl, Double valueInMmol, String units) {
if (units.equals(Constants.MGDL)) return valueInMgdl;
else return valueInMmol;
}
public static String toUnitsString(Double valueInMgdl, Double valueInMmol, String units) {
if (units.equals(Constants.MGDL)) return DecimalFormatter.to0Decimal(valueInMgdl);
else return DecimalFormatter.to1Decimal(valueInMmol);
}
}

View file

@ -0,0 +1,109 @@
package info.nightscout.androidaps.data;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.interfaces.Interval;
/**
* Created by mike on 09.05.2017.
*/
// Zero duration means profile is valid until is chaged
// When no interval match the lastest record without duration is used
public class ProfileIntervals<T extends Interval> {
private LongSparseArray<T> rawData = new LongSparseArray<>(); // oldest at index 0
public ProfileIntervals reset() {
rawData = new LongSparseArray<>();
return this;
}
public void add(T newInterval) {
rawData.put(newInterval.start(), newInterval);
merge();
}
public void add(List<T> list) {
for (T interval : list) {
rawData.put(interval.start(), interval);
}
merge();
}
private void merge() {
for (int index = 0; index < rawData.size() - 1; index++) {
Interval i = rawData.valueAt(index);
long startOfNewer = rawData.valueAt(index + 1).start();
if (i.originalEnd() > startOfNewer) {
i.cutEndTo(startOfNewer);
}
}
}
@Nullable
public Interval getValueToTime(long time) {
int index = binarySearch(time);
if (index >= 0) return rawData.valueAt(index);
return null;
}
public List<T> getList() {
List<T> list = new ArrayList<>();
for (int i = 0; i < rawData.size(); i++)
list.add(rawData.valueAt(i));
return list;
}
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) {
if (rawData.size() == 0)
return -1;
int lo = 0;
int hi = rawData.size() - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
final Interval midVal = rawData.valueAt(mid);
if (midVal.match(value)) {
return mid; // value found
} else if (midVal.before(value)) {
lo = mid + 1;
} else if (midVal.after(value)) {
hi = mid - 1;
}
}
// not found, try nearest older with duration 0
lo = lo - 1;
while (lo >= 0 && lo < rawData.size()) {
if (rawData.valueAt(lo).isEndingEvent())
return lo;
lo--;
}
return -1; // 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

@ -0,0 +1,99 @@
package info.nightscout.androidaps.data;
import android.support.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Created by mike on 01.06.2017.
*/
public class ProfileStore {
private static Logger log = LoggerFactory.getLogger(ProfileStore.class);
private JSONObject json = null;
public ProfileStore(JSONObject json) {
this.json = json;
}
public JSONObject getData() {
return json;
}
@Nullable
public Profile getDefaultProfile() {
Profile profile = null;
try {
String defaultProfileName = json.getString("defaultProfile");
JSONObject store = json.getJSONObject("store");
if (store.has(defaultProfileName)) {
String units = null;
if (store.has("units"))
units = store.getString("units");
profile = new Profile(store.getJSONObject(defaultProfileName), units);
}
} catch (JSONException e) {
e.printStackTrace();
}
return profile;
}
@Nullable
public String getDefaultProfileName() {
String defaultProfileName = null;
try {
defaultProfileName = json.getString("defaultProfile");
JSONObject store = json.getJSONObject("store");
if (store.has(defaultProfileName)) {
return defaultProfileName;
}
} catch (JSONException e) {
e.printStackTrace();
}
return defaultProfileName;
}
@Nullable
public Profile getSpecificProfile(String profileName) {
Profile profile = null;
try {
JSONObject store = json.getJSONObject("store");
if (store.has(profileName)) {
String units = null;
if (json.has("units"))
units = json.getString("units");
profile = new Profile(store.getJSONObject(profileName), units);
}
} catch (JSONException e) {
e.printStackTrace();
}
return profile;
}
public ArrayList<CharSequence> getProfileList() {
ArrayList<CharSequence> ret = new ArrayList<CharSequence>();
JSONObject store;
try {
store = json.getJSONObject("store");
Iterator<?> keys = store.keys();
while (keys.hasNext()) {
String profileName = (String) keys.next();
ret.add(profileName);
}
} catch (JSONException e) {
e.printStackTrace();
}
return ret;
}
}

View file

@ -8,7 +8,6 @@ import org.json.JSONObject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round;
@ -94,7 +93,7 @@ public class PumpEnactResult extends Object {
result.put("duration", 0);
} else if (isPercent) {
// Nightscout is expecting absolute value
Double abs = Round.roundTo(MainApp.getConfigBuilder().getActiveProfile().getProfile().getBasal(NSProfile.secondsFromMidnight()) * percent / 100, 0.01);
Double abs = Round.roundTo(MainApp.getConfigBuilder().getProfile().getBasal() * percent / 100, 0.01);
result.put("rate", abs);
result.put("duration", duration);
} else {

View file

@ -51,6 +51,7 @@ public class CareportalEvent {
public static final String SITECHANGE = "Site Change";
public static final String INSULINCHANGE = "Insulin Change";
public static final String SENSORCHANGE = "Sensor Change";
public static final String PUMPBATTERYCHANGE = "Pump Battery Change";
public CareportalEvent() {
}

View file

@ -31,9 +31,11 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
@ -41,7 +43,6 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@ -56,6 +57,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
private static final int DATABASE_VERSION = 7;
@ -79,6 +81,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final ScheduledExecutorService careportalEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledCareportalEventPost = null;
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(getWritableDatabase(), getConnectionSource());
@ -96,6 +101,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
@ -114,6 +120,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
log.error("Can't drop databases", e);
@ -158,6 +165,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
log.debug("Before CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
getWritableDatabase().delete(DATABASE_CAREPORTALEVENTS, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
log.debug("Before ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
getWritableDatabase().delete(DATABASE_PROFILESWITCHES, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
}
public long size(String database) {
@ -176,6 +187,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
@ -184,6 +196,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
e.printStackTrace();
@ -194,6 +207,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleExtendedBolusChange();
scheduleTemporaryTargetChange();
scheduleCareportalEventChange();
scheduleProfileSwitchChange();
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
@ -258,6 +272,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleCareportalEventChange();
}
public void resetProfileSwitch() {
try {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
e.printStackTrace();
}
scheduleProfileSwitchChange();
}
// ------------------ getDao -------------------------------------------
private Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
@ -292,6 +316,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(CareportalEvent.class);
}
private Dao<ProfileSwitch, Long> getDaoProfileSwitch() throws SQLException {
return getDao(ProfileSwitch.class);
}
// ------------------- BgReading handling -----------------------
public void createIfNotExists(BgReading bgReading) {
@ -304,7 +332,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleBgChange();
}
static public void scheduleBgChange() {
private static void scheduleBgChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventNewBg");
@ -449,7 +477,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// -------------------- TREATMENT HANDLING -------------------
public boolean changeAffectingIobCob(Treatment t) {
private boolean changeAffectingIobCob(Treatment t) {
Treatment existing = findTreatmentByTime(t.date);
if (existing == null)
return true;
@ -540,7 +568,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null;
}
void updateEarliestDataChange(long newDate) {
private void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
earliestDataChange = newDate;
return;
@ -550,7 +578,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
static public void scheduleTreatmentChange() {
private static void scheduleTreatmentChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTreatmentChange");
@ -617,9 +645,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d;
treatment._id = trJson.getString("_id");
if (trJson.has("eventType")) {
treatment.mealBolus = true;
if (trJson.get("eventType").equals("Correction Bolus"))
treatment.mealBolus = false;
treatment.mealBolus = !trJson.get("eventType").equals("Correction Bolus");
double carbs = treatment.carbs;
if (trJson.has("boluscalc")) {
JSONObject boluscalc = trJson.getJSONObject("boluscalc");
@ -631,9 +657,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
treatment.mealBolus = false;
}
createOrUpdate(treatment);
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
@ -676,7 +700,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
static public void scheduleTemporaryTargetChange() {
private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempTargetChange");
@ -717,8 +741,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> list = getDaoTempTargets().query(preparedQuery);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null) return; // no profile data, better ignore than do something wrong
Profile profile = MainApp.getConfigBuilder().getProfile();
String units = profile.getUnits();
TempTarget tempTarget;
if (list.size() == 0) {
@ -736,14 +759,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
tempTarget.date = trJson.getLong("mills");
tempTarget.durationInMinutes = trJson.getInt("duration");
tempTarget.low = NSProfile.toMgdl(trJson.getDouble("targetBottom"), units);
tempTarget.high = NSProfile.toMgdl(trJson.getDouble("targetTop"), units);
tempTarget.low = Profile.toMgdl(trJson.getDouble("targetBottom"), units);
tempTarget.high = Profile.toMgdl(trJson.getDouble("targetTop"), units);
tempTarget.reason = trJson.getString("reason");
tempTarget._id = trJson.getString("_id");
createOrUpdate(tempTarget);
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
@ -817,9 +838,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// already set
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
@ -887,7 +906,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null;
}
static public void scheduleTemporaryBasalChange() {
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempBasalChange");
@ -1018,9 +1037,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
tempBasal._id = trJson.getString("_id");
createOrUpdate(tempBasal);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
@ -1179,14 +1196,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
extendedBolus.insulin = trJson.getDouble("relative");
extendedBolus._id = trJson.getString("_id");
createOrUpdate(extendedBolus);
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
static public void scheduleExtendedBolusChange() {
private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventExtendedBolusChange");
@ -1302,14 +1317,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
careportalEvent.json = trJson.toString();
careportalEvent._id = trJson.getString("_id");
createOrUpdate(careportalEvent);
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
static public void scheduleCareportalEventChange() {
private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing scheduleCareportalEventChange");
@ -1327,4 +1340,135 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
// ---------------- ProfileSwitch handling ---------------
public List<ProfileSwitch> getProfileSwitchData(boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(20L);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<ProfileSwitch>();
}
public void createOrUpdate(ProfileSwitch profileSwitch) {
profileSwitch.date = profileSwitch.date - profileSwitch.date % 1000;
try {
getDaoProfileSwitch().createOrUpdate(profileSwitch);
scheduleProfileSwitchChange();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void delete(ProfileSwitch profileSwitch) {
try {
getDaoProfileSwitch().delete(profileSwitch);
scheduleProfileSwitchChange();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventProfileSwitchChange");
MainApp.bus().post(new EventProfileSwitchChange());
scheduledProfileSwitchEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledProfileSwitchEventPost != null)
scheduledProfileSwitchEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id":"592fa43ed97496a80da913d2",
"created_at":"2017-06-01T05:20:06Z",
"eventType":"Profile Switch",
"profile":"2016 +30%",
"units":"mmol",
"enteredBy":"sony",
"NSCLIENT_ID":1496294454309,
}
*/
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
try {
QueryBuilder<ProfileSwitch, Long> queryBuilder = null;
queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);
ProfileSwitch profileSwitch;
if (list.size() == 0) {
profileSwitch = new ProfileSwitch();
if (Config.logIncommingData)
log.debug("Adding ProfileSwitch record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
profileSwitch = list.get(0);
if (Config.logIncommingData)
log.debug("Updating ProfileSwitch record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
return;
}
profileSwitch.date = trJson.getLong("mills");
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
profileSwitch._id = trJson.getString("_id");
profileSwitch.profileName = trJson.getString("profile");
profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
if (trJson.has("timeshift"))
profileSwitch.timeshift = trJson.getInt("timeshift");
if (trJson.has("percentage"))
profileSwitch.percentage = trJson.getInt("percentage");
if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson");
if (trJson.has("profilePlugin"))
profileSwitch.profilePlugin = trJson.getString("profilePlugin");
createOrUpdate(profileSwitch);
} catch (SQLException | JSONException e) {
e.printStackTrace();
}
}
public void deleteProfileSwitchById(String _id) {
try {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);
if (list.size() == 1) {
ProfileSwitch record = list.get(0);
if (Config.logIncommingData)
log.debug("Removing ProfileSwitch record from database: " + record.log());
delete(record);
} else {
if (Config.logIncommingData)
log.debug("ProfileSwitch not found database: " + _id);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View file

@ -13,12 +13,13 @@ import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round;
@ -132,7 +133,7 @@ public class ExtendedBolus implements Interval {
public IobTotal iobCalc(long time) {
IobTotal result = new IobTotal(time);
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
if (profile == null)

View file

@ -0,0 +1,138 @@
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.interfaces.Interval;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.utils.DateUtil;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(ProfileSwitch.class);
@DatabaseField(id = true)
public long date;
@DatabaseField
public boolean isValid = true;
@DatabaseField
public int source = Source.NONE;
@DatabaseField
public String _id = null; // NS _id
@DatabaseField
public boolean isCPP = false; // CPP NS="CircadianPercentageProfile"
@DatabaseField
public int timeshift = 0; // CPP NS="timeshift"
@DatabaseField
public int percentage = 100; // CPP NS="percentage"
@DatabaseField
public String profileName = null;
@DatabaseField
public String profileJson = null;
@DatabaseField
public String profilePlugin = null; // NSProfilePlugin.class.getName();
@DatabaseField
public int durationInMinutes = 0;
// -------- Interval interface ---------
Long cuttedEnd = null;
public long durationInMsec() {
return durationInMinutes * 60 * 1000L;
}
public long start() {
return date;
}
// planned end time at time of creation
public long originalEnd() {
return date + durationInMinutes * 60 * 1000L;
}
// end time after cut
public long end() {
if (cuttedEnd != null)
return cuttedEnd;
return originalEnd();
}
public void cutEndTo(long end) {
cuttedEnd = end;
}
public boolean match(long time) {
if (start() <= time && end() >= time)
return true;
return false;
}
public boolean before(long time) {
if (end() < time)
return true;
return false;
}
public boolean after(long time) {
if (start() > time)
return true;
return false;
}
@Override
public boolean isInProgress() {
return match(new Date().getTime());
}
@Override
public boolean isEndingEvent() {
return durationInMinutes == 0;
}
// -------- Interval interface end ---------
// ----------------- DataPointInterface --------------------
@Override
public double getX() {
return date;
}
// default when no sgv around available
private double yValue = 0;
@Override
public double getY() {
return yValue;
}
@Override
public String getLabel() {
return profileName;
}
public String log() {
return "ProfileSwitch{" +
"date=" + date +
"date=" + DateUtil.dateAndTimeString(date) +
", isValid=" + isValid +
", duration=" + durationInMinutes +
", profileName=" + profileName +
", percentage=" + percentage +
", timeshift=" + timeshift +
'}';
}
}

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@ -46,12 +46,11 @@ public class TemporaryBasal implements Interval {
@DatabaseField
public double absoluteRate = 0d;
public TemporaryBasal() {}
public TemporaryBasal() {
}
public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = 0d;
if (ConfigBuilderPlugin.getActiveProfile() != null && ConfigBuilderPlugin.getActiveProfile().getProfile() != null)
basal = ConfigBuilderPlugin.getActiveProfile().getProfile().getBasal(NSProfile.secondsFromMidnight(extendedBolus.date));
double basal = MainApp.getConfigBuilder().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source;
@ -134,12 +133,9 @@ public class TemporaryBasal implements Interval {
public IobTotal iobCalc(long time) {
IobTotal result = new IobTotal(time);
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
if (profile == null)
return result;
int realDuration = getDurationToTime(time);
Double netBasalAmount = 0d;
@ -154,7 +150,7 @@ public class TemporaryBasal implements Interval {
// find middle of the interval
Long calcdate = (long) (date + j * tempBolusSpacing * 60 * 1000 + 0.5d * tempBolusSpacing * 60 * 1000);
Double basalRate = profile.getBasal(NSProfile.secondsFromMidnight(calcdate));
Double basalRate = profile.getBasal(calcdate);
if (basalRate == null)
continue;
@ -205,8 +201,7 @@ public class TemporaryBasal implements Interval {
public double tempBasalConvertedToAbsolute(long time) {
if (isAbsolute) return absoluteRate;
else {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
return profile.getBasal(NSProfile.secondsFromMidnight(time)) * percentRate / 100;
return MainApp.getConfigBuilder().getProfile(time).getBasal(time) * percentRate / 100;
}
}

View file

@ -3,8 +3,6 @@ package info.nightscout.androidaps.db;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -16,11 +14,10 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TREATMENTS)
public class Treatment implements DataPointWithLabelInterface {
@ -107,12 +104,11 @@ public class Treatment implements DataPointWithLabelInterface {
}
public void setYValue(List<BgReading> bgReadingsArray) {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null) return;
Profile profile = MainApp.getConfigBuilder().getProfile();
for (int r = bgReadingsArray.size() - 1; r >= 0; r--) {
BgReading reading = bgReadingsArray.get(r);
if (reading.date > date) continue;
yValue = NSProfile.fromMgdlToUnits(reading.value, profile.getUnits());
yValue = Profile.fromMgdlToUnits(reading.value, profile.getUnits());
break;
}
}

View file

@ -1,16 +1,7 @@
package info.nightscout.androidaps.events;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
/**
* Created by mike on 04.06.2016.
*/
public class EventNewBasalProfile {
public NSProfile newNSProfile = null;
public String from = "";
public EventNewBasalProfile(NSProfile newProfile, String from) {
newNSProfile = newProfile;
this.from = from;
}
}

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.events;
/**
* Created by mike on 02.06.2017.
*/
public class EventProfileSwitchChange {
}

View file

@ -2,12 +2,13 @@ package info.nightscout.androidaps.interfaces;
import android.support.annotation.Nullable;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.ProfileStore;
/**
* Created by mike on 14.06.2016.
*/
public interface ProfileInterface {
@Nullable
NSProfile getProfile();
ProfileStore getProfile();
String getProfileName();
}

View file

@ -1,14 +1,12 @@
package info.nightscout.androidaps.interfaces;
import android.content.Context;
import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
/**
* Created by mike on 04.06.2016.
@ -23,8 +21,8 @@ public interface PumpInterface {
int SUCCESS = 0;
int FAILED = 1;
int NOT_NEEDED = 2;
int setNewBasalProfile(NSProfile profile);
boolean isThisProfileSet(NSProfile profile);
int setNewBasalProfile(Profile profile);
boolean isThisProfileSet(Profile profile);
Date lastDataTime();
void refreshDataFromPump(String reason);

View file

@ -6,10 +6,12 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.utils.OverlappingIntervals;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.ProfileIntervals;
/**
* Created by mike on 14.06.2016.
@ -49,11 +51,15 @@ public interface TreatmentsInterface {
void addToHistoryExtendedBolusStop(long time);
OverlappingIntervals<ExtendedBolus> getExtendedBolusesFromHistory();
void addTreatmentToHistory(DetailedBolusInfo detailedBolusInfo);
void addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo);
TempTarget getTempTargetFromHistory(long time);
OverlappingIntervals<TempTarget> getTempTargetsFromHistory();
long oldestDataAvaialable();
ProfileSwitch getProfileSwitchFromHistory(long time);
ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory();
void addToHistoryProfileSwitch(ProfileSwitch profileSwitch);
long oldestDataAvailable();
}

View file

@ -129,7 +129,10 @@ public class ActionsFragment extends Fragment implements View.OnClickListener {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (!MainApp.getConfigBuilder().getPumpDescription().isSetBasalProfileCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended())
if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() == null)
return;
boolean allowProfileSwitch = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getProfileList().size() > 1;
if (!MainApp.getConfigBuilder().getPumpDescription().isSetBasalProfileCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || !allowProfileSwitch)
profileSwitch.setVisibility(View.GONE);
else
profileSwitch.setVisibility(View.VISIBLE);

View file

@ -21,13 +21,12 @@ import com.crashlytics.android.answers.CustomEvent;
import java.text.DecimalFormat;
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.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SafeParse;
@ -73,9 +72,8 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
basalPercent = new PlusMinusEditText(view, R.id.overview_newtempbasal_basalpercentinput, R.id.overview_newtempbasal_basalpercent_plus, R.id.overview_newtempbasal_basalpercent_minus,
100d, 0d, (double) pumpDescription.maxTempPercent, (double) pumpDescription.tempPercentStep, new DecimalFormat("0"), true);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Double currentBasal = 0d;
if (profile != null) currentBasal = profile.getBasal(NSProfile.secondsFromMidnight());
Profile profile = MainApp.getConfigBuilder().getProfile();
Double currentBasal = profile.getBasal();
basalAbsolute = new PlusMinusEditText(view, R.id.overview_newtempbasal_basalabsoluteinput, R.id.overview_newtempbasal_basalabsolute_plus, R.id.overview_newtempbasal_basalabsolute_minus,
currentBasal, 0d, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, new DecimalFormat("0.00"), true);

View file

@ -25,6 +25,7 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
TextView iage;
TextView cage;
TextView sage;
TextView pbage;
static public CareportalPlugin getPlugin() {
if (careportalPlugin == null) {
@ -34,25 +35,25 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
}
// bg,insulin,carbs,prebolus,duration,percent,absolute,profile,split,temptarget
final OptionsToShow bgcheck = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck, true, true, true, false, false, false, false, false, false, false);
final OptionsToShow snackbolus = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus, true, true, true, true, false, false, false, false, false, false);
final OptionsToShow mealbolus = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus, true, true, true, true, false, false, false, false, false, false);
final OptionsToShow correctionbolus = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus, true, true, true, true, false, false, false, false, false, false);
final OptionsToShow carbcorrection = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection, true, false, true, false, false, false, false, false, false, false);
final OptionsToShow combobolus = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus, true, true, true, true, true, false, false, false, true, false);
final OptionsToShow announcement = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement, true, false, false, false, false, false, false, false, false, false);
final OptionsToShow note = new OptionsToShow(R.id.careportal_note, R.string.careportal_note, true, false, false, false, true, false, false, false, false, false);
final OptionsToShow question = new OptionsToShow(R.id.careportal_question, R.string.careportal_question, true, false, false, false, false, false, false, false, false, false);
final OptionsToShow exercise = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise, false, false, false, false, true, false, false, false, false, false);
final OptionsToShow sitechange = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange, true, true, false, false, false, false, false, false, false, false);
final OptionsToShow sensorstart = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart, true, false, false, false, false, false, false, false, false, false);
final OptionsToShow sensorchange = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert, true, false, false, false, false, false, false, false, false, false);
final OptionsToShow insulinchange = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange, true, false, false, false, false, false, false, false, false, false);
final OptionsToShow tempbasalstart = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart, true, false, false, false, true, true, true, false, false, false);
final OptionsToShow tempbasalend = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend, true, false, false, false, false, false, false, false, false, false);
final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, false, false, false, true, false, false);
final OptionsToShow openapsoffline = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline, false, false, false, false, true, false, false, false, false, false);
final OptionsToShow temptarget = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget, false, false, false, false, true, false, false, false, false, true);
static final OptionsToShow bgcheck = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck, true, true, true, false, false, false, false, false, false, false);
static final OptionsToShow snackbolus = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus, true, true, true, true, false, false, false, false, false, false);
static final OptionsToShow mealbolus = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus, true, true, true, true, false, false, false, false, false, false);
static final OptionsToShow correctionbolus = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus, true, true, true, true, false, false, false, false, false, false);
static final OptionsToShow carbcorrection = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection, true, false, true, false, false, false, false, false, false, false);
static final OptionsToShow combobolus = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus, true, true, true, true, true, false, false, false, true, false);
static final OptionsToShow announcement = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement, true, false, false, false, false, false, false, false, false, false);
static final OptionsToShow note = new OptionsToShow(R.id.careportal_note, R.string.careportal_note, true, false, false, false, true, false, false, false, false, false);
static final OptionsToShow question = new OptionsToShow(R.id.careportal_question, R.string.careportal_question, true, false, false, false, false, false, false, false, false, false);
static final OptionsToShow exercise = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise, false, false, false, false, true, false, false, false, false, false);
static final OptionsToShow sitechange = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange, true, true, false, false, false, false, false, false, false, false);
static final OptionsToShow sensorstart = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart, true, false, false, false, false, false, false, false, false, false);
static final OptionsToShow sensorchange = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert, true, false, false, false, false, false, false, false, false, false);
static final OptionsToShow insulinchange = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange, true, false, false, false, false, false, false, false, false, false);
static final OptionsToShow tempbasalstart = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart, true, false, false, false, true, true, true, false, false, false);
static final OptionsToShow tempbasalend = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend, true, false, false, false, false, false, false, false, false, false);
static final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, true, false, false, true, false, false);
static final OptionsToShow openapsoffline = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline, false, false, false, false, true, false, false, false, false, false);
static final OptionsToShow temptarget = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget, false, false, false, false, true, false, false, false, false, true);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
@ -82,6 +83,7 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
iage = (TextView) view.findViewById(R.id.careportal_insulinage);
cage = (TextView) view.findViewById(R.id.careportal_canulaage);
sage = (TextView) view.findViewById(R.id.careportal_sensorage);
pbage = (TextView) view.findViewById(R.id.careportal_pbage);
updateGUI();
return view;
@ -89,9 +91,12 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
@Override
public void onClick(View view) {
FragmentManager manager = getFragmentManager();
action(view.getId(), getFragmentManager());
}
public static void action(int id, FragmentManager manager) {
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
switch (view.getId()) {
switch (id) {
case R.id.careportal_bgcheck:
newDialog.setOptions(bgcheck);
break;
@ -175,19 +180,33 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
void updateGUI() {
Activity activity = getActivity();
updateAge(activity, sage, iage, cage, pbage);
}
public static void updateAge(Activity activity, final TextView sage, final TextView iage, final TextView cage, final TextView pbage) {
if (activity != null) {
activity.runOnUiThread(
new Runnable() {
@Override
public void run() {
CareportalEvent careportalEvent;
if (sage != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
sage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
}
if (iage != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
iage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
}
if (cage != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SITECHANGE);
cage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
}
if (pbage != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.PUMPBATTERYCHANGE);
pbage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
}
}
}
);
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.Careportal;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
@ -57,7 +58,7 @@ public class CareportalPlugin implements PluginBase {
@Override
public boolean showInList(int type) {
return true;
return !Config.NSCLIENT;
}
@Override

View file

@ -45,19 +45,21 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
import info.nightscout.utils.Translator;
public class NewNSTreatmentDialog extends DialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
@ -67,7 +69,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
private static OptionsToShow options;
NSProfile profile;
Profile profile;
ProfileStore profileStore;
String units;
RelativeLayout layoutBg;
@ -225,26 +228,20 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
cancelButton.setOnClickListener(this);
// profile
profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
profile = MainApp.getConfigBuilder().getProfile();
profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
ArrayList<CharSequence> profileList;
units = Constants.MGDL;
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), context.getString(R.string.noprofile));
profileList = new ArrayList<CharSequence>();
} else {
units = profile.getUnits();
profileList = profile.getProfileList();
}
profileList = profileStore.getProfileList();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
R.layout.spinner_centered, profileList);
profileSpinner.setAdapter(adapter);
if (profile != null) {
// set selected to actual profile
for (int p = 0; p < profileList.size(); p++) {
if (profileList.get(p).equals(profile.getActiveProfile()))
if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName()))
profileSpinner.setSelection(p);
}
}
// temp target
ArrayList<CharSequence> reasonList = new ArrayList<CharSequence>();
@ -268,7 +265,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
// meterRadioButton.setChecked(true);
// }
Double bg = NSProfile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL);
Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL);
if (profile == null)
editBg = new PlusMinusEditText(view, R.id.careportal_newnstreatment_bginput, R.id.careportal_newnstreatment_bg_plus, R.id.careportal_newnstreatment_bg_minus, bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
else if (profile.getUnits().equals(Constants.MMOL))
@ -277,9 +274,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editBg = new PlusMinusEditText(view, R.id.careportal_newnstreatment_bginput, R.id.careportal_newnstreatment_bg_plus, R.id.careportal_newnstreatment_bg_minus, bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
bgInputEdit.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true);
@ -288,9 +287,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
if (profile == null) return;
Double bg = NSProfile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
editBg.setValue(bg);
}
});
@ -439,6 +436,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
break;
case R.id.careportal_profileswitch:
data.put("eventType", CareportalEvent.PROFILESWITCH);
allowZeroDuration = true;
break;
case R.id.careportal_pumpsitechange:
data.put("eventType", CareportalEvent.SITECHANGE);
@ -615,24 +613,30 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
@Override
public void run() {
try {
String profile = data.getString("profile");
NSProfile nsProfile = ConfigBuilderPlugin.getActiveProfile().getProfile();
nsProfile.setActiveProfile(profile);
String profileName = data.getString("profile");
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = new Date().getTime();
profileSwitch.source = Source.PUMP;
profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).toString();
profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = data.getInt("duration");
if (ConfigBuilderPlugin.getActiveProfileInterface() instanceof CircadianPercentageProfilePlugin) {
CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) MainApp.getConfigBuilder().getActiveProfileInterface();
profileSwitch.isCPP = true;
profileSwitch.timeshift = cpp.timeshift;
profileSwitch.percentage = cpp.percentage;
}
MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
PumpInterface pump = MainApp.getConfigBuilder();
if (pump != null) {
pump.setNewBasalProfile(nsProfile);
pump.setNewBasalProfile(profileStore.getSpecificProfile(profileName));
log.debug("Setting new profile: " + profile);
MainApp.bus().post(new EventNewBasalProfile(nsProfile, "NewNSTreatmentDialog"));
MainApp.bus().post(new EventNewBasalProfile());
} else {
log.error("No active pump selected");
}
if (ConfigBuilderPlugin.getActiveProfile() instanceof CircadianPercentageProfilePlugin) {
CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) ConfigBuilderPlugin.getActiveProfile();
data.put("CircadianPercentageProfile", true);
data.put("timeshift", cpp.timeshift);
data.put("percentage", cpp.percentage);
}
NSUpload.uploadCareportalEntryToNS(data);
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} catch (JSONException e) {
e.printStackTrace();
@ -652,8 +656,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
tempTarget.durationInMinutes = data.getInt("duration");
tempTarget.reason = data.getString("reason");
if (tempTarget.durationInMinutes != 0) {
tempTarget.low = NSProfile.toMgdl(data.getDouble("targetBottom"), ConfigBuilderPlugin.getActiveProfile().getProfile().getUnits());
tempTarget.high = NSProfile.toMgdl(data.getDouble("targetTop"), ConfigBuilderPlugin.getActiveProfile().getProfile().getUnits());
tempTarget.low = Profile.toMgdl(data.getDouble("targetBottom"), profile.getUnits());
tempTarget.high = Profile.toMgdl(data.getDouble("targetTop"), profile.getUnits());
} else {
tempTarget.low = 0;
tempTarget.high = 0;

View file

@ -50,12 +50,15 @@ public class ConfigBuilderFragment extends Fragment {
ListView insulinListView;
ListView bgsourceListView;
TextView bgsourceLabel;
ListView pumpListView;
TextView pumpLabel;
ListView loopListView;
TextView loopLabel;
ListView treatmentsListView;
TextView treatmentsLabel;
ListView profileListView;
TextView profileLabel;
ListView apsListView;
TextView apsLabel;
ListView constraintsListView;
@ -94,12 +97,15 @@ public class ConfigBuilderFragment extends Fragment {
insulinListView = (ListView) view.findViewById(R.id.configbuilder_insulinlistview);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
bgsourceLabel = (TextView) view.findViewById(R.id.configbuilder_bgsourcelabel);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
pumpLabel = (TextView) view.findViewById(R.id.configbuilder_pumplabel);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
treatmentsLabel = (TextView) view.findViewById(R.id.configbuilder_treatmentslabel);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
profileLabel = (TextView) view.findViewById(R.id.configbuilder_profilelabel);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
@ -144,6 +150,8 @@ public class ConfigBuilderFragment extends Fragment {
setListViewHeightBasedOnChildren(insulinListView);
bgsourceDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginBase.BGSOURCE), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.BGSOURCE).size() == 0)
bgsourceLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(bgsourceListView);
pumpDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
@ -157,9 +165,13 @@ public class ConfigBuilderFragment extends Fragment {
loopLabel.setVisibility(View.GONE);
treatmentsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT).size() == 0)
treatmentsLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(treatmentsListView);
profileDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.BGSOURCE), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PROFILE).size() == 0)
profileLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(profileListView);
apsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter);

View file

@ -1,13 +1,13 @@
package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -22,13 +22,16 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventBolusRequested;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
@ -40,15 +43,12 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperActivity;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OverlappingIntervals;
/**
* Created by mike on 05.08.2016.
@ -191,8 +191,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return activeBgSource;
}
@Nullable
public static ProfileInterface getActiveProfile() {
public static ProfileInterface getActiveProfileInterface() {
return activeProfile;
}
@ -353,9 +352,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public int setNewBasalProfile(NSProfile profile) {
public int setNewBasalProfile(Profile profile) {
// Compare with pump limits
NSProfile.BasalValue[] basalValues = profile.getBasalValues();
Profile.BasalValue[] basalValues = profile.getBasalValues();
for (int index = 0; index < basalValues.length; index++) {
if (basalValues[index].value < getPumpDescription().basalMinimumRate) {
@ -377,7 +376,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public boolean isThisProfileSet(NSProfile profile) {
public boolean isThisProfileSet(Profile profile) {
if (activePump != null)
return activePump.isThisProfileSet(profile);
else return true;
@ -432,7 +431,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
t.carbs = (double) result.carbsDelivered; // with different carbTime record will come back from nightscout
t.date = new Date().getTime();
t.mealBolus = result.carbsDelivered > 0;
addTreatmentToHistory(t);
addToHistoryTreatment(t);
t.carbs = (double) result.carbsDelivered;
NSUpload.uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
}
@ -506,7 +505,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
t.carbs = (double) result.carbsDelivered;
t.date = new Date().getTime();
t.mealBolus = t.carbs > 0;
addTreatmentToHistory(t);
addToHistoryTreatment(t);
NSUpload.uploadTreatment(t);
}
mWakeLock.release();
@ -680,6 +679,8 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
@Override
public boolean isFakingTempsByExtendedBoluses() {
if (Config.NSCLIENT)
return false;
return activePump.isFakingTempsByExtendedBoluses();
}
@ -851,6 +852,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
@Nullable
public TemporaryBasal getRealTempBasalFromHistory(long time) {
return activeTreatments.getRealTempBasalFromHistory(time);
}
@ -861,6 +863,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
@Nullable
public TemporaryBasal getTempBasalFromHistory(long time) {
return activeTreatments.getTempBasalFromHistory(time);
}
@ -902,6 +905,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
@Nullable
public ExtendedBolus getExtendedBolusFromHistory(long time) {
return activeTreatments.getExtendedBolusFromHistory(time);
}
@ -930,14 +934,15 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public void addTreatmentToHistory(DetailedBolusInfo detailedBolusInfo) {
public void addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo) {
if (!detailedBolusInfo.addToTreatments)
return;
activeTreatments.addTreatmentToHistory(detailedBolusInfo);
activeTreatments.addToHistoryTreatment(detailedBolusInfo);
NSUpload.uploadBolusWizardRecord(detailedBolusInfo);
}
@Override
@Nullable
public TempTarget getTempTargetFromHistory(long time) {
return activeTreatments.getTempTargetFromHistory(time);
}
@ -948,7 +953,88 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
public long oldestDataAvaialable() {
return activeTreatments.oldestDataAvaialable();
@Nullable
public ProfileSwitch getProfileSwitchFromHistory(long time) {
return activeTreatments.getProfileSwitchFromHistory(time);
}
@Override
public ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory() {
return activeTreatments.getProfileSwitchesFromHistory();
}
@Override
public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) {
activeTreatments.addToHistoryProfileSwitch(profileSwitch);
NSUpload.uploadProfileSwitch(profileSwitch);
}
@Override
public long oldestDataAvailable() {
return activeTreatments.oldestDataAvailable();
}
public String getProfileName() {
return getProfileName(new Date().getTime());
}
public String getProfileName(long time) {
ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return profileSwitch.profileName;
} else {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profileSwitch.profileName;
}
}
// Unable to determine profile, failover to default
String defaultProfile = activeProfile.getProfile().getDefaultProfileName();
if (defaultProfile != null)
return defaultProfile;
// If default from plugin fails .... create empty
return "Default";
}
public Profile getProfile() {
return getProfile(new Date().getTime());
}
public Profile getProfile(long time) {
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
try {
return new Profile(new JSONObject(profileSwitch.profileJson));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profile;
}
}
// Unable to determine profile, failover to default
if (activeProfile.getProfile() == null)
return null; //app not initialized
Profile defaultProfile = activeProfile.getProfile().getDefaultProfile();
if (defaultProfile != null)
return defaultProfile;
// If default from plugin fails .... create empty
try {
Notification noisf = new Notification(Notification.ISF_MISSING, MainApp.sResources.getString(R.string.isfmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noisf));
Notification noic = new Notification(Notification.IC_MISSING, MainApp.sResources.getString(R.string.icmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noic));
Notification nobasal = new Notification(Notification.BASAL_MISSING, MainApp.sResources.getString(R.string.basalmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(nobasal));
Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notarget));
return new Profile(new JSONObject("{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"6\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"8\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}}"));
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.HardLimits;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
@ -105,7 +105,7 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
Double origAbsoluteRate = absoluteRate;
Double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return absoluteRate;
if (absoluteRate < 0) absoluteRate = 0d;
@ -118,8 +118,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasal preference to " + absoluteRate + "U/h");
}
if (absoluteRate > maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight())) {
absoluteRate = Math.floor(maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight()) * 100) / 100;
if (absoluteRate > maxBasalMult * profile.getBasal()) {
absoluteRate = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100;
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasalMult to " + absoluteRate + "U/h");
}
@ -136,9 +136,9 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
Integer origPercentRate = percentRate;
Double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return percentRate;
Double currentBasal = profile.getBasal(profile.secondsFromMidnight());
Double currentBasal = profile.getBasal();
Double absoluteRate = currentBasal * ((double) percentRate / 100);
@ -156,8 +156,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
if (Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasal preference to " + absoluteRate + "U/h");
}
if (absoluteRate > maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight())) {
absoluteRate = Math.floor(maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight()) * 100) / 100;
if (absoluteRate > maxBasalMult * profile.getBasal()) {
absoluteRate = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100;
if (Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasalMult to " + absoluteRate + "U/h");
}

View file

@ -1,15 +1,11 @@
package info.nightscout.androidaps.plugins.InsulinFastacting;
import java.util.Date;
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.db.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
/**
* Created by mike on 17.04.2017.
@ -93,10 +89,7 @@ public class InsulinFastactingPlugin implements PluginBase, InsulinInterface {
@Override
public double getDia() {
ProfileInterface profileInterface = MainApp.getConfigBuilder().getActiveProfile();
if (profileInterface.getProfile() != null)
return profileInterface.getProfile().getDia();
return Constants.defaultDIA;
return MainApp.getConfigBuilder().getProfile().getDia();
}
@Override

View file

@ -1,15 +1,11 @@
package info.nightscout.androidaps.plugins.InsulinFastactingProlonged;
import java.util.Date;
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.db.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
/**
* Created by mike on 17.04.2017.
@ -93,10 +89,7 @@ public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInte
@Override
public double getDia() {
ProfileInterface profileInterface = MainApp.getConfigBuilder().getActiveProfile();
if (profileInterface.getProfile() != null)
return profileInterface.getProfile().getDia();
return Constants.defaultDIA;
return MainApp.getConfigBuilder().getProfile().getDia();
}
@Override

View file

@ -21,4 +21,8 @@ public class AutosensData {
return "AutosensData: " + new Date(time).toLocaleString() + " " + pastSensitivity + " Delta=" + delta + " Bgi=" + bgi + " Deviation=" + deviation + " Absorbed=" + absorbed + " CarbsFromBolus=" + carbsFromBolus + " COB=" + cob;
}
public int minOld() {
return (int) ((new Date().getTime() - time) / 1000 / 60);
}
}

View file

@ -16,18 +16,18 @@ import java.util.Arrays;
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.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
@ -154,7 +154,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
private void loadBgData() {
//log.debug("Locking loadBgData");
synchronized (dataLock) {
onNewProfile(new EventNewBasalProfile(null, "IobCobCalculator init"));
onNewProfile(null);
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia)), false);
log.debug("BG data loaded. Size: " + bgReadings.size());
}
@ -228,14 +228,10 @@ public class IobCobCalculatorPlugin implements PluginBase {
}
public void calculateSensitivityData() {
if (MainApp.getConfigBuilder() == null)
return; // app still initializing
//log.debug("Locking calculateSensitivityData");
synchronized (dataLock) {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile() != null ? ConfigBuilderPlugin.getActiveProfile().getProfile() : null;
if (profile == null || profile.getIsf(NSProfile.secondsFromMidnight()) == null || profile.getIc(NSProfile.secondsFromMidnight()) == null) {
log.debug("calculateSensitivityData: No profile available");
return;
}
if (bucketed_data == null || bucketed_data.size() < 3) {
log.debug("calculateSensitivityData: No bucketed data available");
@ -250,6 +246,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
// check if data already exists
long bgTime = bucketed_data.get(i).date;
bgTime = roundUpTime(bgTime);
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
AutosensData existing;
if ((existing = autosensDataTable.get(bgTime)) != null) {
@ -257,8 +254,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
continue;
}
int secondsFromMidnight = NSProfile.secondsFromMidnight(bgTime);
double sens = NSProfile.toMgdl(profile.getIsf(secondsFromMidnight), profile.getUnits());
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
AutosensData autosensData = new AutosensData();
autosensData.time = bgTime;
@ -289,7 +285,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
// figure out how many carbs that represents
// but always assume at least 3mg/dL/5m (default) absorption
double ci = Math.max(deviation, SP.getDouble("openapsama_min_5m_carbimpact", 3.0));
autosensData.absorbed = ci * profile.getIc(secondsFromMidnight) / sens;
autosensData.absorbed = ci * profile.getIc(bgTime) / sens;
// and add that to the running total carbsAbsorbed
autosensData.cob = Math.max(previous.cob - autosensData.absorbed, 0d);
}
@ -315,6 +311,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
previous = autosensData;
autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData)
log.debug(autosensData.log(bgTime));
}
}
@ -385,7 +382,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
}
public static IobTotal[] calculateIobArrayInDia() {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
// predict IOB out to DIA plus 30m
long time = new Date().getTime();
int len = (int) ((profile.getDia() * 60 + 30) / 5);
@ -430,7 +427,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
deviationsArray.add(autosensData.deviation);
pastSensitivity += autosensData.pastSensitivity;
int secondsFromMidnight = NSProfile.secondsFromMidnight(autosensData.time);
int secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time);
if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) {
pastSensitivity += "(" + Math.round(secondsFromMidnight / 3600d) + ")";
}
@ -440,19 +437,9 @@ public class IobCobCalculatorPlugin implements PluginBase {
Double[] deviations = new Double[deviationsArray.size()];
deviations = deviationsArray.toArray(deviations);
if (ConfigBuilderPlugin.getActiveProfile() == null || ConfigBuilderPlugin.getActiveProfile().getProfile() == null) {
log.debug("No profile available");
return new AutosensResult();
}
Profile profile = MainApp.getConfigBuilder().getProfile();
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Double sens = profile.getIsf(NSProfile.secondsFromMidnight());
if (sens == null || profile.getMaxDailyBasal() == 0) {
log.debug("No profile available");
return new AutosensResult();
}
double sens = profile.getIsf();
double ratio = 1;
String ratioLimit = "";
@ -472,10 +459,10 @@ public class IobCobCalculatorPlugin implements PluginBase {
double basalOff = 0;
if (pSensitive < 0) { // sensitive
basalOff = pSensitive * (60 / 5) / NSProfile.toMgdl(sens, profile.getUnits());
basalOff = pSensitive * (60 / 5) / Profile.toMgdl(sens, profile.getUnits());
sensResult = "Excess insulin sensitivity detected";
} else if (pResistant > 0) { // resistant
basalOff = pResistant * (60 / 5) / NSProfile.toMgdl(sens, profile.getUnits());
basalOff = pResistant * (60 / 5) / Profile.toMgdl(sens, profile.getUnits());
sensResult = "Excess insulin resistance detected";
} else {
sensResult = "Sensitivity normal";
@ -492,9 +479,9 @@ public class IobCobCalculatorPlugin implements PluginBase {
log.debug(ratioLimit);
}
double newisf = Math.round(NSProfile.toMgdl(sens, profile.getUnits()) / ratio);
double newisf = Math.round(Profile.toMgdl(sens, profile.getUnits()) / ratio);
if (ratio != 1) {
log.debug("ISF adjusted from " + NSProfile.toMgdl(sens, profile.getUnits()) + " to " + newisf);
log.debug("ISF adjusted from " + Profile.toMgdl(sens, profile.getUnits()) + " to " + newisf);
}
AutosensResult output = new AutosensResult();
@ -531,17 +518,15 @@ public class IobCobCalculatorPlugin implements PluginBase {
@Subscribe
public void onNewProfile(EventNewBasalProfile ev) {
if (MainApp.getConfigBuilder().getActiveProfile() == null)
return;
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile != null) {
if (MainApp.getConfigBuilder() == null)
return; // app still initializing
Profile profile = MainApp.getConfigBuilder().getProfile();
dia = profile.getDia();
}
if (ev.newNSProfile == null) { // on init no need of reset
if (ev == null) { // on init no need of reset
return;
}
synchronized (dataLock) {
log.debug("Invalidating cached data because of new profile from " + ev.from + ". IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
@ -562,6 +547,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
log.debug("Invalidating cached data to: " + new Date(time).toLocaleString());
for (int index = iobTable.size() - 1; index >= 0; index--) {
if (iobTable.keyAt(index) > time) {
if (Config.logAutosensData)
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
iobTable.removeAt(index);
} else {
@ -570,6 +556,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
}
for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
if (autosensDataTable.keyAt(index) > time) {
if (Config.logAutosensData)
log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString());
autosensDataTable.removeAt(index);
} else {

View file

@ -12,6 +12,7 @@ import android.support.v7.app.NotificationCompat;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -32,8 +33,10 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
/**
* Created by mike on 05.08.2016.

View file

@ -20,6 +20,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -115,7 +116,7 @@ public class NSClientInternalPlugin implements PluginBase {
@Override
public boolean showInList(int type) {
return true;
return !Config.NSCLIENT;
}
@Override

View file

@ -11,7 +11,7 @@ import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.ProfileStore;
/**
@ -20,10 +20,9 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
public class BroadcastProfile {
private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class);
public void handleNewTreatment(NSProfile profile, Context context, boolean isDelta) {
public void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("profile", profile.getData().toString());
bundle.putString("activeprofile", profile.getActiveProfile());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_PROFILE);
intent.putExtras(bundle);

View file

@ -1,494 +0,0 @@
package info.nightscout.androidaps.plugins.NSClientInternal.data;
import android.support.annotation.Nullable;
import com.crashlytics.android.Crashlytics;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;
import info.nightscout.androidaps.Constants;
import info.nightscout.utils.DecimalFormatter;
public class NSProfile {
private static Logger log = LoggerFactory.getLogger(NSProfile.class);
private JSONObject json = null;
private String activeProfile = null;
public NSProfile(JSONObject json, String activeProfile) {
this.json = json;
this.activeProfile = null;
JSONObject store;
try {
store = json.getJSONObject("store");
if (activeProfile != null && store.has(activeProfile)) {
this.activeProfile = activeProfile;
} else {
log.error("Active profile not found in store");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public JSONObject getDefaultProfile() {
String defaultProfileName = null;
JSONObject store;
JSONObject profile = null;
try {
defaultProfileName = (String) json.get("defaultProfile");
store = json.getJSONObject("store");
if (activeProfile != null && store.has(activeProfile)) {
defaultProfileName = activeProfile;
}
profile = store.getJSONObject(defaultProfileName);
} catch (JSONException e) {
e.printStackTrace();
}
return profile;
}
public JSONObject getSpecificProfile(String profileName) {
JSONObject profile = null;
try {
JSONObject store = json.getJSONObject("store");
if (store.has(profileName)) {
profile = store.getJSONObject(profileName);
}
} catch (JSONException e) {
e.printStackTrace();
}
return profile;
}
public ArrayList<CharSequence> getProfileList() {
ArrayList<CharSequence> ret = new ArrayList<CharSequence>();
JSONObject store;
JSONObject profile = null;
try {
store = json.getJSONObject("store");
Iterator<?> keys = store.keys();
while (keys.hasNext()) {
String profileName = (String) keys.next();
ret.add(profileName);
}
} catch (JSONException e) {
e.printStackTrace();
}
return ret;
}
public String log() {
String ret = "\n";
for (Integer hour = 0; hour < 24; hour++) {
double value = getBasal(hour * 60 * 60);
ret += "NS basal value for " + hour + ":00 is " + value + "\n";
}
ret += "NS units: " + getUnits();
return ret;
}
public JSONObject getData() {
return json;
}
public Double getDia() {
return getDia(getDefaultProfile());
}
public Double getDia(JSONObject profile) {
Double dia;
if (profile != null) {
try {
dia = profile.getDouble("dia");
return dia;
} catch (JSONException e) {
e.printStackTrace();
}
}
return Constants.defaultDIA;
}
/*
public Double getCarbAbsorbtionRate() {
return getCarbAbsorbtionRate(getDefaultProfile());
}
public Double getCarbAbsorbtionRate(JSONObject profile) {
Double carbAbsorptionRate;
if (profile != null) {
try {
carbAbsorptionRate = profile.getDouble("carbs_hr");
return carbAbsorptionRate;
} catch (JSONException e) {
e.printStackTrace();
}
}
return 0D;
}
*/
// mmol or mg/dl
public String getUnits() {
return getUnits(getDefaultProfile());
}
public String getUnits(JSONObject profile) {
String units;
if (profile != null) {
try {
units = profile.getString("units");
return units.toLowerCase();
} catch (JSONException e) {
log.error("Profile not found. Failing over to main JSON");
try {
return json.getString("units").toLowerCase();
} catch (JSONException e1) {
e1.printStackTrace();
Crashlytics.log("Profile failover failed too");
}
}
}
return Constants.MGDL;
}
public TimeZone getTimeZone() {
return getTimeZone(getDefaultProfile());
}
public TimeZone getTimeZone(JSONObject profile) {
TimeZone timeZone;
if (profile != null) {
try {
return TimeZone.getTimeZone(profile.getString("timezone"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return TimeZone.getDefault();
}
@Nullable
public Double getValueToTime(JSONArray array, Integer timeAsSeconds) {
Double lastValue = null;
for (Integer index = 0; index < array.length(); index++) {
try {
JSONObject o = array.getJSONObject(index);
Integer tas = o.getInt("timeAsSeconds");
Double value = o.getDouble("value");
if (lastValue == null) lastValue = value;
if (timeAsSeconds < tas) {
break;
}
lastValue = value;
} catch (JSONException e) {
e.printStackTrace();
}
}
return lastValue;
}
public String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) {
String retValue = "";
for (Integer index = 0; index < array.length(); index++) {
try {
JSONObject o = array.getJSONObject(index);
retValue += o.getString("time");
retValue += " ";
retValue += format.format(o.getDouble("value"));
if (array2 != null) {
JSONObject o2 = array2.getJSONObject(index);
retValue += " - ";
retValue += format.format(o2.getDouble("value"));
}
retValue += " " + units;
retValue += "\n";
} catch (JSONException e) {
e.printStackTrace();
}
}
return retValue;
}
@Nullable
public Double getIsf(Integer timeAsSeconds) {
return getIsf(getDefaultProfile(), timeAsSeconds);
}
@Nullable
public Double getIsf(JSONObject profile, Integer timeAsSeconds) {
if (profile != null) {
try {
return getValueToTime(profile.getJSONArray("sens"), timeAsSeconds);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
public String getIsfList() {
return getIsfList(getDefaultProfile());
}
public String getIsfList(JSONObject profile) {
if (profile != null) {
try {
return getValuesList(profile.getJSONArray("sens"), null, new DecimalFormat("0.0"), getUnits() + "/U");
} catch (JSONException e) {
e.printStackTrace();
}
}
return "";
}
@Nullable
public Double getIc(Integer timeAsSeconds) {
return getIc(getDefaultProfile(), timeAsSeconds);
}
@Nullable
public Double getIc(JSONObject profile, Integer timeAsSeconds) {
if (profile != null) {
try {
return getValueToTime(profile.getJSONArray("carbratio"), timeAsSeconds);
} catch (JSONException e) {
e.printStackTrace();
}
}
return 0D;
}
public String getIcList() {
return getIcList(getDefaultProfile());
}
public String getIcList(JSONObject profile) {
if (profile != null) {
try {
return getValuesList(profile.getJSONArray("carbratio"), null, new DecimalFormat("0.0"), "g");
} catch (JSONException e) {
e.printStackTrace();
}
}
return "";
}
@Nullable
public Double getBasal(Integer timeAsSeconds) {
return getBasal(getDefaultProfile(), timeAsSeconds);
}
@Nullable
public Double getBasal(JSONObject profile, Integer timeAsSeconds) {
if (profile != null) {
try {
return getValueToTime(profile.getJSONArray("basal"), timeAsSeconds);
} catch (JSONException e) {
e.printStackTrace();
}
}
return 0D;
}
public String getBasalList() {
return getBasalList(getDefaultProfile());
}
public class BasalValue {
public BasalValue(Integer timeAsSeconds, Double value) {
this.timeAsSeconds = timeAsSeconds;
this.value = value;
}
public Integer timeAsSeconds;
public Double value;
}
public BasalValue[] getBasalValues() {
try {
JSONArray array = getDefaultProfile().getJSONArray("basal");
BasalValue[] ret = new BasalValue[array.length()];
for (Integer index = 0; index < array.length(); index++) {
JSONObject o = array.getJSONObject(index);
Integer tas = o.getInt("timeAsSeconds");
Double value = o.getDouble("value");
ret[index] = new BasalValue(tas, value);
}
return ret;
} catch (JSONException e) {
e.printStackTrace();
}
return new BasalValue[0];
}
public String getBasalList(JSONObject profile) {
if (profile != null) {
try {
return getValuesList(profile.getJSONArray("basal"), null, new DecimalFormat("0.00"), "U");
} catch (JSONException e) {
e.printStackTrace();
}
}
return "";
}
@Nullable
public Double getTargetLow(Integer timeAsSeconds) {
return getTargetLow(getDefaultProfile(), timeAsSeconds);
}
@Nullable
public Double getTargetLow(JSONObject profile, Integer timeAsSeconds) {
if (profile != null) {
try {
return getValueToTime(profile.getJSONArray("target_low"), timeAsSeconds);
} catch (JSONException e) {
e.printStackTrace();
}
}
return 0D;
}
@Nullable
public Double getTargetHigh(Integer timeAsSeconds) {
return getTargetHigh(getDefaultProfile(), timeAsSeconds);
}
@Nullable
public Double getTargetHigh(JSONObject profile, Integer timeAsSeconds) {
if (profile != null) {
try {
return getValueToTime(profile.getJSONArray("target_high"), timeAsSeconds);
} catch (JSONException e) {
e.printStackTrace();
}
}
return 0D;
}
public String getTargetList() {
return getTargetList(getDefaultProfile());
}
public String getTargetList(JSONObject profile) {
if (profile != null) {
try {
return getValuesList(profile.getJSONArray("target_low"), profile.getJSONArray("target_high"), new DecimalFormat("0.0"), getUnits());
} catch (JSONException e) {
e.printStackTrace();
}
}
return "";
}
public String getActiveProfile() {
if (activeProfile != null)
return activeProfile;
else {
try {
JSONObject store = json.getJSONObject("store");
String defaultProfileName = (String) json.get("defaultProfile");
if (store.has(defaultProfileName)) {
return defaultProfileName;
}
log.error("Default profile not found");
return null;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
public void setActiveProfile(String newProfile) {
try {
JSONObject store = json.getJSONObject("store");
if (newProfile != null && store.has(newProfile)) {
activeProfile = newProfile;
} else {
log.error("Attempt to set wrong active profile");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public double getMaxDailyBasal() {
Double max = 0d;
for (Integer hour = 0; hour < 24; hour++) {
double value = getBasal(hour * 60 * 60);
if (value > max) max = value;
}
return max;
}
public static int secondsFromMidnight() {
Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static int secondsFromMidnight(Date date) {
Calendar c = Calendar.getInstance();
long now = date.getTime();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static int secondsFromMidnight(long date) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = date - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static Double toMgdl(Double value, String units) {
if (units.equals(Constants.MGDL)) return value;
else return value * Constants.MMOLL_TO_MGDL;
}
public static Double fromMgdlToUnits(Double value, String units) {
if (units.equals(Constants.MGDL)) return value;
else return value * Constants.MGDL_TO_MMOLL;
}
public static Double toUnits(Double valueInMgdl, Double valueInMmol, String units) {
if (units.equals(Constants.MGDL)) return valueInMgdl;
else return valueInMmol;
}
public static String toUnitsString(Double valueInMgdl, Double valueInMmol, String units) {
if (units.equals(Constants.MGDL)) return DecimalFormatter.to0Decimal(valueInMgdl);
else return DecimalFormatter.to1Decimal(valueInMmol);
}
}

View file

@ -29,6 +29,7 @@ import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
@ -47,7 +48,6 @@ import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastS
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSCal;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
@ -69,10 +69,9 @@ public class NSClientService extends Service {
static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder();
static NSProfile nsProfile;
static ProfileStore profileStore;
static public Handler handler;
static private HandlerThread handlerThread;
public static Socket mSocket;
public static boolean isConnected = false;
@ -101,7 +100,7 @@ public class NSClientService extends Service {
public NSClientService() {
registerBus();
if (handler == null) {
handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler");
HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
@ -174,14 +173,6 @@ public class NSClientService extends Service {
restart();
}
public static void setNsProfile(NSProfile profile) {
nsProfile = profile;
}
public static NSProfile getNsProfile() {
return nsProfile;
}
public void initialize() {
dataCounter = 0;
@ -334,9 +325,7 @@ public class NSClientService extends Service {
JSONArray profiles = (JSONArray) data.getJSONArray("profiles");
if (profiles.length() > 0) {
JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1);
String activeProfile = NSClientService.getNsProfile() == null ? null : NSClientService.getNsProfile().getActiveProfile();
NSProfile nsProfile = new NSProfile(profile, activeProfile);
NSClientService.setNsProfile(nsProfile);
profileStore = new ProfileStore(profile);
broadcastProfile = true;
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received"));
}
@ -358,20 +347,6 @@ public class NSClientService extends Service {
BroadcastStatus bs = new BroadcastStatus();
bs.handleNewStatus(nsStatus, MainApp.instance().getApplicationContext(), isDelta);
if (NSClientService.getNsProfile() != null) {
String oldActiveProfile = NSClientService.getNsProfile().getActiveProfile();
String receivedActiveProfile = nsStatus.getActiveProfile();
NSClientService.getNsProfile().setActiveProfile(receivedActiveProfile);
if (receivedActiveProfile != null) {
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "status activeProfile received: " + receivedActiveProfile));
}
// Change possible nulls to ""
String oldP = oldActiveProfile == null ? "" : oldActiveProfile;
String newP = receivedActiveProfile == null ? "" : receivedActiveProfile;
if (!newP.equals(oldP)) {
broadcastProfile = true;
}
}
/* Other received data to 2016/02/10
{
status: 'ok'
@ -393,9 +368,9 @@ public class NSClientService extends Service {
}
// If new profile received or change detected broadcast it
if (broadcastProfile && nsProfile != null) {
if (broadcastProfile && profileStore != null) {
BroadcastProfile bp = new BroadcastProfile();
bp.handleNewTreatment(nsProfile, MainApp.instance().getApplicationContext(), isDelta);
bp.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta);
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting"));
}
@ -419,12 +394,11 @@ public class NSClientService extends Service {
latestDateInReceivedData = treatment.getMills();
if (treatment.getAction() == null) {
if (!isCurrent(treatment)) continue;
addedTreatments.put(jsonTreatment);
} else if (treatment.getAction().equals("update")) {
if (!isCurrent(treatment)) continue;
updatedTreatments.put(jsonTreatment);
} else if (treatment.getAction().equals("remove")) {
if (!isCurrent(treatment)) continue;
removedTreatments.put(jsonTreatment);
}
}
@ -481,7 +455,6 @@ public class NSClientService extends Service {
}
if (data.has("sgvs")) {
BroadcastSgvs bs = new BroadcastSgvs();
String units = nsProfile != null ? nsProfile.getUnits() : "mg/dl";
JSONArray sgvs = (JSONArray) data.getJSONArray("sgvs");
if (sgvs.length() > 0)
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));

View file

@ -22,7 +22,7 @@ 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.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.SP;
public class DetermineBasalAdapterAMAJS {
@ -190,7 +190,7 @@ public class DetermineBasalAdapterAMAJS {
}
public void setData(NSProfile profile,
public void setData(Profile profile,
double maxIob,
double maxBasal,
double minBg,
@ -215,8 +215,8 @@ public class DetermineBasalAdapterAMAJS {
mProfile.add("min_bg", minBg);
mProfile.add("max_bg", maxBg);
mProfile.add("target_bg", targetBg);
mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight()));
mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units));
mProfile.add("carb_ratio", profile.getIc());
mProfile.add("sens", Profile.toMgdl(profile.getIsf().doubleValue(), units));
mProfile.add("max_daily_safety_multiplier", SP.getInt("openapsama_max_daily_safety_multiplier", 3));
mProfile.add("current_basal_safety_multiplier", SP.getInt("openapsama_current_basal_safety_multiplier", 4));
mProfile.add("skip_neutral_temps", true);

View file

@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil;
@ -132,7 +132,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
PumpInterface pump = MainApp.getConfigBuilder();
if (!isEnabled(PluginBase.APS)) {
@ -149,20 +149,6 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
return;
}
if (profile == null || profile.getIc(NSProfile.secondsFromMidnight()) == null || profile.getIsf(NSProfile.secondsFromMidnight()) == null || profile.getBasal(NSProfile.secondsFromMidnight()) == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noprofile)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noprofile));
return;
}
if (pump == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_nopump)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_nopump));
return;
}
String units = profile.getUnits();
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
@ -178,9 +164,9 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
double minBg = Profile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
double maxBg = Profile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
double targetBg = Profile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d);
@ -216,12 +202,12 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
if (!checkOnlyHardLimits(profile.getDia(), "dia", 2, 7)) return;
if (!checkOnlyHardLimits(profile.getIc(profile.secondsFromMidnight()), "carbratio", 2, 100))
return;
if (!checkOnlyHardLimits(NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units), "sens", 2, 900))
if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf().doubleValue(), units), "sens", 2, 900))
return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.1, 10)) return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, 5)) return;
long oldestDataAvailable = MainApp.getConfigBuilder().oldestDataAvaialable();
long oldestDataAvailable = MainApp.getConfigBuilder().oldestDataAvailable();
long getBGDataFrom = Math.max(oldestDataAvailable, (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + profile.getDia())));
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString());

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.SP;
public class DetermineBasalAdapterMAJS {
@ -217,7 +217,7 @@ public class DetermineBasalAdapterMAJS {
}
public void setData(NSProfile profile,
public void setData(Profile profile,
double maxIob,
double maxBasal,
double minBg,
@ -238,8 +238,8 @@ public class DetermineBasalAdapterMAJS {
mProfile.add("min_bg", minBg);
mProfile.add("max_bg", maxBg);
mProfile.add("target_bg", targetBg);
mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight()));
mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units));
mProfile.add("carb_ratio", profile.getIc());
mProfile.add("sens", Profile.toMgdl(profile.getIsf().doubleValue(), units));
mProfile.add("current_basal", pump.getBaseBasalRate());
mCurrentTemp.add("duration", MainApp.getConfigBuilder().getTempBasalRemainingMinutesFromHistory());

View file

@ -20,7 +20,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil;
@ -130,7 +130,7 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
PumpInterface pump = MainApp.getConfigBuilder();
if (!isEnabled(PluginBase.APS)) {
@ -147,20 +147,6 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
return;
}
if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noprofile)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noprofile));
return;
}
if (pump == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_nopump)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_nopump));
return;
}
String units = profile.getUnits();
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
@ -176,9 +162,9 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
double minBg = Profile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
double maxBg = Profile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
double targetBg = Profile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d);
@ -211,8 +197,8 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
maxBasal = verifyHardLimits(maxBasal, "max_basal", 0.1, 10);
if (!checkOnlyHardLimits(profile.getDia(), "dia", 2, 7)) return;
if (!checkOnlyHardLimits(profile.getIc(profile.secondsFromMidnight()), "carbratio", 2, 100)) return;
if (!checkOnlyHardLimits(NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units), "sens", 2, 900)) return;
if (!checkOnlyHardLimits(profile.getIc(), "carbratio", 2, 100)) return;
if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf().doubleValue(), units), "sens", 2, 900)) return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.1, 10)) return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, 5)) return;

View file

@ -24,7 +24,7 @@ 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.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.XdripCalibrations;
@ -60,8 +60,8 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
okButton = (Button) view.findViewById(R.id.overview_calibration_okbutton);
okButton.setOnClickListener(this);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Double bg = profile != null ? NSProfile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()) : 0d;
Profile profile = MainApp.getConfigBuilder().getProfile();
Double bg = profile != null ? Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()) : 0d;
String units = Constants.MGDL;
if (profile != null)
@ -83,7 +83,8 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
public void onClick(View view) {
switch (view.getId()) {
case R.id.overview_calibration_okbutton:
final Double bg = SafeParse.stringToDouble(this.bgView.getText().toString());;
final Double bg = SafeParse.stringToDouble(this.bgView.getText().toString());
;
XdripCalibrations.confirmAndSendCalibration(bg, context);
dismiss();
Answers.getInstance().logCustom(new CustomEvent("Calibration"));

View file

@ -52,7 +52,8 @@ import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.utils.BolusWizard;
@ -351,7 +352,8 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
}
private void initDialog() {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile));
@ -359,14 +361,14 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
}
ArrayList<CharSequence> profileList;
profileList = profile.getProfileList();
profileList = profileStore.getProfileList();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
R.layout.spinner_centered, profileList);
profileSpinner.setAdapter(adapter);
// set selected to actual profile
for (int p = 0; p < profileList.size(); p++) {
if (profileList.get(p).equals(profile.getActiveProfile()))
if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName()))
profileSpinner.setSelection(p);
}
@ -380,9 +382,9 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
if (lastBg != null) {
Double lastBgValue = lastBg.valueToUnits(units);
Double sens = profile.getIsf(NSProfile.secondsFromMidnight());
Double targetBGLow = profile.getTargetLow(NSProfile.secondsFromMidnight());
Double targetBGHigh = profile.getTargetHigh(NSProfile.secondsFromMidnight());
Double sens = profile.getIsf();
Double targetBGLow = profile.getTargetLow();
Double targetBGHigh = profile.getTargetHigh();
Double bgDiff;
if (lastBgValue <= targetBGLow) {
bgDiff = lastBgValue - targetBGLow;
@ -428,11 +430,11 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
}
private void calculateInsulin() {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
ProfileStore profile = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profileSpinner == null || profileSpinner.getSelectedItem() == null)
return; // not initialized yet
String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString();
JSONObject specificProfile = profile.getSpecificProfile(selectedAlternativeProfile);
Profile specificProfile = profile.getSpecificProfile(selectedAlternativeProfile);
// Entered values
Double c_bg = SafeParse.stringToDouble(bgInput.getText().toString());
@ -506,7 +508,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
// Trend
if (bgtrendCheckbox.isChecked()) {
if (wizard.glucoseStatus != null) {
bgTrend.setText((wizard.glucoseStatus.avgdelta > 0 ? "+" : "") + NSProfile.toUnitsString(wizard.glucoseStatus.avgdelta * 3, wizard.glucoseStatus.avgdelta * 3 / 18, profile.getUnits()) + " " + profile.getUnits());
bgTrend.setText((wizard.glucoseStatus.avgdelta > 0 ? "+" : "") + Profile.toUnitsString(wizard.glucoseStatus.avgdelta * 3, wizard.glucoseStatus.avgdelta * 3 / 18, specificProfile.getUnits()) + " " + specificProfile.getUnits());
} else {
bgTrend.setText("");
}

View file

@ -25,6 +25,10 @@ public class Notification {
public static final int APPROACHING_DAILY_LIMIT = 10;
public static final int NSCLIENT_NO_WRITE_PERMISSION = 11;
public static final int MISSING_SMS_PERMISSION = 12;
public static final int ISF_MISSING = 13;
public static final int IC_MISSING = 14;
public static final int BASAL_MISSING = 15;
public static final int TARGET_MISSING = 16;
public int id;
public Date date;

View file

@ -54,11 +54,14 @@ import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
@ -66,10 +69,13 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
@ -85,6 +91,7 @@ import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
@ -94,7 +101,6 @@ import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugi
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
@ -107,6 +113,7 @@ import info.nightscout.androidaps.plugins.Overview.graphExtensions.DoubleDataPoi
import info.nightscout.androidaps.plugins.Overview.graphExtensions.FixedLineGraphSeries;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.TimeAsXAxisLabelFormatter;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.VerticalTextsGraphSeries;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil;
@ -126,16 +133,17 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return overviewPlugin;
}
TextView timeView;
TextView bgView;
TextView arrowView;
TextView timeAgoView;
TextView deltaView;
TextView avgdeltaView;
TextView runningTempView;
TextView baseBasalView;
LinearLayout basalLayout;
TextView extendedBolusView;
TextView activeProfileView;
TextView iobView;
TextView cobView;
TextView apsModeView;
TextView tempTargetView;
TextView pumpStatusView;
@ -144,6 +152,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
GraphView bgGraph;
GraphView iobGraph;
TextView iage;
TextView cage;
TextView sage;
TextView pbage;
CheckBox showPredictionView;
CheckBox showBasalsView;
CheckBox showIobView;
@ -176,6 +189,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledUpdate = null;
final Handler timeHandler = new Handler();
public OverviewFragment() {
super();
if (sHandlerThread == null) {
@ -199,12 +214,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
View view;
if (smallHeight) {
if (MainApp.sResources.getBoolean(R.bool.isTablet)) {
view = inflater.inflate(R.layout.overview_fragment_tablet, container, false);
} else if (smallHeight) {
view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false);
} else {
view = inflater.inflate(R.layout.overview_fragment, container, false);
}
timeView = (TextView) view.findViewById(R.id.overview_time);
bgView = (TextView) view.findViewById(R.id.overview_bg);
arrowView = (TextView) view.findViewById(R.id.overview_arrow);
if (smallWidth) {
@ -213,9 +231,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
timeAgoView = (TextView) view.findViewById(R.id.overview_timeago);
deltaView = (TextView) view.findViewById(R.id.overview_delta);
avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta);
runningTempView = (TextView) view.findViewById(R.id.overview_runningtemp);
baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal);
basalLayout = (LinearLayout) view.findViewById(R.id.overview_basallayout);
extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus);
activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile);
pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus);
loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout);
@ -224,9 +241,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
pumpStatusView.setBackgroundColor(MainApp.sResources.getColor(R.color.colorInitializingBorder));
iobView = (TextView) view.findViewById(R.id.overview_iob);
cobView = (TextView) view.findViewById(R.id.overview_cob);
apsModeView = (TextView) view.findViewById(R.id.overview_apsmode);
tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget);
iage = (TextView) view.findViewById(R.id.careportal_insulinage);
cage = (TextView) view.findViewById(R.id.careportal_canulaage);
sage = (TextView) view.findViewById(R.id.careportal_sensorage);
pbage = (TextView) view.findViewById(R.id.careportal_pbage);
bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph);
iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph);
@ -251,7 +274,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
showCobView = (CheckBox) view.findViewById(R.id.overview_showcob);
showDeviationsView = (CheckBox) view.findViewById(R.id.overview_showdeviations);
showPredictionView.setChecked(SP.getBoolean("showprediction", false));
showBasalsView.setChecked(SP.getBoolean("showbasals", false));
showBasalsView.setChecked(SP.getBoolean("showbasals", true));
showIobView.setChecked(SP.getBoolean("showiob", false));
showCobView.setChecked(SP.getBoolean("showcob", false));
showDeviationsView.setChecked(SP.getBoolean("showdeviations", false));
@ -265,8 +288,21 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
notificationsView.setHasFixedSize(true);
llm = new LinearLayoutManager(view.getContext());
notificationsView.setLayoutManager(llm);
/*
final LinearLayout graphs = (LinearLayout)view.findViewById(R.id.overview_graphs_layout);
ViewTreeObserver observer = graphs.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
log.debug("Height: " + graphs.getHeight());
graphs.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
int heightNeeded = Math.max(320, graphs.getHeight() - 200);
if (heightNeeded != bgGraph.getHeight())
bgGraph.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, heightNeeded));
}
});
*/
bgGraph.getGridLabelRenderer().setGridColor(Color.rgb(0x75, 0x75, 0x75));
bgGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setGridColor(Color.rgb(0x75, 0x75, 0x75));
@ -286,6 +322,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
});
Timer timeTimer = new Timer();
timeTimer.schedule(new TimerTask() {
@Override
public void run() {
timeUpdate();
}
}, 0, 30000);
return view;
}
@ -594,16 +638,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
void onClickQuickwizard() {
final BgReading actualBg = DatabaseHelper.actualBg();
if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet
return;
final NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
final Profile profile = MainApp.getConfigBuilder().getProfile();
QuickWizard.QuickWizardEntry quickWizardEntry = getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && actualBg != null) {
quickWizardButton.setVisibility(View.VISIBLE);
String text = MainApp.sResources.getString(R.string.bolus) + ": " + quickWizardEntry.buttonText();
BolusWizard wizard = new BolusWizard();
wizard.doCalc(profile.getDefaultProfile(), quickWizardEntry.carbs(), 0d, actualBg.valueToUnits(profile.getUnits()), 0d, true, true, false, false);
wizard.doCalc(profile, quickWizardEntry.carbs(), 0d, actualBg.valueToUnits(profile.getUnits()), 0d, true, true, false, false);
final JSONObject boluscalcJSON = new JSONObject();
try {
@ -809,6 +851,20 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
private void timeUpdate() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (timeView != null) { //must not exists
timeView.setText(DateUtil.timeString(new Date()));
}
log.debug("Time updated");
}
});
}
public void scheduleUpdateGUI(final String from) {
class UpdateRunnable implements Runnable {
public void run() {
@ -835,19 +891,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
@SuppressLint("SetTextI18n")
public void updateGUI(String from) {
log.debug("updateGUI entered from: " + from);
updateNotifications();
BgReading actualBG = DatabaseHelper.actualBg();
BgReading lastBG = DatabaseHelper.lastBg();
if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null || MainApp.getConfigBuilder().getActiveProfile().getProfile() == null) {// app not initialized yet
if (MainApp.getConfigBuilder().getProfile() == null) {// app not initialized yet
pumpStatusView.setText(R.string.noprofileset);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
return;
} else {
}
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
}
updateNotifications();
CareportalFragment.updateAge(getActivity(), sage, iage, cage, pbage);
BgReading actualBG = DatabaseHelper.actualBg();
BgReading lastBG = DatabaseHelper.lastBg();
PumpInterface pump = MainApp.getConfigBuilder();
@ -855,6 +911,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
if (bgGraph == null)
return;
Profile profile = MainApp.getConfigBuilder().getProfile();
if (getActivity() == null)
return;
@ -893,13 +950,17 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
// temp target
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
if (tempTarget != null) {
tempTargetView.setTextColor(Color.BLACK);
tempTargetView.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetBackground));
tempTargetView.setVisibility(View.VISIBLE);
tempTargetView.setText(NSProfile.toUnitsString(tempTarget.low, NSProfile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + NSProfile.toUnitsString(tempTarget.high, NSProfile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits()));
if (tempTarget.low == tempTarget.high)
tempTargetView.setText(Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()));
else
tempTargetView.setText(Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + Profile.toUnitsString(tempTarget.high, Profile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits()));
} if (Config.NSCLIENT) {
tempTargetView.setVisibility(View.GONE);
} else {
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
@ -928,34 +989,41 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
// **** Calibration button ****
if (MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE) && profile != null && DatabaseHelper.actualBg() != null) {
if (MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE) && profile != null && DatabaseHelper.actualBg() != null) {
calibrationButton.setVisibility(View.VISIBLE);
} else {
calibrationButton.setVisibility(View.GONE);
}
TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime());
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
if (activeTemp != null) {
cancelTempButton.setVisibility(View.VISIBLE);
cancelTempButton.setText(MainApp.instance().getString(R.string.cancel) + "\n" + activeTemp.toStringShort());
runningTempView.setVisibility(View.VISIBLE);
runningTempView.setText(activeTemp.toString());
} else {
cancelTempButton.setVisibility(View.GONE);
runningTempView.setVisibility(View.GONE);
}
if (pump.getPumpDescription().isTempBasalCapable) {
basalLayout.setVisibility(View.VISIBLE);
baseBasalView.setText(DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + " U/h");
} else {
basalLayout.setVisibility(View.GONE);
String basalText = "";
if (activeTemp != null) {
basalText = activeTemp.toString() + " ";
}
if (Config.NSCLIENT)
basalText += "( " + DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + " U/h )";
else if (pump.getPumpDescription().isTempBasalCapable) {
basalText += "( " + DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + " U/h )";
}
baseBasalView.setText(basalText);
if (profile != null && profile.getActiveProfile() != null) {
activeProfileView.setText(profile.getActiveProfile());
ExtendedBolus extendedBolus = MainApp.getConfigBuilder().getExtendedBolusFromHistory(new Date().getTime());
String extendedBolusText = "";
if (extendedBolus != null) {
extendedBolusText = extendedBolus.toString();
}
if (extendedBolusView != null) // must not exists in all layouts
extendedBolusView.setText(extendedBolusText);
activeProfileView.setText(MainApp.getConfigBuilder().getProfileName());
activeProfileView.setBackgroundColor(Color.GRAY);
}
activeProfileView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
@ -992,7 +1060,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
BolusWizard wizard = new BolusWizard();
wizard.doCalc(profile.getDefaultProfile(), quickWizardEntry.carbs(), 0d, lastBG.valueToUnits(profile.getUnits()), 0d, true, true, false, false);
wizard.doCalc(profile, quickWizardEntry.carbs(), 0d, lastBG.valueToUnits(profile.getUnits()), 0d, true, true, false, false);
text += " " + DecimalFormatter.to2Decimal(wizard.calculatedTotalInsulin) + "U";
quickWizardButton.setText(text);
if (wizard.calculatedTotalInsulin <= 0)
@ -1014,12 +1082,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
Double lowLine = SP.getDouble("low_mark", 0d);
Double highLine = SP.getDouble("high_mark", 0d);
if (lowLine < 1) {
lowLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
lowLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
}
if (highLine < 1) {
highLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
highLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
}
timeUpdate();
// **** BG value ****
if (lastBG != null) {
@ -1034,9 +1103,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
arrowView.setTextColor(color);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null) {
deltaView.setText("Δ " + NSProfile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
avgdeltaView.setText("øΔ15m: " + NSProfile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
" øΔ40m: " + NSProfile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
avgdeltaView.setText("øΔ15m: " + Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
" øΔ40m: " + Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
} else {
deltaView.setText("Δ " + MainApp.sResources.getString(R.string.notavailable));
avgdeltaView.setText("");
@ -1068,6 +1137,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
iobView.setText(iobtext);
// cob
if (cobView != null) { // view must not exists
String cobText = "";
AutosensData autosensData = IobCobCalculatorPlugin.getAutosensData(new Date().getTime());
if (autosensData != null)
cobText = (int) autosensData.cob + " g " + String.format(MainApp.sResources.getString(R.string.minago), autosensData.minOld());
cobView.setText(cobText);
}
boolean showPrediction = showPredictionView.isChecked() && finalLastRun != null && finalLastRun.constraintsProcessed.getClass().equals(DetermineBasalResultAMA.class);
if (MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class) != null && MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class).isEnabled(PluginBase.APS)) {
showPredictionView.setVisibility(View.VISIBLE);
@ -1116,6 +1194,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
PointsGraphSeries<BgReading> seriesHigh;
PointsGraphSeries<BgReading> predSeries;
PointsWithLabelGraphSeries<Treatment> seriesTreatments;
VerticalTextsGraphSeries<ProfileSwitch> seriesProfileSwitch;
// **** TEMP BASALS graph ****
Double maxBasalValueFound = 0d;
@ -1130,7 +1209,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
double lastTempBasal = 0;
for (long time = fromTime; time < now; time += 1 * 60 * 1000L) {
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasalFromHistory(time);
double baseBasalValue = profile.getBasal(NSProfile.secondsFromMidnight(new Date(time)));
double baseBasalValue = MainApp.getConfigBuilder().getProfile(time).getBasal(Profile.secondsFromMidnight(time));
double baseLineValue = baseBasalValue;
double tempBasalValue = 0;
double basal = 0d;
@ -1346,7 +1425,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
else
inRangeArray.add(bg);
}
maxBgValue = NSProfile.fromMgdlToUnits(maxBgValue, units);
maxBgValue = Profile.fromMgdlToUnits(maxBgValue, units);
maxBgValue = units.equals(Constants.MGDL) ? Round.roundTo(maxBgValue, 40d) + 80 : Round.roundTo(maxBgValue, 2d) + 4;
if (highLine > maxBgValue) maxBgValue = highLine;
Integer numOfHorizLines = units.equals(Constants.MGDL) ? (int) (maxBgValue / 40 + 1) : (int) (maxBgValue / 2 + 1);
@ -1358,25 +1437,26 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
low = lowArray.toArray(low);
high = highArray.toArray(high);
boolean isTablet = MainApp.sResources.getBoolean(R.bool.isTablet);
if (inRange.length > 0) {
bgGraph.addSeries(seriesInRage = new PointsGraphSeries<>(inRange));
seriesInRage.setShape(PointsGraphSeries.Shape.POINT);
seriesInRage.setSize(5);
seriesInRage.setSize(isTablet ? 8 : 5);
seriesInRage.setColor(MainApp.sResources.getColor(R.color.inrange));
}
if (low.length > 0) {
bgGraph.addSeries(seriesLow = new PointsGraphSeries<>(low));
seriesLow.setShape(PointsGraphSeries.Shape.POINT);
seriesLow.setSize(5);
seriesLow.setSize(isTablet ? 8 : 5);
seriesLow.setColor(MainApp.sResources.getColor(R.color.low));
}
if (high.length > 0) {
bgGraph.addSeries(seriesHigh = new PointsGraphSeries<>(high));
seriesHigh.setShape(PointsGraphSeries.Shape.POINT);
seriesHigh.setSize(5);
seriesHigh.setSize(isTablet ? 8 : 5);
seriesHigh.setColor(MainApp.sResources.getColor(R.color.high));
}
@ -1423,7 +1503,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
for (int tx = 0; tx < treatments.size(); tx++) {
Treatment t = treatments.get(tx);
if (t.date < fromTime || t.date > now) continue;
if (t.date < fromTime || t.date > endTime) continue;
t.setYValue(bgReadingsArray);
filteredTreatments.add(t);
}
@ -1436,6 +1516,24 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
seriesTreatments.setColor(Color.CYAN);
}
// ProfileSwitch
List<ProfileSwitch> profileSwitches = MainApp.getConfigBuilder().getProfileSwitchesFromHistory().getList();
List<ProfileSwitch> filteredProfileSwitches = new ArrayList<ProfileSwitch>();
for (int tx = 0; tx < profileSwitches.size(); tx++) {
ProfileSwitch t = profileSwitches.get(tx);
if (t.date < fromTime || t.date > endTime) continue;
filteredProfileSwitches.add(t);
}
ProfileSwitch[] profileSwitchArray = new ProfileSwitch[filteredProfileSwitches.size()];
profileSwitchArray = filteredProfileSwitches.toArray(profileSwitchArray);
if (profileSwitchArray.length > 0) {
bgGraph.addSeries(seriesProfileSwitch = new VerticalTextsGraphSeries<ProfileSwitch>(profileSwitchArray));
//seriesProfileSwitch.setShape(PointsWithLabelGraphSeries.Shape.TRIANGLE);
seriesProfileSwitch.setSize(10);
seriesProfileSwitch.setColor(Color.CYAN);
}
// set manual y bounds to have nice steps
bgGraph.getViewport().setMaxY(maxBgValue);
bgGraph.getViewport().setMinY(0);

View file

@ -10,7 +10,7 @@ import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.DateUtil;
/**
@ -47,7 +47,7 @@ public class QuickWizard {
}
public Boolean isActive() {
return NSProfile.secondsFromMidnight() >= validFrom() && NSProfile.secondsFromMidnight() <= validTo();
return Profile.secondsFromMidnight() >= validFrom() && Profile.secondsFromMidnight() <= validTo();
}
public String buttonText() {

View file

@ -0,0 +1,326 @@
package info.nightscout.androidaps.plugins.Overview.graphExtensions;
/**
* GraphView
* Copyright (C) 2014 Jonas Gehring
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License,
* with the "Linking Exception", which can be found at the license.txt
* file in this program.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* with the "Linking Exception" along with this program; if not,
* write to the author Jonas Gehring <g.jjoe64@gmail.com>.
* <p>
* Added by mike
*/
/**
* Added by mike
*/
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.BaseSeries;
import java.util.Iterator;
/**
* Series that plots the data as points.
* The points can be different shapes or a
* complete custom drawing.
*
* @author jjoe64
*/
public class VerticalTextsGraphSeries<E extends DataPointWithLabelInterface> extends BaseSeries<E> {
/**
* interface to implement a custom
* drawing for the data points.
*/
public static interface CustomShape {
/**
* called when drawing a single data point.
* use the x and y coordinates to render your
* drawing at this point.
*
* @param canvas canvas to draw on
* @param paint internal paint object. this has the correct color.
* But you can use your own paint.
* @param x x-coordinate the point has to be drawn to
* @param y y-coordinate the point has to be drawn to
* @param dataPoint the related data point
*/
void draw(Canvas canvas, Paint paint, float x, float y, DataPointWithLabelInterface dataPoint);
}
/**
* choose a predefined shape to render for
* each data point.
* You can also render a custom drawing via {@link com.jjoe64.graphview.series.PointsGraphSeries.CustomShape}
*/
public enum Shape {
/**
* draws a point / circle
*/
POINT,
/**
* draws a triangle
*/
TRIANGLE,
/**
* draws a rectangle
*/
RECTANGLE
}
/**
* wrapped styles for this series
*/
private final class Styles {
/**
* this is used for the size of the shape that
* will be drawn.
* This is useless if you are using a custom shape.
*/
float size;
/**
* the shape that will be drawn for each point.
*/
Shape shape;
}
/**
* wrapped styles
*/
private Styles mStyles;
/**
* internal paint object
*/
private Paint mPaint;
/**
* handler to use a custom drawing
*/
private CustomShape mCustomShape;
/**
* creates the series without data
*/
public VerticalTextsGraphSeries() {
init();
}
/**
* creates the series with data
*
* @param data datapoints
*/
public VerticalTextsGraphSeries(E[] data) {
super(data);
init();
}
/**
* inits the internal objects
* set the defaults
*/
protected void init() {
mStyles = new Styles();
mStyles.size = 20f;
mPaint = new Paint();
mPaint.setStrokeCap(Paint.Cap.ROUND);
setShape(Shape.POINT);
}
/**
* plot the data to the viewport
*
* @param graphView graphview
* @param canvas canvas to draw on
* @param isSecondScale whether it is the second scale
*/
@Override
public void draw(GraphView graphView, Canvas canvas, boolean isSecondScale) {
resetDataPoints();
// get data
double maxX = graphView.getViewport().getMaxX(false);
double minX = graphView.getViewport().getMinX(false);
double maxY;
double minY;
if (isSecondScale) {
maxY = graphView.getSecondScale().getMaxY();
minY = graphView.getSecondScale().getMinY();
} else {
maxY = graphView.getViewport().getMaxY(false);
minY = graphView.getViewport().getMinY(false);
}
Iterator<E> values = getValues(minX, maxX);
// draw background
double lastEndY = 0;
double lastEndX = 0;
// draw data
mPaint.setColor(getColor());
double diffY = maxY - minY;
double diffX = maxX - minX;
float graphHeight = graphView.getGraphContentHeight();
float graphWidth = graphView.getGraphContentWidth();
float graphLeft = graphView.getGraphContentLeft();
float graphTop = graphView.getGraphContentTop();
lastEndY = 0;
lastEndX = 0;
float firstX = 0;
int i = 0;
while (values.hasNext()) {
E value = values.next();
double valY = value.getY() - minY;
double ratY = valY / diffY;
double y = graphHeight * ratY;
double valX = value.getX() - minX;
double ratX = valX / diffX;
double x = graphWidth * ratX;
double orgX = x;
double orgY = y;
// overdraw
boolean overdraw = false;
if (x > graphWidth) { // end right
overdraw = true;
}
if (y < 0) { // end bottom
overdraw = true;
}
if (y > graphHeight) { // end top
overdraw = true;
}
/* Fix a bug that continue to show the DOT after Y axis */
if (x < 0) {
overdraw = true;
}
float endX = (float) x + (graphLeft + 1);
float endY = (float) (graphTop - y) + graphHeight;
registerDataPoint(endX, endY, value);
// draw data point
if (!overdraw) {
if (value.getLabel() != null) {
mPaint.setTextSize((int) (getSize() * 3));
mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
Rect bounds = new Rect();
mPaint.getTextBounds(value.getLabel(), 0, value.getLabel().length(), bounds);
mPaint.setStyle(Paint.Style.STROKE);
float px = endX + bounds.height() / 2;
float py = (float) (graphHeight * ratY + bounds.width() + 10);
canvas.save();
canvas.rotate(-90, px, py);
canvas.drawText(value.getLabel(), px, py, mPaint);
canvas.drawRect(px - 3, bounds.top + py - 3, bounds.right + px + 3, bounds.bottom + py + 3, mPaint);
canvas.restore();
}
}
i++;
}
}
/**
* helper to render triangle
*
* @param point array with 3 coordinates
* @param canvas canvas to draw on
* @param paint paint object
*/
private void drawArrows(Point[] point, Canvas canvas, Paint paint) {
float[] points = new float[8];
points[0] = point[0].x;
points[1] = point[0].y;
points[2] = point[1].x;
points[3] = point[1].y;
points[4] = point[2].x;
points[5] = point[2].y;
points[6] = point[0].x;
points[7] = point[0].y;
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
Path path = new Path();
path.moveTo(point[0].x, point[0].y);
path.lineTo(point[1].x, point[1].y);
path.lineTo(point[2].x, point[2].y);
canvas.drawPath(path, paint);
}
/**
* This is used for the size of the shape that
* will be drawn.
* This is useless if you are using a custom shape.
*
* @return the size of the shape
*/
public float getSize() {
return mStyles.size;
}
/**
* This is used for the size of the shape that
* will be drawn.
* This is useless if you are using a custom shape.
*
* @param radius the size of the shape
*/
public void setSize(float radius) {
mStyles.size = radius;
}
/**
* @return the shape that will be drawn for each point
*/
public Shape getShape() {
return mStyles.shape;
}
/**
* @param s the shape that will be drawn for each point
*/
public void setShape(Shape s) {
mStyles.shape = s;
}
/**
* Use a custom handler to render your own
* drawing for each data point.
*
* @param shape handler to use a custom drawing
*/
public void setCustomShape(CustomShape shape) {
mCustomShape = shape;
}
}

View file

@ -32,7 +32,7 @@ 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.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.DecimalFormatter;
/**
@ -102,7 +102,7 @@ public class PersistentNotificationPlugin implements PluginBase{
if (getType() == type) {
this.fragmentEnabled = fragmentEnabled;
checkBusRegistration();
updateNotification();
//updateNotification();
}
}
@ -118,8 +118,7 @@ public class PersistentNotificationPlugin implements PluginBase{
String line1 = ctx.getString(R.string.noprofile);
if (MainApp.getConfigBuilder().getActiveProfile() == null) return;
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
BgReading lastBG = DatabaseHelper.lastBg();
@ -158,8 +157,7 @@ public class PersistentNotificationPlugin implements PluginBase{
String line3 = DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + " U/h";
if (profile != null && profile.getActiveProfile() != null)
line3 += " - " + profile.getActiveProfile();
line3 += " - " + MainApp.getConfigBuilder().getProfileName();
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
@ -197,7 +195,8 @@ public class PersistentNotificationPlugin implements PluginBase{
} else {
try {
MainApp.bus().unregister(this);
} catch (Exception e) {}
} catch (Exception e) {
}
}
}
@ -216,8 +215,7 @@ public class PersistentNotificationPlugin implements PluginBase{
}
if (units.equals(Constants.MGDL)) {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMGDL));
}
else {
} else {
deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMMOL));
}
return deltastring;

View file

@ -15,7 +15,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
@ -33,7 +33,8 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
private static boolean fragmentEnabled = false;
private static boolean fragmentVisible = true;
private static NSProfile convertedProfile = null;
private static ProfileStore convertedProfile = null;
private static String convertedProfileName = null;
boolean mgdl;
boolean mmol;
@ -203,17 +204,22 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
} catch (JSONException e) {
e.printStackTrace();
}
convertedProfile = new NSProfile(json, profileName);
convertedProfile = new ProfileStore(json);
convertedProfileName = profileName;
}
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
performLimitCheck();
return convertedProfile;
}
@Override
public String getProfileName() {
performLimitCheck();
return convertedProfileName;
}
private void performLimitCheck() {
if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) {
String msg = String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Percentage");

View file

@ -15,7 +15,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.utils.SP;
/**
@ -27,7 +27,8 @@ public class LocalProfilePlugin implements PluginBase, ProfileInterface {
private static boolean fragmentEnabled = false;
private static boolean fragmentVisible = true;
private static NSProfile convertedProfile = null;
private static ProfileStore convertedProfile = null;
private static String convertedProfileName = null;
final private String DEFAULTARRAY = "[{\"timeAsSeconds\":0,\"value\":0}]";
@ -230,12 +231,18 @@ public class LocalProfilePlugin implements PluginBase, ProfileInterface {
} catch (JSONException e) {
e.printStackTrace();
}
convertedProfile = new NSProfile(json, "LocalProfile");
convertedProfile = new ProfileStore(json);
convertedProfileName = "LocalProfile";
}
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
return convertedProfile;
}
@Override
public String getProfileName() {
return convertedProfileName;
}
}

View file

@ -12,6 +12,7 @@ import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
import info.nightscout.utils.DecimalFormatter;
@ -74,19 +75,21 @@ public class NSProfileFragment extends Fragment {
}
private void updateGUI() {
if (nsProfilePlugin.profile == null) {
if (MainApp.getConfigBuilder().getProfile() == null) {
noProfile.setVisibility(View.VISIBLE);
return;
} else {
noProfile.setVisibility(View.GONE);
}
units.setText(nsProfilePlugin.profile.getUnits());
dia.setText(DecimalFormatter.to2Decimal(nsProfilePlugin.profile.getDia()) + " h");
activeProfile.setText(nsProfilePlugin.profile.getActiveProfile());
ic.setText(nsProfilePlugin.profile.getIcList());
isf.setText(nsProfilePlugin.profile.getIsfList());
basal.setText(nsProfilePlugin.profile.getBasalList());
target.setText(nsProfilePlugin.profile.getTargetList());
Profile profile = MainApp.getConfigBuilder().getProfile();
units.setText(profile.getUnits());
dia.setText(DecimalFormatter.to2Decimal(profile.getDia()) + " h");
activeProfile.setText(MainApp.getConfigBuilder().getProfileName());
ic.setText(profile.getIcList());
isf.setText(profile.getIsfList());
basal.setText(profile.getBasalList());
target.setText(profile.getTargetList());
}
}

View file

@ -1,8 +1,6 @@
package info.nightscout.androidaps.plugins.ProfileNS;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import com.squareup.otto.Subscribe;
@ -16,11 +14,12 @@ import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.utils.SP;
/**
@ -37,7 +36,7 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
static boolean fragmentEnabled = true;
static boolean fragmentVisible = true;
static NSProfile profile = null;
static ProfileStore profile = null;
public NSProfilePlugin() {
MainApp.bus().register(this);
@ -63,12 +62,12 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
@Override
public boolean isEnabled(int type) {
return type == PROFILE && fragmentEnabled;
return type == PROFILE && (Config.NSCLIENT || fragmentEnabled);
}
@Override
public boolean isVisibleInTabs(int type) {
return type == PROFILE && fragmentVisible;
return type == PROFILE && (Config.NSCLIENT ||fragmentVisible);
}
@Override
@ -83,7 +82,7 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
@Override
public boolean showInList(int type) {
return true;
return !Config.NSCLIENT;
}
@Override
@ -102,18 +101,24 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
}
@Subscribe
public void onStatusEvent(final EventNewBasalProfile ev) {
profile = new NSProfile(ev.newNSProfile.getData(), ev.newNSProfile.getActiveProfile());
public static void storeNewProfile(ProfileStore newProfile) {
profile = new ProfileStore(newProfile.getData());
storeNSProfile();
MainApp.bus().post(new EventNSProfileUpdateGUI());
PumpInterface pump = MainApp.getConfigBuilder();
if (SP.getBoolean("syncprofiletopump", false)) {
if (pump.setNewBasalProfile(MainApp.getConfigBuilder().getProfile()) == PumpInterface.SUCCESS) {
SmsCommunicatorPlugin smsCommunicatorPlugin = (SmsCommunicatorPlugin) MainApp.getSpecificPlugin(SmsCommunicatorPlugin.class);
if (smsCommunicatorPlugin != null && smsCommunicatorPlugin.isEnabled(PluginBase.GENERAL)) {
smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.sResources.getString(R.string.profile_set_ok));
}
}
}
private void storeNSProfile() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("profile", profile.getData().toString());
editor.putString("activeProfile", profile.getActiveProfile());
editor.apply();
}
private static void storeNSProfile() {
SP.putString("profile", profile.getData().toString());
if (Config.logPrefsChange)
log.debug("Storing profile");
}
@ -121,14 +126,12 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
private void loadNSProfile() {
if (Config.logPrefsChange)
log.debug("Loading stored profile");
String activeProfile = SP.getString("activeProfile", null);
String profileString = SP.getString("profile", null);
if (profileString != null) {
if (Config.logPrefsChange) {
log.debug("Loaded profile: " + profileString);
log.debug("Loaded active profile: " + activeProfile);
try {
profile = new NSProfile(new JSONObject(profileString), activeProfile);
profile = new ProfileStore(new JSONObject(profileString));
} catch (JSONException e) {
e.printStackTrace();
profile = null;
@ -146,7 +149,12 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
@Nullable
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
return profile;
}
@Override
public String getProfileName() {
return profile.getDefaultProfileName();
}
}

View file

@ -15,7 +15,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.utils.SP;
/**
@ -27,7 +27,7 @@ public class SimpleProfilePlugin implements PluginBase, ProfileInterface {
private static boolean fragmentEnabled = false;
private static boolean fragmentVisible = true;
private static NSProfile convertedProfile = null;
private static ProfileStore convertedProfile = null;
boolean mgdl;
boolean mmol;
@ -193,12 +193,17 @@ public class SimpleProfilePlugin implements PluginBase, ProfileInterface {
} catch (JSONException e) {
e.printStackTrace();
}
convertedProfile = new NSProfile(json, "SimpleProfile");
convertedProfile = new ProfileStore(json);
}
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
return convertedProfile;
}
@Override
public String getProfileName() {
return "SimpleProfile";
}
}

View file

@ -30,13 +30,13 @@ import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
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.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
@ -231,7 +231,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
// Pump interface
@Override
public int setNewBasalProfile(NSProfile profile) {
public int setNewBasalProfile(Profile profile) {
if (sExecutionService == null) {
log.error("setNewBasalProfile sExecutionService is null");
return FAILED;
@ -256,7 +256,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
}
@Override
public boolean isThisProfileSet(NSProfile profile) {
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
if (pump.pumpProfiles == null)
@ -309,7 +309,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.insulin = t.insulin;
detailedBolusInfo.date = new Date().getTime();
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
return result;
} else {
PumpEnactResult result = new PumpEnactResult();
@ -681,7 +681,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getActiveProfile().getProfile().getActiveProfile());
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
@ -782,12 +782,17 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
@Nullable
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
if (pump.lastSettingsRead.getTime() == 0)
return null; // no info now
return pump.createConvertedProfile();
}
@Override
public String getProfileName() {
return pump.createConvertedProfileName();
}
// Reply for sms communicator
public String shortStatus(boolean veryShort) {
String ret = "";

View file

@ -9,7 +9,7 @@ import java.util.Date;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.utils.SP;
/**
@ -132,7 +132,7 @@ public class DanaRPump {
public double maxBolus;
public double maxBasal;
public NSProfile createConvertedProfile() {
public ProfileStore createConvertedProfile() {
JSONObject json = new JSONObject();
JSONObject store = new JSONObject();
JSONObject profile = new JSONObject();
@ -189,7 +189,12 @@ public class DanaRPump {
} catch (Exception e) {
return null;
}
return new NSProfile(json, PROFILE_PREFIX + (activeProfile + 1));
return new ProfileStore(json);
}
public String createConvertedProfileName() {
return PROFILE_PREFIX + (activeProfile + 1);
}
}

View file

@ -17,9 +17,12 @@ import java.util.Date;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.utils.DecimalFormatter;
/**
@ -42,14 +45,11 @@ public class ProfileViewDialog extends DialogFragment {
Handler mHandler;
static HandlerThread mHandlerThread;
NSProfile profile = null;
public ProfileViewDialog() {
mHandlerThread = new HandlerThread(ProfileViewDialog.class.getSimpleName());
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
profile = ((DanaRPlugin) MainApp.getSpecificPlugin(DanaRPlugin.class)).getProfile();
}
@Override
@ -74,7 +74,12 @@ public class ProfileViewDialog extends DialogFragment {
@Override
public void run() {
DanaRPump.getInstance().lastSettingsRead = new Date(0);
if (MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginBase.PUMP))
DanaRPlugin.doConnect("ProfileViewDialog");
if (MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginBase.PUMP))
DanaRKoreanPlugin.doConnect("ProfileViewDialog");
if (MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginBase.PUMP))
DanaRv2Plugin.doConnect("ProfileViewDialog");
}
});
dismiss();
@ -92,15 +97,16 @@ public class ProfileViewDialog extends DialogFragment {
}
private void setContent() {
if (profile == null) {
noProfile.setVisibility(View.VISIBLE);
return;
} else {
noProfile.setVisibility(View.GONE);
}
// if (profile == null) {
// noProfile.setVisibility(View.VISIBLE);
// return;
// } else {
// noProfile.setVisibility(View.GONE);
// }
Profile profile = MainApp.getConfigBuilder().getProfile();
units.setText(profile.getUnits());
dia.setText(DecimalFormatter.to2Decimal(profile.getDia()) + " h");
activeProfile.setText(profile.getActiveProfile());
activeProfile.setText(MainApp.getConfigBuilder().getProfileName());
ic.setText(profile.getIcList());
isf.setText(profile.getIsfList());
basal.setText(profile.getBasalList());

View file

@ -21,16 +21,11 @@ import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@ -39,11 +34,10 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils;
@ -57,7 +51,7 @@ public class DanaRHistoryActivity extends Activity {
private Handler mHandler;
private static HandlerThread mHandlerThread;
static NSProfile profile = null;
static Profile profile = null;
Spinner historyTypeSpinner;
TextView statusView;
@ -249,7 +243,7 @@ public class DanaRHistoryActivity extends Activity {
clearCardView();
}
});
profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile));
finish();
@ -318,7 +312,7 @@ public class DanaRHistoryActivity extends Activity {
holder.alarm.setVisibility(View.GONE);
break;
case RecordTypes.RECORD_TYPE_GLUCOSE:
holder.value.setText(NSProfile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profile.getUnits()));
holder.value.setText(Profile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profile.getUnits()));
// rest is the same
case RecordTypes.RECORD_TYPE_CARBO:
case RecordTypes.RECORD_TYPE_BASALHOUR:

View file

@ -13,9 +13,9 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.ToastUtils;
@ -47,7 +47,7 @@ public class DanaRNSHistorySync {
public void sync(int what) {
try {
ConfigBuilderPlugin ConfigBuilderPlugin = MainApp.getConfigBuilder();
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile));
return;
@ -179,7 +179,7 @@ public class DanaRNSHistorySync {
log.debug("Syncing glucose record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate));
nsrec.put(DANARSIGNATURE, record.bytes);
nsrec.put("eventType", "BG Check");
nsrec.put("glucose", NSProfile.fromMgdlToUnits(record.recordValue, profile.getUnits()));
nsrec.put("glucose", Profile.fromMgdlToUnits(record.recordValue, profile.getUnits()));
nsrec.put("glucoseType", "Finger");
nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name));

View file

@ -5,14 +5,12 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
@ -27,16 +25,11 @@ import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
@ -50,12 +43,13 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
@ -167,18 +161,15 @@ public class DanaRStatsActivity extends Activity {
decimalFormat = new DecimalFormat("0.000");
llm = new LinearLayoutManager(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
TBB = preferences.getString("TBB", "10.00");
TBB = SP.getString("TBB", "10.00");
totalBaseBasal.setText(TBB);
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile();
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfileInterface();
if (pi != null && pi instanceof CircadianPercentageProfilePlugin) {
double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum();
totalBaseBasal.setText(decimalFormat.format(cppTBB));
SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit();
TBB = preferences.getString("TBB", "");
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
}
// stats table
@ -326,10 +317,8 @@ public class DanaRStatsActivity extends Activity {
if (hasFocus) {
totalBaseBasal.getText().clear();
} else {
SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit();
TBB = preferences.getString("TBB", "");
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(totalBaseBasal.getWindowToken(), 0);

View file

@ -18,7 +18,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
@ -33,6 +32,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.SerialIOThread;
@ -79,7 +79,6 @@ import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRBolusStart;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
@ -512,7 +511,7 @@ public class DanaRExecutionService extends Service {
return true;
}
public boolean updateBasalsInPump(final NSProfile profile) {
public boolean updateBasalsInPump(final Profile profile) {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
@ -527,7 +526,7 @@ public class DanaRExecutionService extends Service {
return true;
}
private double[] buildDanaRProfileRecord(NSProfile nsProfile) {
private double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
//Some values get truncated to the next lower one.

View file

@ -30,13 +30,13 @@ import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
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.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
@ -234,7 +234,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
// Pump interface
@Override
public int setNewBasalProfile(NSProfile profile) {
public int setNewBasalProfile(Profile profile) {
if (sExecutionService == null) {
log.error("setNewBasalProfile sExecutionService is null");
return FAILED;
@ -259,7 +259,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
}
@Override
public boolean isThisProfileSet(NSProfile profile) {
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
if (pump.pumpProfiles == null)
@ -302,7 +302,8 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) {
Treatment t = new Treatment(detailedBolusInfo.insulinInterface);
boolean connectionOK = false;
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, t);
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0)
connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, t);
PumpEnactResult result = new PumpEnactResult();
result.success = connectionOK;
result.bolusDelivered = t.insulin;
@ -312,7 +313,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.insulin = t.insulin;
detailedBolusInfo.date = new Date().getTime();
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
return result;
} else {
PumpEnactResult result = new PumpEnactResult();
@ -684,7 +685,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getActiveProfile().getProfile().getActiveProfile());
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
@ -785,12 +786,17 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
@Nullable
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
if (pump.lastSettingsRead.getTime() == 0)
return null; // no info now
return pump.createConvertedProfile();
}
@Override
public String getProfileName() {
return pump.createConvertedProfileName();
}
// Reply for sms communicator
public String shortStatus(boolean veryShort) {
String ret = "";

View file

@ -21,16 +21,11 @@ import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@ -39,12 +34,11 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils;
@ -58,7 +52,7 @@ public class DanaRHistoryActivity extends Activity {
private Handler mHandler;
private static HandlerThread mHandlerThread;
static NSProfile profile = null;
static Profile profile = null;
Spinner historyTypeSpinner;
TextView statusView;
@ -248,7 +242,7 @@ public class DanaRHistoryActivity extends Activity {
clearCardView();
}
});
profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile));
finish();
@ -317,7 +311,7 @@ public class DanaRHistoryActivity extends Activity {
holder.alarm.setVisibility(View.GONE);
break;
case RecordTypes.RECORD_TYPE_GLUCOSE:
holder.value.setText(NSProfile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profile.getUnits()));
holder.value.setText(Profile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profile.getUnits()));
// rest is the same
case RecordTypes.RECORD_TYPE_CARBO:
case RecordTypes.RECORD_TYPE_BASALHOUR:

View file

@ -5,14 +5,12 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
@ -27,16 +25,11 @@ import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
@ -50,12 +43,13 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
@ -167,18 +161,15 @@ public class DanaRStatsActivity extends Activity {
decimalFormat = new DecimalFormat("0.000");
llm = new LinearLayoutManager(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
TBB = preferences.getString("TBB", "10.00");
TBB = SP.getString("TBB", "10.00");
totalBaseBasal.setText(TBB);
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile();
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfileInterface();
if (pi != null && pi instanceof CircadianPercentageProfilePlugin) {
double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum();
totalBaseBasal.setText(decimalFormat.format(cppTBB));
SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit();
TBB = preferences.getString("TBB", "");
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
}
// stats table
@ -326,10 +317,8 @@ public class DanaRStatsActivity extends Activity {
if (hasFocus) {
totalBaseBasal.getText().clear();
} else {
SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit();
TBB = preferences.getString("TBB", "");
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(totalBaseBasal.getWindowToken(), 0);

View file

@ -18,7 +18,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
@ -33,6 +32,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusProgress;
@ -70,7 +70,6 @@ import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRBolusStart;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.SerialIOThread;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgCheckValue_k;
@ -489,7 +488,7 @@ public class DanaRKoreanExecutionService extends Service {
return true;
}
public boolean updateBasalsInPump(final NSProfile profile) {
public boolean updateBasalsInPump(final Profile profile) {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
@ -502,7 +501,7 @@ public class DanaRKoreanExecutionService extends Service {
return true;
}
private double[] buildDanaRProfileRecord(NSProfile nsProfile) {
private double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
double value = Math.round(100d * nsProfile.getBasal(hour * 60 * 60))/100d + 0.00001;

View file

@ -31,13 +31,13 @@ import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
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.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
@ -219,7 +219,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte
// Pump interface
@Override
public int setNewBasalProfile(NSProfile profile) {
public int setNewBasalProfile(Profile profile) {
if (sExecutionService == null) {
log.error("setNewBasalProfile sExecutionService is null");
return FAILED;
@ -244,7 +244,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte
}
@Override
public boolean isThisProfileSet(NSProfile profile) {
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
if (pump.pumpProfiles == null)
@ -599,7 +599,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getActiveProfile().getProfile().getActiveProfile());
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
@ -700,12 +700,17 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte
@Nullable
@Override
public NSProfile getProfile() {
public ProfileStore getProfile() {
if (pump.lastSettingsRead.getTime() == 0)
return null; // no info now
return pump.createConvertedProfile();
}
@Override
public String getProfileName() {
return pump.createConvertedProfileName();
}
// Reply for sms communicator
public String shortStatus(boolean veryShort) {
String ret = "";

View file

@ -21,16 +21,11 @@ import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@ -39,11 +34,10 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@ -58,7 +52,7 @@ public class DanaRHistoryActivity extends Activity {
private Handler mHandler;
private static HandlerThread mHandlerThread;
static NSProfile profile = null;
static Profile profile = null;
Spinner historyTypeSpinner;
TextView statusView;
@ -249,7 +243,7 @@ public class DanaRHistoryActivity extends Activity {
clearCardView();
}
});
profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile));
finish();
@ -318,7 +312,7 @@ public class DanaRHistoryActivity extends Activity {
holder.alarm.setVisibility(View.GONE);
break;
case RecordTypes.RECORD_TYPE_GLUCOSE:
holder.value.setText(NSProfile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profile.getUnits()));
holder.value.setText(Profile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profile.getUnits()));
// rest is the same
case RecordTypes.RECORD_TYPE_CARBO:
case RecordTypes.RECORD_TYPE_BASALHOUR:

View file

@ -56,6 +56,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
@ -167,18 +168,15 @@ public class DanaRStatsActivity extends Activity {
decimalFormat = new DecimalFormat("0.000");
llm = new LinearLayoutManager(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
TBB = preferences.getString("TBB", "10.00");
TBB = SP.getString("TBB", "10.00");
totalBaseBasal.setText(TBB);
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile();
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfileInterface();
if (pi != null && pi instanceof CircadianPercentageProfilePlugin) {
double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum();
totalBaseBasal.setText(decimalFormat.format(cppTBB));
SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit();
TBB = preferences.getString("TBB", "");
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
}
// stats table
@ -326,10 +324,8 @@ public class DanaRStatsActivity extends Activity {
if (hasFocus) {
totalBaseBasal.getText().clear();
} else {
SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit();
TBB = preferences.getString("TBB", "");
SP.putString("TBB", totalBaseBasal.getText().toString());
TBB = SP.getString("TBB", "");
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(totalBaseBasal.getWindowToken(), 0);

View file

@ -113,13 +113,13 @@ public class MsgHistoryEvents_v2 extends MessageBase {
log.debug("EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
detailedBolusInfo.date = datetime.getTime();
detailedBolusInfo.insulin = param1 / 100d;
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
break;
case DanaRPump.DUALBOLUS:
log.debug("EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
detailedBolusInfo.date = datetime.getTime();
detailedBolusInfo.insulin = param1 / 100d;
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
break;
case DanaRPump.DUALEXTENDEDSTART:
log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
@ -153,7 +153,7 @@ public class MsgHistoryEvents_v2 extends MessageBase {
log.debug("EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g");
detailedBolusInfo.date = datetime.getTime();
detailedBolusInfo.carbs = param1;
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
break;
default:
log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2);

View file

@ -18,7 +18,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
@ -33,7 +32,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
@ -45,7 +44,6 @@ import info.nightscout.androidaps.plugins.PumpDanaRv2.SerialIOThread;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgHistoryEvents_v2;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgSetAPSTempBasalStart_v2;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgSetHistoryEntry_v2;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgStatusAPS_v2;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgCheckValue_v2;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgStatusBolusExtended_v2;
import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgStatusTempBasal_v2;
@ -519,7 +517,7 @@ public class DanaRv2ExecutionService extends Service {
return true;
}
public boolean updateBasalsInPump(final NSProfile profile) {
public boolean updateBasalsInPump(final Profile profile) {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
@ -534,7 +532,7 @@ public class DanaRv2ExecutionService extends Service {
return true;
}
private double[] buildDanaRProfileRecord(NSProfile nsProfile) {
private double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
double value = Math.round(100d * nsProfile.getBasal(hour * 60 * 60))/100d + 0.00001;

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps.plugins.PumpMDI;
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@ -15,12 +13,10 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.InsulinInterface;
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.data.Profile;
import info.nightscout.utils.DateUtil;
/**
@ -121,13 +117,13 @@ public class MDIPlugin implements PluginBase, PumpInterface {
}
@Override
public int setNewBasalProfile(NSProfile profile) {
public int setNewBasalProfile(Profile profile) {
// Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile();
return SUCCESS;
}
@Override
public boolean isThisProfileSet(NSProfile profile) {
public boolean isThisProfileSet(Profile profile) {
return false;
}
@ -153,7 +149,7 @@ public class MDIPlugin implements PluginBase, PumpInterface {
result.bolusDelivered = detailedBolusInfo.insulin;
result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
return result;
}
@ -220,7 +216,7 @@ public class MDIPlugin implements PluginBase, PumpInterface {
status.put("status", "normal");
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getActiveProfile().getProfile().getActiveProfile());
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
status.put("timestamp", DateUtil.toISOString(new Date()));

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.PumpVirtual;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
@ -19,15 +18,13 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
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;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
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.utils.DateUtil;
import info.nightscout.utils.NSUpload;
@ -157,14 +154,14 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
}
@Override
public int setNewBasalProfile(NSProfile profile) {
public int setNewBasalProfile(Profile profile) {
// Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile();
lastDataTime = new Date();
return SUCCESS;
}
@Override
public boolean isThisProfileSet(NSProfile profile) {
public boolean isThisProfileSet(Profile profile) {
return false;
}
@ -181,10 +178,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
@Override
public double getBaseBasalRate() {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
if (profile == null)
return defaultBasalValue;
return profile.getBasal(profile.secondsFromMidnight());
return MainApp.getConfigBuilder().getProfile().getBasal();
}
@Override
@ -224,7 +218,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = new Date();
MainApp.getConfigBuilder().addTreatmentToHistory(detailedBolusInfo);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
return result;
}
@ -361,8 +355,9 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
status.put("status", "normal");
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getActiveProfile().getProfile().getActiveProfile());
} catch (Exception e) {}
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime());
if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(new Date().getTime()));
@ -383,6 +378,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
pump.put("reservoir", reservoirInUnits);
pump.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) {
e.printStackTrace();
}
return pump;
}

View file

@ -32,10 +32,10 @@ import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
@ -237,13 +237,7 @@ public class SmsCommunicatorPlugin implements PluginBase {
BgReading actualBG = DatabaseHelper.actualBg();
BgReading lastBG = DatabaseHelper.lastBg();
if (ConfigBuilderPlugin.getActiveProfile() == null || ConfigBuilderPlugin.getActiveProfile().getProfile() == null) {
reply = MainApp.sResources.getString(R.string.noprofile);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date()));
return;
}
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
String units = profile.getUnits();
if (actualBG != null) {
@ -255,7 +249,7 @@ public class SmsCommunicatorPlugin implements PluginBase {
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null)
reply += MainApp.sResources.getString(R.string.sms_delta) + " " + NSProfile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", ";
reply += MainApp.sResources.getString(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", ";
MainApp.getConfigBuilder().updateTotalIOBTreatments();
IobTotal bolusIob = MainApp.getConfigBuilder().getLastCalculationTreatments().round();

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.SourceNSClient;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
@ -35,7 +36,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface {
@Override
public boolean isEnabled(int type) {
return type == BGSOURCE && fragmentEnabled;
return Config.NSCLIENT || type == BGSOURCE && fragmentEnabled;
}
@Override
@ -55,7 +56,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface {
@Override
public boolean showInList(int type) {
return true;
return !Config.NSCLIENT;
}
@Override

View file

@ -16,6 +16,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsBolusFragment;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsExtendedBolusesFragment;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsProfileSwitchFragment;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsTempTargetFragment;
import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsTemporaryBasalsFragment;
@ -28,11 +29,11 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener
return treatmentsPlugin;
}
Context context;
TextView treatmentsTab;
TextView extendedBolusesTab;
TextView tempBasalsTab;
TextView tempTargetTab;
TextView profileSwitchTab;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
@ -43,11 +44,12 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener
extendedBolusesTab = (TextView) view.findViewById(R.id.treatments_extendedboluses);
tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals);
tempTargetTab = (TextView) view.findViewById(R.id.treatments_temptargets);
profileSwitchTab = (TextView) view.findViewById(R.id.treatments_profileswitches);
treatmentsTab.setOnClickListener(this);
extendedBolusesTab.setOnClickListener(this);
tempBasalsTab.setOnClickListener(this);
tempTargetTab.setOnClickListener(this);
context = getContext();
profileSwitchTab.setOnClickListener(this);
setFragment(new TreatmentsBolusFragment());
setBackgroundColorOnSelected(treatmentsTab);
@ -75,6 +77,10 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener
setFragment(new TreatmentsTempTargetFragment());
setBackgroundColorOnSelected(tempTargetTab);
break;
case R.id.treatments_profileswitches:
setFragment(new TreatmentsProfileSwitchFragment());
setBackgroundColorOnSelected(profileSwitchTab);
break;
}
}
@ -91,6 +97,7 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener
extendedBolusesTab.setBackgroundColor(MainApp.sResources.getColor(R.color.defaultbackground));
tempBasalsTab.setBackgroundColor(MainApp.sResources.getColor(R.color.defaultbackground));
tempTargetTab.setBackgroundColor(MainApp.sResources.getColor(R.color.defaultbackground));
profileSwitchTab.setBackgroundColor(MainApp.sResources.getColor(R.color.defaultbackground));
selected.setBackgroundColor(MainApp.sResources.getColor(R.color.tabBgColorSelected));
}
}

View file

@ -11,6 +11,7 @@ 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;
@ -18,21 +19,23 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempTargetChange;
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.OverlappingIntervals;
import info.nightscout.utils.SP;
/**
@ -48,6 +51,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
private static OverlappingIntervals<TemporaryBasal> tempBasals = new OverlappingIntervals<>();
private static OverlappingIntervals<ExtendedBolus> extendedBoluses = new OverlappingIntervals<>();
private static OverlappingIntervals<TempTarget> tempTargets = new OverlappingIntervals<>();
private static ProfileIntervals<ProfileSwitch> profiles = new ProfileIntervals<>();
private static boolean fragmentEnabled = true;
private static boolean fragmentVisible = true;
@ -95,7 +99,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
@Override
public boolean showInList(int type) {
return true;
return !Config.NSCLIENT;
}
@Override
@ -119,13 +123,12 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
initializeTreatmentData();
initializeExtendedBolusData();
initializeTempTargetData();
initializeProfileSwitchData();
}
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();
double dia = MainApp.getConfigBuilder() == null ? Constants.defaultDIA : MainApp.getConfigBuilder().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
treatments = MainApp.getDbHelper().getTreatmentDataFromTime(fromMills, false);
@ -133,9 +136,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
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();
double dia = MainApp.getConfigBuilder() == null ? Constants.defaultDIA : MainApp.getConfigBuilder().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
tempBasals.reset().add(MainApp.getDbHelper().getTemporaryBasalsDataFromTime(fromMills, false));
@ -144,9 +145,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
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();
double dia = MainApp.getConfigBuilder() == null ? Constants.defaultDIA : MainApp.getConfigBuilder().getProfile().getDia();
long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia));
extendedBoluses.reset().add(MainApp.getDbHelper().getExtendedBolusDataFromTime(fromMills, false));
@ -158,6 +157,10 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
tempTargets.reset().add(MainApp.getDbHelper().getTemptargetsDataFromTime(fromMills, false));
}
public void initializeProfileSwitchData() {
profiles.reset().add(MainApp.getDbHelper().getProfileSwitchData(false));
}
@Override
public IobTotal getLastCalculationTreatments() {
return lastTreatmentCalculation;
@ -167,9 +170,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
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();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null)
return total;
@ -206,7 +207,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
public MealData getMealData() {
MealData result = new MealData();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return result;
long now = new Date().getTime();
@ -404,7 +405,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
}
@Override
public void addTreatmentToHistory(DetailedBolusInfo detailedBolusInfo) {
public void addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo) {
Treatment treatment = new Treatment(detailedBolusInfo.insulinInterface);
treatment.date = detailedBolusInfo.date;
treatment.insulin = detailedBolusInfo.insulin;
@ -425,7 +426,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
}
@Override
public long oldestDataAvaialable() {
public long oldestDataAvailable() {
long oldestTime = new Date().getTime();
if (tempBasals.size() > 0)
oldestTime = Math.min(oldestTime, tempBasals.get(0).date);
@ -454,5 +455,27 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
return tempTargets;
}
// Profile Switch
@Subscribe
public void onStatusEvent(final EventProfileSwitchChange ev) {
initializeProfileSwitchData();
}
@Override
public ProfileSwitch getProfileSwitchFromHistory(long time) {
return (ProfileSwitch) profiles.getValueToTime(time);
}
@Override
public ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory() {
return profiles;
}
@Override
public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) {
log.debug("Adding new TemporaryBasal record" + profileSwitch.log());
MainApp.getDbHelper().createOrUpdate(profileSwitch);
}
}

View file

@ -35,8 +35,7 @@ import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@ -71,9 +70,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
@Override
public void onBindViewHolder(TreatmentsViewHolder holder, int position) {
if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet
return;
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null)
return;
holder.date.setText(DateUtil.dateAndTimeString(treatments.get(position).date));
@ -186,7 +183,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
case R.id.treatments_reshreshfromnightscout:
AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
builder.setTitle(this.getContext().getString(R.string.confirmation));
builder.setMessage(this.getContext().getString(R.string.refreshtreatmentsfromnightscout));
builder.setMessage(this.getContext().getString(R.string.refresheventsfromnightscout) + "?");
builder.setPositiveButton(this.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainApp.getDbHelper().resetTreatments();
@ -225,10 +222,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis
public void updateGUI() {
Activity activity = getActivity();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null)
return;
if (activity != null && recyclerView != null)
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {

View file

@ -34,7 +34,7 @@ import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OverlappingIntervals;
import info.nightscout.androidaps.data.OverlappingIntervals;
public class TreatmentsExtendedBolusesFragment extends Fragment {

View file

@ -0,0 +1,203 @@
package info.nightscout.androidaps.plugins.Treatments.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OKDialog;
import info.nightscout.utils.SP;
/**
* Created by mike on 13/01/17.
*/
public class TreatmentsProfileSwitchFragment extends Fragment implements View.OnClickListener {
RecyclerView recyclerView;
LinearLayoutManager llm;
Button refreshFromNS;
Context context;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ProfileSwitchViewHolder> {
ProfileIntervals<ProfileSwitch> profileSwitchList;
RecyclerViewAdapter(ProfileIntervals<ProfileSwitch> profileSwitchList) {
this.profileSwitchList = profileSwitchList;
}
@Override
public ProfileSwitchViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.treatments_profileswitch_item, viewGroup, false);
ProfileSwitchViewHolder ProfileSwitchViewHolder = new ProfileSwitchViewHolder(v);
return ProfileSwitchViewHolder;
}
@Override
public void onBindViewHolder(ProfileSwitchViewHolder holder, int position) {
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return;
ProfileSwitch profileSwitch = profileSwitchList.getReversed(position);
holder.date.setText(DateUtil.dateAndTimeString(profileSwitch.date));
if (!profileSwitch.isEndingEvent()) {
holder.duration.setText(DecimalFormatter.to0Decimal(profileSwitch.durationInMinutes) + " min");
} else {
holder.duration.setText("");
}
holder.name.setText(profileSwitch.profileName);
if (profileSwitch.isInProgress())
holder.date.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive));
else
holder.date.setTextColor(holder.duration.getCurrentTextColor());
holder.remove.setTag(profileSwitch);
}
@Override
public int getItemCount() {
return profileSwitchList.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public class ProfileSwitchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView date;
TextView duration;
TextView name;
TextView remove;
ProfileSwitchViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.profileswitch_cardview);
date = (TextView) itemView.findViewById(R.id.profileswitch_date);
duration = (TextView) itemView.findViewById(R.id.profileswitch_duration);
name = (TextView) itemView.findViewById(R.id.profileswitch_name);
remove = (TextView) itemView.findViewById(R.id.profileswitch_remove);
remove.setOnClickListener(this);
remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
}
@Override
public void onClick(View v) {
final ProfileSwitch profileSwitch = (ProfileSwitch) v.getTag();
switch (v.getId()) {
case R.id.profileswitch_remove:
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.confirmation), MainApp.sResources.getString(R.string.removerecord) + "\n" + DateUtil.dateAndTimeString(profileSwitch.date), new Runnable() {
@Override
public void run() {
final String _id = profileSwitch._id;
if (_id != null && !_id.equals("")) {
NSUpload.removeCareportalEntryFromNS(_id);
}
MainApp.getDbHelper().delete(profileSwitch);
}
});
break;
}
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.treatments_profileswitch_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.profileswitch_recyclerview);
recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getConfigBuilder().getProfileSwitchesFromHistory());
recyclerView.setAdapter(adapter);
refreshFromNS = (Button) view.findViewById(R.id.profileswitch_refreshfromnightscout);
refreshFromNS.setOnClickListener(this);
context = getContext();
boolean nsUploadOnly = SP.getBoolean(R.string.key_ns_upload_only, false);
if (nsUploadOnly)
refreshFromNS.setVisibility(View.GONE);
updateGUI();
return view;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.profileswitch_refreshfromnightscout:
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.confirmation), MainApp.sResources.getString(R.string.refresheventsfromnightscout) + "?", new Runnable() {
@Override
public void run() {
MainApp.getDbHelper().resetProfileSwitch();
Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
}
});
break;
}
}
@Override
public void onPause() {
super.onPause();
MainApp.bus().unregister(this);
}
@Override
public void onResume() {
super.onResume();
MainApp.bus().register(this);
}
@Subscribe
public void onStatusEvent(final EventProfileSwitchChange ev) {
updateGUI();
}
void updateGUI() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getConfigBuilder().getProfileSwitchesFromHistory()), false);
}
});
}
}

View file

@ -25,12 +25,11 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OverlappingIntervals;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.utils.SP;
/**
@ -62,11 +61,11 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli
@Override
public void onBindViewHolder(TempTargetsViewHolder holder, int position) {
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return;
TempTarget tempTarget = tempTargetList.getReversed(position);
if (!tempTarget.isEndingEvent()) {
holder.date.setText(DateUtil.dateAndTimeString(tempTarget.date) + " - " + DateUtil.timeString(tempTargetList.get(position).originalEnd()));
holder.date.setText(DateUtil.dateAndTimeString(tempTarget.date) + " - " + DateUtil.timeString(tempTarget.originalEnd()));
holder.duration.setText(DecimalFormatter.to0Decimal(tempTarget.durationInMinutes) + " min");
holder.low.setText(tempTarget.lowValueToUnitsToString(profile.getUnits()));
holder.high.setText(tempTarget.highValueToUnitsToString(profile.getUnits()));
@ -181,7 +180,7 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli
case R.id.temptargetrange_refreshfromnightscout:
AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
builder.setTitle(this.getContext().getString(R.string.confirmation));
builder.setMessage(this.getContext().getString(R.string.refreshtemptargetsfromnightscout));
builder.setMessage(this.getContext().getString(R.string.refresheventsfromnightscout) + " ?");
builder.setPositiveButton(this.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainApp.getDbHelper().resetTempTargets();

View file

@ -34,7 +34,7 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OverlappingIntervals;
import info.nightscout.androidaps.data.OverlappingIntervals;
public class TreatmentsTemporaryBasalsFragment extends Fragment {
@ -74,6 +74,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment {
holder.netInsulin.setText("");
holder.netRatio.setText("");
holder.extendedFlag.setVisibility(View.GONE);
holder.iob.setTextColor(holder.netRatio.getCurrentTextColor());
} else {
if (tempBasal.isInProgress()) {
holder.date.setText(DateUtil.dateAndTimeString(tempBasal.date));

View file

@ -21,7 +21,7 @@ import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@ -110,7 +110,7 @@ public class ActionStringHandler {
///////////////////////////////////////////////////////// TEMPTARGET
boolean isMGDL = Boolean.parseBoolean(act[1]);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
sendError("No profile found!");
return;
@ -174,7 +174,7 @@ public class ActionStringHandler {
boolean useBolusIOB = Boolean.parseBoolean(act[3]);
boolean useBasalIOB = Boolean.parseBoolean(act[4]);
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
sendError("No profile found!");
return;
@ -187,7 +187,7 @@ public class ActionStringHandler {
}
DecimalFormat format = new DecimalFormat("0.00");
BolusWizard bolusWizard = new BolusWizard();
bolusWizard.doCalc(profile.getDefaultProfile(), carbsAfterConstraints, 0d, useBG ? bgReading.valueToUnits(profile.getUnits()) : 0d, 0d, useBolusIOB, useBasalIOB, false, false);
bolusWizard.doCalc(profile, carbsAfterConstraints, 0d, useBG ? bgReading.valueToUnits(profile.getUnits()) : 0d, 0d, useBolusIOB, useBasalIOB, false, false);
Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(bolusWizard.calculatedTotalInsulin);
if (insulinAfterConstraints - bolusWizard.calculatedTotalInsulin != 0) {
@ -197,7 +197,6 @@ public class ActionStringHandler {
}
double insulin = bolusWizard.calculatedTotalInsulin;
if (bolusWizard.calculatedTotalInsulin < 0) {
bolusWizard.calculatedTotalInsulin = 0d;
}
@ -270,7 +269,7 @@ public class ActionStringHandler {
if (!Config.APS) {
return "Targets only apply in APS mode!";
}
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
return "No profile set :(";
}
@ -278,7 +277,7 @@ public class ActionStringHandler {
//Check for Temp-Target:
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
if (tempTarget != null) {
ret += "Temp Target: " + NSProfile.toUnitsString(tempTarget.low, NSProfile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + NSProfile.toUnitsString(tempTarget.high, NSProfile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits());
ret += "Temp Target: " + Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + Profile.toUnitsString(tempTarget.high, Profile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits());
ret += "\nuntil: " + DateUtil.timeString(tempTarget.originalEnd());
ret += "\n\n";
}

View file

@ -35,7 +35,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
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.data.Profile;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
@ -209,7 +209,7 @@ public class WatchUpdaterService extends WearableListenerService implements
}
private DataMap dataMapSingleBG(BgReading lastBG, GlucoseStatus glucoseStatus) {
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return null;
Double lowLine = SafeParse.stringToDouble(mPrefs.getString("low_mark", "0"));
@ -339,7 +339,7 @@ public class WatchUpdaterService extends WearableListenerService implements
ArrayList<DataMap> temps = new ArrayList<>();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
return;
@ -348,7 +348,7 @@ public class WatchUpdaterService extends WearableListenerService implements
long beginBasalSegmentTime = startTimeWindow;
long runningTime = startTimeWindow;
double beginBasalValue = profile.getBasal(NSProfile.secondsFromMidnight(new Date(beginBasalSegmentTime)));
double beginBasalValue = profile.getBasal(beginBasalSegmentTime);
double endBasalValue = beginBasalValue;
TemporaryBasal tb1 = MainApp.getConfigBuilder().getTempBasalFromHistory(runningTime);
@ -367,7 +367,7 @@ public class WatchUpdaterService extends WearableListenerService implements
for (; runningTime < now; runningTime += 5 * 60 * 1000) {
//basal rate
endBasalValue = profile.getBasal(NSProfile.secondsFromMidnight(new Date(runningTime)));
endBasalValue = profile.getBasal(runningTime);
if (endBasalValue != beginBasalValue) {
//push the segment we recently left
basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue));
@ -561,12 +561,12 @@ public class WatchUpdaterService extends WearableListenerService implements
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "|"
+ 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) {
Profile profile = MainApp.getConfigBuilder().getProfile();
if (!mPrefs.getBoolean("wear_showbgi", false)) {
return status;
}
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(NSProfile.secondsFromMidnight());
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf();
status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi);

View file

@ -11,6 +11,7 @@ import com.squareup.otto.Subscribe;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
@ -24,7 +25,7 @@ import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
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.data.Profile;
import info.nightscout.utils.DecimalFormatter;
/**
@ -98,7 +99,7 @@ public class StatuslinePlugin implements PluginBase {
@Override
public boolean showInList(int type) {
return true;
return !Config.NSCLIENT;
}
@Override
@ -186,12 +187,12 @@ public class StatuslinePlugin implements PluginBase {
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "|"
+ 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) {
Profile profile = MainApp.getConfigBuilder().getProfile();
if (!mPrefs.getBoolean("xdripstatus_showbgi", false)) {
return status;
}
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(NSProfile.secondsFromMidnight());
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf();
status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi);

View file

@ -21,7 +21,7 @@ import java.util.Date;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
public class KeepAliveReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class);
@ -34,15 +34,15 @@ public class KeepAliveReceiver extends BroadcastReceiver {
final PumpInterface pump = MainApp.getConfigBuilder();
final NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (pump != null && profile != null && profile.getBasal(NSProfile.secondsFromMidnight()) != null) {
final Profile profile = MainApp.getConfigBuilder().getProfile();
if (pump != null && profile != null && profile.getBasal() != null) {
boolean isBasalOutdated = false;
boolean isStatusOutdated = false;
Date lastConnection = pump.lastDataTime();
if (lastConnection.getTime() + 30 * 60 * 1000L < new Date().getTime())
isStatusOutdated = true;
if (Math.abs(profile.getBasal(NSProfile.secondsFromMidnight()) - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep)
if (Math.abs(profile.getBasal() - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep)
isBasalOutdated = true;
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());

View file

@ -1,15 +1,12 @@
package info.nightscout.utils;
import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
/**
* Created by mike on 11.10.2016.
@ -17,7 +14,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
public class BolusWizard {
// Inputs
JSONObject specificProfile = null;
Profile specificProfile = null;
public Integer carbs = 0;
Double bg = 0d;
Double correction;
@ -52,7 +49,7 @@ public class BolusWizard {
public Double calculatedTotalInsulin = 0d;
public Double carbsEquivalent = 0d;
public Double doCalc(JSONObject specificProfile, Integer carbs, Double cob, Double bg, Double correction, Boolean includeBolusIOB, Boolean includeBasalIOB, Boolean superBolus, Boolean trend) {
public Double doCalc(Profile specificProfile, Integer carbs, Double cob, Double bg, Double correction, Boolean includeBolusIOB, Boolean includeBasalIOB, Boolean superBolus, Boolean trend) {
this.specificProfile = specificProfile;
this.carbs = carbs;
this.bg = bg;
@ -60,12 +57,11 @@ public class BolusWizard {
this.superBolus = superBolus;
this.trend = trend;
NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
// Insulin from BG
sens = profile.getIsf(specificProfile, NSProfile.secondsFromMidnight());
targetBGLow = profile.getTargetLow(specificProfile, NSProfile.secondsFromMidnight());
targetBGHigh = profile.getTargetHigh(specificProfile, NSProfile.secondsFromMidnight());
sens = specificProfile.getIsf();
targetBGLow = specificProfile.getTargetLow();
targetBGHigh = specificProfile.getTargetHigh();
if (bg <= targetBGLow) {
bgDiff = bg - targetBGLow;
} else {
@ -76,11 +72,11 @@ public class BolusWizard {
// Insulin from 15 min trend
glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null && trend) {
insulinFromTrend = (NSProfile.fromMgdlToUnits(glucoseStatus.short_avgdelta, profile.getUnits()) * 3) / sens;
insulinFromTrend = (Profile.fromMgdlToUnits(glucoseStatus.short_avgdelta, specificProfile.getUnits()) * 3) / sens;
}
// Insuling from carbs
ic = profile.getIc(specificProfile, NSProfile.secondsFromMidnight());
ic = specificProfile.getIc();
insulinFromCarbs = carbs / ic;
insulinFromCOB = cob / ic;
@ -100,10 +96,10 @@ public class BolusWizard {
// Insulin from superbolus for 2h. Get basal rate now and after 1h
if (superBolus) {
insulinFromSuperBolus = profile.getBasal(NSProfile.secondsFromMidnight());
insulinFromSuperBolus = specificProfile.getBasal();
long timeAfter1h = new Date().getTime();
timeAfter1h += 60L * 60 * 1000;
insulinFromSuperBolus += profile.getBasal(NSProfile.secondsFromMidnight(new Date(timeAfter1h)));
insulinFromSuperBolus += specificProfile.getBasal(Profile.secondsFromMidnight(new Date(timeAfter1h)));
}
// Total

View file

@ -19,13 +19,14 @@ import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA;
import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResultMA;
@ -69,9 +70,9 @@ public class NSUpload {
if (useAbsolute) {
TemporaryBasal t = temporaryBasal.clone();
t.isAbsolute = true;
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile != null) {
t.absoluteRate = profile.getBasal(NSProfile.secondsFromMidnight(temporaryBasal.date)) * temporaryBasal.percentRate / 100d;
t.absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d;
uploadTempBasalStartAbsolute(t, null);
}
} else {
@ -274,6 +275,27 @@ public class NSUpload {
uploadCareportalEntryToNS(data);
}
public static void uploadProfileSwitch(ProfileSwitch profileSwitch) {
try {
JSONObject data = new JSONObject();
data.put("eventType", CareportalEvent.PROFILESWITCH);
data.put("duration", profileSwitch.durationInMinutes);
data.put("profile", profileSwitch.profileName);
data.put("profileJson", profileSwitch.profileJson);
data.put("profilePlugin", profileSwitch.profilePlugin);
if (profileSwitch.isCPP) {
data.put("CircadianPercentageProfile", true);
data.put("timeshift", profileSwitch.timeshift);
data.put("percentage", profileSwitch.percentage);
}
data.put("created_at", DateUtil.toISOString(profileSwitch.date));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
uploadCareportalEntryToNS(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void uploadCareportalEntryToNS(JSONObject data) {
try {
if (data.has("preBolus") && data.has("carbs")) {

View file

@ -98,6 +98,12 @@ public class SP {
editor.apply();
}
static public void putString(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
static public void removeString(int resourceID) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(MainApp.sResources.getString(resourceID));

View file

@ -17,7 +17,7 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.data.Profile;
/**
* Created by mike on 10.02.2017.
@ -44,7 +44,7 @@ public class XdripCalibrations {
}
public static boolean sendIntent(Double bg) {
final NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
final Profile profile = MainApp.getConfigBuilder().getProfile();
Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle();

View file

@ -17,7 +17,6 @@
<include
layout="@layout/careportal_stats_fragment"
layout_width="match_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

View file

@ -15,7 +15,6 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
@ -148,6 +147,51 @@
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:paddingRight="5dp"
android:text="@string/careportal_pbage_label"
android:textSize="14sp" />
<TextView
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingEnd="2dp"
android:paddingStart="2dp"
android:text=":"
android:textSize="14sp" />
<TextView
android:id="@+id/careportal_pbage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start"
android:paddingLeft="5dp"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
</LinearLayout>
</FrameLayout>

View file

@ -43,6 +43,7 @@
<TextView
android:id="@+id/configbuilder_bgsourcelabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
@ -113,6 +114,7 @@
android:background="@color/cardColorBackground" />
<TextView
android:id="@+id/configbuilder_profilelabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
@ -129,6 +131,7 @@
android:background="@color/cardColorBackground" />
<TextView
android:id="@+id/configbuilder_treatmentslabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"

View file

@ -17,11 +17,12 @@
android:id="@+id/profileview_noprofile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/noprofileset"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@android:color/holo_red_light"
android:textStyle="bold"
android:gravity="center_horizontal" />
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"

View file

@ -0,0 +1,626 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.nightscout.androidaps.plugins.Overview.OverviewFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/overview_buttons"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/overview_notifications"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:id="@+id/overview_looplayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="2dp">
<TextView
android:id="@+id/overview_apsmode"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:text="Open Loop"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/overview_activeprofile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:text="Profile"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/overview_temptarget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:text="TempTarget"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/mdtp_white" />
</LinearLayout>
<LinearLayout
android:id="@+id/overview_pumpstatuslayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="2dp">
<TextView
android:id="@+id/overview_pumpstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:gravity="center_vertical|center_horizontal"
android:text="@string/initializing"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<TextView
android:id="@+id/overview_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:gravity="center_vertical"
android:text="00.0"
android:textSize="90dp"
android:textStyle="bold" />
<TextView
android:id="@+id/overview_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:layout_marginTop="-15dp"
android:gravity="center_vertical"
android:paddingLeft="-5dp"
android:paddingRight="-5dp"
android:text="→"
android:textSize="90dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_marginTop="10dp"
android:layout_weight="0.5"
android:gravity="top|center_horizontal"
android:orientation="vertical">
<TextView
android:id="@+id/overview_timeago"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="0.5"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/overview_delta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:layout_weight="0.5"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/overview_avgdelta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
<TextView
android:id="@+id/overview_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:gravity="center_vertical"
android:text="8:00 PM"
android:textAlignment="viewEnd"
android:textSize="90dp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:paddingRight="5dp"
android:text="@string/basal"
android:textSize="14sp" />
<TextView
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingEnd="2dp"
android:paddingStart="2dp"
android:text=":"
android:textSize="14sp" />
<TextView
android:id="@+id/overview_basebasal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="start"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:text="0.50U/h @17:35 1/30min - 0.40U/h"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:paddingRight="5dp"
android:text="@string/virtualpump_extendedbolus_label"
android:textSize="14sp" />
<TextView
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingEnd="2dp"
android:paddingStart="2dp"
android:text=":"
android:textSize="14sp" />
<TextView
android:id="@+id/overview_extendedbolus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="start"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:text="0.50U/h @17:35 1/30min"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:paddingRight="5dp"
android:text="@string/iob"
android:textSize="14sp" />
<TextView
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingEnd="2dp"
android:paddingStart="2dp"
android:text=":"
android:textSize="14sp" />
<TextView
android:id="@+id/overview_iob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="start"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:text="0.50U/h @17:35 1/30min - 0.40U/h"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:paddingRight="5dp"
android:text="@string/cob"
android:textSize="14sp" />
<TextView
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingEnd="2dp"
android:paddingStart="2dp"
android:text=":"
android:textSize="14sp" />
<TextView
android:id="@+id/overview_cob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="start"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:text="23 g"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginBottom="5dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:background="@color/listdelimiter" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<include
layout="@layout/careportal_stats_fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:paddingTop="5dp">
<TextView
android:id="@+id/overview_showprediction_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/predictionshortlabel"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/prediction"
android:textStyle="bold" />
<CheckBox
android:id="@+id/overview_showprediction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
android:layout_marginTop="-9dp"
app:buttonTint="@color/prediction" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/basalshortlabel"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/basal"
android:textStyle="bold" />
<CheckBox
android:id="@+id/overview_showbasals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
android:layout_marginTop="-9dp"
app:buttonTint="@color/basal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/iob"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/iob"
android:textStyle="bold" />
<CheckBox
android:id="@+id/overview_showiob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
android:layout_marginTop="-9dp"
app:buttonTint="@color/iob" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/cob"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/cob"
android:textStyle="bold" />
<CheckBox
android:id="@+id/overview_showcob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
android:layout_marginTop="-9dp"
app:buttonTint="@color/cob" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/dev"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/deviations"
android:textStyle="bold" />
<CheckBox
android:id="@+id/overview_showdeviations"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
android:layout_marginTop="-9dp"
app:buttonTint="@color/deviations" />
</LinearLayout>
<LinearLayout
android:id="@+id/overview_graphs_layout"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<com.jjoe64.graphview.GraphView
android:id="@+id/overview_bggraph"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1" />
<com.jjoe64.graphview.GraphView
android:id="@+id/overview_iobgraph"
android:layout_width="wrap_content"
android:layout_height="100dp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="@+id/overview_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<LinearLayout
android:id="@+id/overview_accepttemplayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/overview_accepttempbutton"
style="?android:attr/buttonStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_weight="0.5"
android:text="Accept new temp\n0.25U/h"
android:textColor="@color/colorAcceptTempButton" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/overview_treatmentbutton"
style="?android:attr/buttonStyle"
android:layout_width="0px"
android:layout_height="fill_parent"
android:layout_marginRight="-4dp"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_bolus"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:text="@string/overview_bolus_label"
android:textColor="@color/colorTreatmentButton"
android:textSize="10sp" />
<Button
android:id="@+id/overview_wizardbutton"
style="?android:attr/buttonStyle"
android:layout_width="0px"
android:layout_height="fill_parent"
android:layout_marginRight="-4dp"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_calculator"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:text="@string/overview_calculator_label"
android:textColor="@color/colorCalculatorButton"
android:textSize="10sp" />
<Button
android:id="@+id/overview_calibrationbutton"
style="?android:attr/buttonStyle"
android:layout_width="0px"
android:layout_height="fill_parent"
android:layout_marginRight="-4dp"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_calibration"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:text="@string/overview_calibration"
android:textColor="@color/colorCalibrationButton"
android:textSize="10sp" />
<Button
android:id="@+id/overview_quickwizardbutton"
style="?android:attr/buttonStyle"
android:layout_width="0px"
android:layout_height="fill_parent"
android:layout_marginRight="-4dp"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_quickwizard"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:text="Quick wizard"
android:textColor="@color/colorQuickWizardButton"
android:textSize="10sp" />
<Button
android:id="@+id/overview_canceltempbutton"
style="?android:attr/buttonStyle"
android:layout_width="0px"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:drawableTop="@drawable/icon_cancelbasal"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:text="Cancel temp basal"
android:textColor="@color/colorCancelTempButton"
android:textSize="10sp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</FrameLayout>

View file

@ -13,40 +13,49 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal">
<TextView
android:id="@+id/treatments_treatments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="30dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:text="@string/bolus" />
<TextView
android:id="@+id/treatments_extendedboluses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="30dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:text="@string/extendedbolus" />
<TextView
android:id="@+id/treatments_tempbasals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="30dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:text="@string/tempbasal" />
<TextView
android:id="@+id/treatments_temptargets"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="30dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:text="@string/temptarget" />
<TextView
android:id="@+id/treatments_profileswitches"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:text="@string/profileswitch" />
</LinearLayout>
<FrameLayout

View file

@ -0,0 +1,28 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsProfileSwitchFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/profileswitch_refreshfromnightscout"
style="?android:attr/buttonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/refresheventsfromnightscout" />
<android.support.v7.widget.RecyclerView
android:id="@+id/profileswitch_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</FrameLayout>

View file

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/profileswitch_cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardBackgroundColor="?android:colorBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="true"
android:orientation="horizontal">
<com.joanzapata.iconify.widget.IconTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical|right"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:text="{fa-clock-o}" />
<TextView
android:id="@+id/profileswitch_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" />
<TextView
android:id="@+id/profileswitch_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/profileswitch_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="5dp"
android:text="60 min"
android:textAlignment="viewEnd"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/profileswitch_remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:text="@string/overview_quickwizard_item_remove_button"
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

@ -15,7 +15,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/temptargetrange_refreshfromnightscout" />
android:text="@string/refresheventsfromnightscout" />
<android.support.v7.widget.RecyclerView
android:id="@+id/temptargetrange_recyclerview"

View file

@ -123,7 +123,6 @@
<string name="objectives_pumpstatusavailableinns">Статус на помпа в NS</string>
<string name="rate">Стойност</string>
<string name="reason">Основание</string>
<string name="refreshtreatmentsfromnightscout">Искате ли да обновите treatments от Nightscout</string>
<string name="safety">Безопасност</string>
<string name="setextendedbolusquestion">Задай нов удължен болусs:</string>
<string name="setbasalquestion">Приложи нов временен базал:</string>
@ -413,12 +412,10 @@
<string name="ongoingnotificaction">Текущи известия</string>
<string name="openapsma_scriptdebugdata_label">Script debug</string>
<string name="openapsma_valuelimitedto" formatted="false">%.2f ограничено до %.2f</string>
<string name="refreshtemptargetsfromnightscout">Искате ли да обновите временните цели от Найтскаут</string>
<string name="removerecord">Премахни запис:</string>
<string name="short_avgdelta">Краткоср. Δ:</string>
<string name="short_tabtitles">Къси имена</string>
<string name="smscommunicator_bolusdelivered" formatted="false">Bolus %.2fU delivered successfully</string>
<string name="temptargetrange_refreshfromnightscout">Обнови временни цели от NS</string>
<string name="danar_stats_expweight">Експоненциално претеглена TDD</string>
<string name="danar_stats_cumulative_tdd">Комулативна TDD</string>
<string name="danar_stats_weight">Тегло</string>

View file

@ -123,10 +123,9 @@
<string name="objectives_pumpstatusavailableinns">Stav pumpy dostupný v NS</string>
<string name="rate">Hodnota</string>
<string name="reason">Zdůvodnění</string>
<string name="refreshtreatmentsfromnightscout">Opravdu aktualizovat ošetření z NS</string>
<string name="safety">Bezpečnost</string>
<string name="danar_useextended_title">Použít kombo bolusy pro >200%</string>
<string name="setextendedbolusquestion">Spustit nový kombo bolus:</string>
<string name="danar_useextended_title">Použít prodloužený bolusy pro >200%</string>
<string name="setextendedbolusquestion">Spustit nový prodloužený bolus:</string>
<string name="setbasalquestion">Spustit nový dočasný bazál:</string>
<string name="simpleprofile">Jednoduchý profil</string>
<string name="tempbasals_iob_label_string">IOB:</string>
@ -158,14 +157,14 @@
<string name="virtualpump">Virtualní pumpa</string>
<string name="virtualpump_basebasalrate_label">Základní hodnota bazálu</string>
<string name="virtualpump_battery_label">Baterie</string>
<string name="virtualpump_extendedbolus_label">Kombo bolus</string>
<string name="virtualpump_extendedbolus_label">Prodloužený bolus</string>
<string name="virtualpump_reservoir_label">Zásobník</string>
<string name="virtualpump_resultok">OK</string>
<string name="virtualpump_sqlerror">Chyba databáze</string>
<string name="virtualpump_tempbasal_label">Dočasný bazál</string>
<string name="vitualpump_label">VIRTUÁLNÍ PUMPA</string>
<string name="xdrip">xDrip</string>
<string name="overview_extendedbolus_button">Kombo bolus</string>
<string name="overview_extendedbolus_button">Prodloužený bolus</string>
<string name="overview_tempbasal_button">Dočasný bazál</string>
<string name="nsprofileview_isf_label">Citlivost:</string>
<string name="nsclientnotinstalled">NSClient není nainstalován. Záznam je ztracen!</string>
@ -388,10 +387,9 @@
<string name="openapsma_autosensdata_label">Data detekce senzitivity</string>
<string name="openapsma_scriptdebugdata_label">Ladící informace</string>
<string name="openapsma_valuelimitedto" formatted="false">%.2f omezeno na %.2f</string>
<string name="refreshtemptargetsfromnightscout">Opravdu aktualizovat dočasné cíle z NS</string>
<string name="removerecord">Odstranit záznam:</string>
<string name="short_avgdelta">Krátkodobý průměr</string>
<string name="temptargetrange_refreshfromnightscout">Obnovit dočasné cíle z NS</string>
<string name="refresheventsfromnightscout">Obnovit události z NS</string>
<string name="actions_shortname">"AKCE"</string>
<string name="wear_shortname">"WEAR"</string>
<string name="virtualpump_shortname">VPUM</string>

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