From f267c85377a48fbe38c65e4d50bed126bd6d5219 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 2 Jun 2017 10:25:49 +0200 Subject: [PATCH 1/8] it compiles now with profiles --- .../androidaps/Services/DataService.java | 46 +- .../nightscout/androidaps/data/IobTotal.java | 3 - .../nightscout/androidaps/data/Profile.java | 347 ++++++++++++ .../androidaps/data/ProfileStore.java | 99 ++++ .../androidaps/data/PumpEnactResult.java | 3 +- .../androidaps/db/DatabaseHelper.java | 212 ++++++-- .../androidaps/db/ExtendedBolus.java | 5 +- .../androidaps/db/ProfileSwitch.java | 121 +++++ .../androidaps/db/TemporaryBasal.java | 21 +- .../nightscout/androidaps/db/Treatment.java | 10 +- .../events/EventNewBasalProfile.java | 9 - .../interfaces/ProfileInterface.java | 5 +- .../androidaps/interfaces/PumpInterface.java | 8 +- .../interfaces/TreatmentsInterface.java | 10 +- .../plugins/Actions/ActionsFragment.java | 3 +- .../Actions/dialogs/NewTempBasalDialog.java | 8 +- .../Careportal/CareportalFragment.java | 2 +- .../Dialogs/NewNSTreatmentDialog.java | 82 +-- .../ConfigBuilder/ConfigBuilderPlugin.java | 111 +++- .../ConstraintsSafety/SafetyPlugin.java | 16 +- .../InsulinFastactingPlugin.java | 9 +- .../InsulinFastactingProlongedPlugin.java | 11 +- .../IobCobCalculatorPlugin.java | 55 +- .../broadcasts/BroadcastProfile.java | 5 +- .../NSClientInternal/data/NSProfile.java | 494 ------------------ .../services/NSClientService.java | 38 +- .../DetermineBasalAdapterAMAJS.java | 12 +- .../plugins/OpenAPSAMA/OpenAPSAMAPlugin.java | 28 +- .../OpenAPSMA/DetermineBasalAdapterMAJS.java | 8 +- .../plugins/OpenAPSMA/OpenAPSMAPlugin.java | 28 +- .../Overview/Dialogs/CalibrationDialog.java | 9 +- .../Overview/Dialogs/WizardDialog.java | 22 +- .../plugins/Overview/Notification.java | 4 + .../plugins/Overview/OverviewFragment.java | 52 +- .../plugins/Overview/QuickWizard.java | 4 +- .../PersistentNotificationPlugin.java | 34 +- .../CircadianPercentageProfilePlugin.java | 18 +- .../ProfileLocal/LocalProfilePlugin.java | 15 +- .../plugins/ProfileNS/NSProfileFragment.java | 29 +- .../plugins/ProfileNS/NSProfilePlugin.java | 44 +- .../ProfileSimple/SimpleProfilePlugin.java | 13 +- .../plugins/PumpDanaR/DanaRPlugin.java | 19 +- .../plugins/PumpDanaR/DanaRPump.java | 11 +- .../PumpDanaR/Dialogs/ProfileViewDialog.java | 30 +- .../History/DanaRHistoryActivity.java | 14 +- .../PumpDanaR/History/DanaRNSHistorySync.java | 6 +- .../PumpDanaR/History/DanaRStatsActivity.java | 29 +- .../services/DanaRExecutionService.java | 7 +- .../PumpDanaRKorean/DanaRKoreanPlugin.java | 22 +- .../History/DanaRHistoryActivity.java | 14 +- .../History/DanaRStatsActivity.java | 27 +- .../services/DanaRKoreanExecutionService.java | 7 +- .../plugins/PumpDanaRv2/DanaRv2Plugin.java | 17 +- .../History/DanaRHistoryActivity.java | 14 +- .../History/DanaRStatsActivity.java | 18 +- .../PumpDanaRv2/comm/MsgHistoryEvents_v2.java | 6 +- .../services/DanaRv2ExecutionService.java | 8 +- .../androidaps/plugins/PumpMDI/MDIPlugin.java | 14 +- .../PumpVirtual/VirtualPumpPlugin.java | 24 +- .../SmsCommunicatorPlugin.java | 12 +- .../plugins/Treatments/TreatmentsPlugin.java | 44 +- .../fragments/TreatmentsBolusFragment.java | 12 +- .../TreatmentsTempTargetFragment.java | 5 +- .../plugins/Wear/ActionStringHandler.java | 13 +- .../wearintegration/WatchUpdaterService.java | 16 +- .../XDripStatusline/StatuslinePlugin.java | 8 +- .../receivers/KeepAliveReceiver.java | 8 +- .../info/nightscout/utils/BolusWizard.java | 24 +- .../java/info/nightscout/utils/NSUpload.java | 28 +- .../utils/OverlappingIntervals.java | 2 + .../nightscout/utils/ProfileIntervals.java | 106 ++++ .../main/java/info/nightscout/utils/SP.java | 6 + .../nightscout/utils/XdripCalibrations.java | 4 +- app/src/main/res/values/strings.xml | 5 + 74 files changed, 1476 insertions(+), 1157 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/data/Profile.java create mode 100644 app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java create mode 100644 app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java create mode 100644 app/src/main/java/info/nightscout/utils/ProfileIntervals.java diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java index b63f9026f7..cb0e1c6835 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -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); @@ -195,7 +190,7 @@ public class DataService extends IntentService { if (Config.logIncommingBG) log.debug(bundle.toString()); - log.debug("GLIMP BG " + bgReading.toString()); + log.debug("GLIMP BG " + bgReading.toString()); MainApp.getDbHelper().createIfNotExists(bgReading); } @@ -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) { @@ -516,8 +500,8 @@ public class DataService extends IntentService { public void handleAddChangeCareportalEventRecord(JSONObject trJson) throws JSONException { 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.INSULINCHANGE) || + trJson.getString("eventType").equals(CareportalEvent.SENSORCHANGE) )) { if (Config.logIncommingData) log.debug("Processing CareportalEvent record: " + trJson.toString()); @@ -525,6 +509,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; diff --git a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java index 1787f6b0d5..5c89a7bec7 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java +++ b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java new file mode 100644 index 0000000000..757b706da0 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -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 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); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java new file mode 100644 index 0000000000..613f257a86 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java @@ -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 (store.has("units")) + units = store.getString("units"); + profile = new Profile(store.getJSONObject(profileName), units); + } + } catch (JSONException e) { + e.printStackTrace(); + } + return profile; + } + + public ArrayList getProfileList() { + ArrayList ret = new ArrayList(); + + 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; + } + + +} diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index bd3529124b..bfddeff320 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -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 { diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index b9e45d4145..246e6f13d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -34,6 +34,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; +import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; @@ -41,7 +42,7 @@ 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.data.Profile; 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 getDaoTempTargets() throws SQLException { @@ -292,6 +316,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return getDao(CareportalEvent.class); } + private Dao 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 preparedQuery = queryBuilder.prepare(); List 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 getProfileSwitchDataFromTime(long mills, boolean ascending) { + try { + Dao daoProfileSwitch = getDaoProfileSwitch(); + List profileSwitches; + QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder(); + queryBuilder.orderBy("date", ascending); + Where where = queryBuilder.where(); + where.ge("date", mills); + PreparedQuery preparedQuery = queryBuilder.prepare(); + profileSwitches = daoProfileSwitch.query(preparedQuery); + return profileSwitches; + } catch (SQLException e) { + e.printStackTrace(); + } + return new ArrayList(); + } + + 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 EventNewBasalProfileChange"); + MainApp.bus().post(new EventNewBasalProfile()); + 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 queryBuilder = null; + queryBuilder = getDaoProfileSwitch().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List 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"); + 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 queryBuilder = getDaoProfileSwitch().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", _id); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List 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(); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java index 503ccace22..1cb2aea0ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java @@ -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) diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java new file mode 100644 index 0000000000..2d82c3e478 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -0,0 +1,121 @@ +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.Constants; +import info.nightscout.androidaps.interfaces.Interval; +import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; +import info.nightscout.utils.DateUtil; +import info.nightscout.utils.DecimalFormatter; + +@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES) +public class ProfileSwitch implements Interval { + 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 --------- + + public String log() { + return "ProfileSwitch{" + + "date=" + date + + "date=" + DateUtil.dateAndTimeString(date) + + ", isValid=" + isValid + + ", duration=" + durationInMinutes + + ", profileName=" + profileName + + ", percentage=" + percentage + + ", timeshift=" + timeshift + + '}'; + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java index 027f5c1e3e..45271cf753 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java @@ -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,13 +133,10 @@ 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); + int realDuration = getDurationToTime(time); Double netBasalAmount = 0d; if (realDuration > 0) { @@ -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; } } diff --git a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java index e44413de15..d6dfa9fede 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -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 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; } } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java index b3750f59c8..1309625b98 100644 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java @@ -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; - } } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java index 0924723776..64fffa3e57 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java @@ -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(); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java index 1e9fcc6e35..dbbdec2ce1 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index c0c58a1117..d210d07620 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -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.utils.ProfileIntervals; /** * Created by mike on 14.06.2016. @@ -49,11 +51,15 @@ public interface TreatmentsInterface { void addToHistoryExtendedBolusStop(long time); OverlappingIntervals getExtendedBolusesFromHistory(); - void addTreatmentToHistory(DetailedBolusInfo detailedBolusInfo); + void addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo); TempTarget getTempTargetFromHistory(long time); OverlappingIntervals getTempTargetsFromHistory(); - long oldestDataAvaialable(); + ProfileSwitch getProfileSwitchFromHistory(long time); + ProfileIntervals getProfileSwitchesFromHistory(); + void addToHistoryProfileSwitch(ProfileSwitch profileSwitch); + + long oldestDataAvailable(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java index 417b58d190..8b9549d956 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java @@ -129,7 +129,8 @@ 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()) + 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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java index 2a79ccef49..51effccb86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java index 3351ebdd72..557dad36cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java @@ -50,7 +50,7 @@ public class CareportalFragment extends Fragment implements View.OnClickListener 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 profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, true, 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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java index 2702f7ac96..29d6adeeee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java @@ -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,25 +228,19 @@ 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 profileList; units = Constants.MGDL; - if (profile == null) { - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), context.getString(R.string.noprofile)); - profileList = new ArrayList(); - } else { - units = profile.getUnits(); - profileList = profile.getProfileList(); - } + units = profile.getUnits(); + profileList = profileStore.getProfileList(); ArrayAdapter adapter = new ArrayAdapter(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())) - profileSpinner.setSelection(p); - } + // set selected to actual profile + for (int p = 0; p < profileList.size(); p++) { + if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName())) + profileSpinner.setSelection(p); } // temp target @@ -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(); @@ -642,7 +646,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } } else if (options.executeTempTarget) { try { - if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration")&& data.getInt("duration") == 0)) { + if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration") && data.getInt("duration") == 0)) { sHandler.post(new Runnable() { @Override public void run() { @@ -651,9 +655,9 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick tempTarget.date = eventTime.getTime(); 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()); + if (tempTarget.durationInMinutes != 0) { + 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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java index 2b5c82ce77..e97f8a77f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java @@ -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; @@ -24,11 +24,11 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; 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 +40,15 @@ 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.data.Profile; 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; +import info.nightscout.utils.ProfileIntervals; /** * 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(); @@ -851,6 +850,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain } @Override + @Nullable public TemporaryBasal getRealTempBasalFromHistory(long time) { return activeTreatments.getRealTempBasalFromHistory(time); } @@ -861,6 +861,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain } @Override + @Nullable public TemporaryBasal getTempBasalFromHistory(long time) { return activeTreatments.getTempBasalFromHistory(time); } @@ -902,6 +903,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain } @Override + @Nullable public ExtendedBolus getExtendedBolusFromHistory(long time) { return activeTreatments.getExtendedBolusFromHistory(time); } @@ -930,14 +932,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 +951,85 @@ 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 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) { + 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 + 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; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java index cdf7f554ee..213bba47fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java @@ -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"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java index 099285967a..c98295ad35 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java @@ -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 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java index b7e2bfdd0b..ed5fc0485c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java @@ -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 @@ -107,7 +100,7 @@ public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInte double peak = 75d * dia / 6.0; double tail = 180d * dia / 6.0; double end = 360d * dia / 6.0; - double Total = 2 * peak + (tail - peak) * 5 / 2 + (end - tail) / 2; + double Total = 2 * peak + (tail - peak) * 5 / 2 + (end - tail) / 2; if (treatment.insulin != 0d) { long bolusTime = treatment.date; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java index 1ad6c4121e..4a55b8ee0e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java @@ -24,10 +24,9 @@ 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.androidaps.data.Profile; import info.nightscout.utils.Round; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; @@ -154,7 +153,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()); } @@ -230,12 +229,7 @@ public class IobCobCalculatorPlugin implements PluginBase { public void calculateSensitivityData() { //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; - } + Profile profile = MainApp.getConfigBuilder().getProfile(); if (bucketed_data == null || bucketed_data.size() < 3) { log.debug("calculateSensitivityData: No bucketed data available"); @@ -257,8 +251,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 +282,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); } @@ -385,7 +378,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 +423,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 +433,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 +455,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 +475,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 +514,13 @@ 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) { - dia = profile.getDia(); - } - if (ev.newNSProfile == null) { // on init no need of reset + Profile profile = MainApp.getConfigBuilder().getProfile(); + dia = profile.getDia(); + 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<>(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java index a1d44d0340..641a4e6a77 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java deleted file mode 100644 index eb320ebfdb..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java +++ /dev/null @@ -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 getProfileList() { - ArrayList ret = new ArrayList(); - - 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); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java index bd62ce631f..e51b70a014 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java @@ -47,10 +47,10 @@ 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; +import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; @@ -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")); } @@ -481,7 +456,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")); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java index 75a839b659..044374bc86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java @@ -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); @@ -233,7 +233,7 @@ public class DetermineBasalAdapterAMAJS { // as we have non default temps longer than 30 mintues TemporaryBasal tempBasal = MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()); - if(tempBasal != null){ + if (tempBasal != null) { mCurrentTemp.add("minutesrunning", tempBasal.getRealDuration()); } @@ -245,7 +245,7 @@ public class DetermineBasalAdapterAMAJS { mGlucoseStatus = new V8Object(mV8rt); mGlucoseStatus.add("glucose", glucoseStatus.glucose); - if(SP.getBoolean("always_use_shortavg", false)){ + if (SP.getBoolean("always_use_shortavg", false)) { mGlucoseStatus.add("delta", glucoseStatus.short_avgdelta); } else { mGlucoseStatus.add("delta", glucoseStatus.delta); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java index d68ba9d5f8..c39e9a78d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java @@ -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()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java index 52ae7ae8c8..7df122fc92 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java @@ -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()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java index 26eb525b07..11ea2de109 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java index d13243e66a..d1b25fff3a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java @@ -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")); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index c247ad0cd6..f3faaafa2f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -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 profileList; - profileList = profile.getProfileList(); + profileList = profileStore.getProfileList(); ArrayAdapter adapter = new ArrayAdapter(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(""); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java index 3666573d0a..572f8edae0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 637bf018d8..6763013634 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -94,7 +94,7 @@ 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.data.Profile; import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog; @@ -594,16 +594,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 { @@ -839,15 +837,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, 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 - pumpStatusView.setText(R.string.noprofileset); - pumpStatusLayout.setVisibility(View.VISIBLE); - loopStatusLayout.setVisibility(View.GONE); - return; - } else { - pumpStatusLayout.setVisibility(View.GONE); - loopStatusLayout.setVisibility(View.VISIBLE); - } +// if (MainApp.getConfigBuilder().getActiveProfile().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); +// } PumpInterface pump = MainApp.getConfigBuilder(); @@ -893,13 +891,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } // temp target - NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); + Profile profile = MainApp.getConfigBuilder().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())); + 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())); } else { Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; @@ -952,10 +950,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, basalLayout.setVisibility(View.GONE); } - if (profile != null && profile.getActiveProfile() != null) { - activeProfileView.setText(profile.getActiveProfile()); - activeProfileView.setBackgroundColor(Color.GRAY); - } + activeProfileView.setText(MainApp.getConfigBuilder().getProfileName()); + activeProfileView.setBackgroundColor(Color.GRAY); activeProfileView.setOnLongClickListener(new View.OnLongClickListener() { @Override @@ -992,7 +988,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,10 +1010,10 @@ 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); } @@ -1034,9 +1030,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(""); @@ -1130,7 +1126,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 = profile.getBasal(Profile.secondsFromMidnight(new Date(time))); double baseLineValue = baseBasalValue; double tempBasalValue = 0; double basal = 0d; @@ -1346,7 +1342,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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java index 4f3e2a255c..63ad14ab6b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java @@ -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() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java index 91efde76c7..b11bc8c530 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java @@ -32,14 +32,14 @@ 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; /** * Created by adrian on 23/12/16. */ -public class PersistentNotificationPlugin implements PluginBase{ +public class PersistentNotificationPlugin implements PluginBase { private static final int ONGOING_NOTIFICATION_ID = 4711; static boolean fragmentEnabled = true; @@ -99,7 +99,7 @@ public class PersistentNotificationPlugin implements PluginBase{ @Override public void setFragmentEnabled(int type, boolean fragmentEnabled) { - if(getType() == type){ + if (getType() == type) { this.fragmentEnabled = fragmentEnabled; checkBusRegistration(); updateNotification(); @@ -109,7 +109,7 @@ public class PersistentNotificationPlugin implements PluginBase{ private void updateNotification() { - if(!fragmentEnabled){ + if (!fragmentEnabled) { NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.cancel(ONGOING_NOTIFICATION_ID); @@ -118,14 +118,13 @@ 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(); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); - if(profile != null && lastBG != null) { + if (profile != null && lastBG != null) { line1 = lastBG.valueToUnitsToString(profile.getUnits()); if (glucoseStatus != null) { line1 += " Δ" + deltastring(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, profile.getUnits()) @@ -158,9 +157,8 @@ 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); builder.setOngoing(true); @@ -192,32 +190,32 @@ public class PersistentNotificationPlugin implements PluginBase{ } private void checkBusRegistration() { - if(fragmentEnabled){ + if (fragmentEnabled) { MainApp.bus().register(this); } else { try { MainApp.bus().unregister(this); - } catch (Exception e) {} + } catch (Exception e) { + } } } @Override public void setFragmentVisible(int type, boolean fragmentVisible) { - //no visible fragment + //no visible fragment } private String deltastring(double deltaMGDL, double deltaMMOL, String units) { String deltastring = ""; - if (deltaMGDL >=0){ + if (deltaMGDL >= 0) { deltastring += "+"; - } else{ + } else { deltastring += "-"; } - if (units.equals(Constants.MGDL)){ + if (units.equals(Constants.MGDL)) { deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMGDL)); - } - else { + } else { deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMMOL)); } return deltastring; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java index dc5fe95190..0fe6c30c78 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java @@ -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"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java index 6e822e5d43..d22361981c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java @@ -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; + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java index 028ef1ac45..4886a506f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java @@ -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) { - 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()); +// if (nsProfilePlugin.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(MainApp.getConfigBuilder().getProfileName()); + ic.setText(profile.getIcList()); + isf.setText(profile.getIsfList()); + basal.setText(profile.getBasalList()); + target.setText(profile.getTargetList()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java index 5f29881b2a..1544808ca7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java @@ -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.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.data.ProfileStore; 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); @@ -53,7 +52,7 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface { @Override public String getNameShort() { String name = MainApp.sResources.getString(R.string.profileviewer_shortname); - if (!name.trim().isEmpty()){ + if (!name.trim().isEmpty()) { //only if translation exists return name; } @@ -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(); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java index aac4a05798..40a53d0707 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java @@ -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"; + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java index ffbf4d9084..b672d80f24 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java @@ -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 = ""; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java index e95b45d760..af36e4059f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java @@ -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); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java index f4f5bf2b31..9f05a7569a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java @@ -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); - DanaRPlugin.doConnect("ProfileViewDialog"); + 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()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRHistoryActivity.java index 468d40dd57..0116498233 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRHistoryActivity.java @@ -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: diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java index 82436cd067..72ecf91f0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java @@ -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)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRStatsActivity.java index 7b0c3682c8..6a360b9c26 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRStatsActivity.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java index 0c1b50d109..957819aaf9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java @@ -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. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java index 5df5fa238b..adc513d034 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java @@ -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 = ""; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRHistoryActivity.java index bc8345e72b..d9802c016c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRHistoryActivity.java @@ -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: diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRStatsActivity.java index 8644160ea5..dc014b5eaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/History/DanaRStatsActivity.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java index 524e7b0682..89976c6778 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java index cee70f606d..053ef6f6c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java @@ -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 = ""; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRHistoryActivity.java index 505e22dfa6..1391b753f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRHistoryActivity.java @@ -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: diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRStatsActivity.java index e225369875..d366c42df7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/History/DanaRStatsActivity.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java index 750efa1178..24a98a4e44 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java @@ -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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java index 5435280758..6138b1d2ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java index 4354f7d546..b0c55ba036 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java @@ -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())); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java index be8646157a..309c031803 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java @@ -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; @@ -88,7 +85,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { @Override public String getNameShort() { String name = MainApp.sResources.getString(R.string.virtualpump_shortname); - if (!name.trim().isEmpty()){ + if (!name.trim().isEmpty()) { //only if translation exists return name; } @@ -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; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java index ecacbbcb48..e77e16005f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java @@ -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(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java index bbfd2ce4c0..5fbd12c21e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java @@ -11,7 +11,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -19,6 +18,7 @@ import info.nightscout.androidaps.data.Iob; 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; @@ -28,11 +28,11 @@ 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.androidaps.data.Profile; import info.nightscout.utils.OverlappingIntervals; +import info.nightscout.utils.ProfileIntervals; import info.nightscout.utils.SP; /** @@ -123,9 +123,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { 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().getProfile().getDia(); long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia)); treatments = MainApp.getDbHelper().getTreatmentDataFromTime(fromMills, false); @@ -133,9 +131,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().getProfile().getDia(); long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia)); tempBasals.reset().add(MainApp.getDbHelper().getTemporaryBasalsDataFromTime(fromMills, false)); @@ -144,9 +140,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().getProfile().getDia(); long fromMills = (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia)); extendedBoluses.reset().add(MainApp.getDbHelper().getExtendedBolusDataFromTime(fromMills, false)); @@ -167,9 +161,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 +198,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 +396,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 +417,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 +446,21 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { return tempTargets; } + @Override + public ProfileSwitch getProfileSwitchFromHistory(long time) { + return null; + } + + @Override + public ProfileIntervals getProfileSwitchesFromHistory() { + return null; + } + + @Override + public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) { + log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); + MainApp.getDbHelper().createOrUpdate(profileSwitch); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java index 1d868b5356..c670fbbe16 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java @@ -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)); @@ -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() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java index 5e1c4f8cdd..2ee2c4fe61 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java @@ -25,8 +25,7 @@ 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; @@ -62,7 +61,7 @@ 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()) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java index 36e6f43899..9c4fc24f25 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java @@ -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"; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java index 2e3523bf41..d58742d32a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java @@ -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 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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java index 8e4d419c1b..49446579a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java @@ -24,7 +24,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; /** @@ -186,12 +186,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); diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index 5c889b661f..6b48804926 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -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()); diff --git a/app/src/main/java/info/nightscout/utils/BolusWizard.java b/app/src/main/java/info/nightscout/utils/BolusWizard.java index b3d44dbcc4..ea34c7c8f9 100644 --- a/app/src/main/java/info/nightscout/utils/BolusWizard.java +++ b/app/src/main/java/info/nightscout/utils/BolusWizard.java @@ -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 diff --git a/app/src/main/java/info/nightscout/utils/NSUpload.java b/app/src/main/java/info/nightscout/utils/NSUpload.java index c0cc3a985a..8dd50c08d8 100644 --- a/app/src/main/java/info/nightscout/utils/NSUpload.java +++ b/app/src/main/java/info/nightscout/utils/NSUpload.java @@ -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")) { diff --git a/app/src/main/java/info/nightscout/utils/OverlappingIntervals.java b/app/src/main/java/info/nightscout/utils/OverlappingIntervals.java index 55647061f2..bf3fe18b17 100644 --- a/app/src/main/java/info/nightscout/utils/OverlappingIntervals.java +++ b/app/src/main/java/info/nightscout/utils/OverlappingIntervals.java @@ -14,6 +14,8 @@ import info.nightscout.androidaps.interfaces.Interval; * Created by mike on 09.05.2017. */ +// Zero duration means end of interval + public class OverlappingIntervals { private LongSparseArray rawData = new LongSparseArray<>(); // oldest at index 0 diff --git a/app/src/main/java/info/nightscout/utils/ProfileIntervals.java b/app/src/main/java/info/nightscout/utils/ProfileIntervals.java new file mode 100644 index 0000000000..719bd8d569 --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/ProfileIntervals.java @@ -0,0 +1,106 @@ +package info.nightscout.utils; + +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 { + + private LongSparseArray 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 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 getList() { + List list = new ArrayList<>(); + for (int i = 0; i < rawData.size(); i++) + list.add(rawData.valueAt(i)); + return list; + } + + public List getReversedList() { + List list = new ArrayList<>(); + for (int i = rawData.size() -1; i>=0; i--) + list.add(rawData.valueAt(i)); + return list; + } + + private int binarySearch(long value) { + int lo = 0; + int hi = rawData.size() - 1; + + while (lo <= hi) { + final int mid = (lo + hi) >>> 1; + final Interval midVal = rawData.valueAt(mid); + + if (midVal.before(value)) { + lo = mid + 1; + } else if (midVal.after(value)) { + hi = mid - 1; + } else if (midVal.match(value)) { + return mid; // value found + } + } + // not found, try nearest older with duration 0 + while (lo >= 0) { + 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); + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/utils/SP.java b/app/src/main/java/info/nightscout/utils/SP.java index 9bed316195..4733c42d04 100644 --- a/app/src/main/java/info/nightscout/utils/SP.java +++ b/app/src/main/java/info/nightscout/utils/SP.java @@ -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)); diff --git a/app/src/main/java/info/nightscout/utils/XdripCalibrations.java b/app/src/main/java/info/nightscout/utils/XdripCalibrations.java index 53c3bf45ec..2bc60d3693 100644 --- a/app/src/main/java/info/nightscout/utils/XdripCalibrations.java +++ b/app/src/main/java/info/nightscout/utils/XdripCalibrations.java @@ -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(); diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4e56869e16..6718710e31 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -620,4 +620,9 @@ Insulin age hours Basal type + ISF missing in profile. Using default. + IC missing in profile. Using default. + Basal missing in profile. Using default. + Target missing in profile. Using default. + Invalid profile !!! From 6ca4811e8e734d108e41d279270790cb27e1f761 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 2 Jun 2017 12:27:21 +0200 Subject: [PATCH 2/8] profiles visualisation --- .../data}/OverlappingIntervals.java | 4 +- .../nightscout/androidaps/data/Profile.java | 6 +- .../data}/ProfileIntervals.java | 6 +- .../androidaps/db/DatabaseHelper.java | 21 +- .../androidaps/db/ProfileSwitch.java | 25 +- .../events/EventProfileSwitchChange.java | 8 + .../interfaces/TreatmentsInterface.java | 4 +- .../ConfigBuilder/ConfigBuilderPlugin.java | 4 +- .../IobCobCalculatorPlugin.java | 4 + .../plugins/Overview/OverviewFragment.java | 23 +- .../VerticalTextsGraphSeries.java | 326 ++++++++++++++++++ .../PersistentNotificationPlugin.java | 2 +- .../plugins/Treatments/TreatmentsPlugin.java | 29 +- .../TreatmentsExtendedBolusesFragment.java | 2 +- .../TreatmentsTempTargetFragment.java | 2 +- .../TreatmentsTemporaryBasalsFragment.java | 2 +- 16 files changed, 429 insertions(+), 39 deletions(-) rename app/src/main/java/info/nightscout/{utils => androidaps/data}/OverlappingIntervals.java (96%) rename app/src/main/java/info/nightscout/{utils => androidaps/data}/ProfileIntervals.java (94%) create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java diff --git a/app/src/main/java/info/nightscout/utils/OverlappingIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java similarity index 96% rename from app/src/main/java/info/nightscout/utils/OverlappingIntervals.java rename to app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java index bf3fe18b17..cc03936766 100644 --- a/app/src/main/java/info/nightscout/utils/OverlappingIntervals.java +++ b/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index 757b706da0..dd68eff35f 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -291,7 +291,7 @@ public class Profile { return max; } - public static int secondsFromMidnight() { + public static Integer secondsFromMidnight() { Calendar c = Calendar.getInstance(); long now = c.getTimeInMillis(); c.set(Calendar.HOUR_OF_DAY, 0); @@ -302,7 +302,7 @@ public class Profile { return (int) (passed / 1000); } - public static int secondsFromMidnight(Date date) { + public static Integer secondsFromMidnight(Date date) { Calendar c = Calendar.getInstance(); long now = date.getTime(); c.setTime(date); @@ -314,7 +314,7 @@ public class Profile { return (int) (passed / 1000); } - public static int secondsFromMidnight(long date) { + public static Integer secondsFromMidnight(long date) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(date); c.set(Calendar.HOUR_OF_DAY, 0); diff --git a/app/src/main/java/info/nightscout/utils/ProfileIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java similarity index 94% rename from app/src/main/java/info/nightscout/utils/ProfileIntervals.java rename to app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java index 719bd8d569..e5ecea9f97 100644 --- a/app/src/main/java/info/nightscout/utils/ProfileIntervals.java +++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java @@ -1,4 +1,4 @@ -package info.nightscout.utils; +package info.nightscout.androidaps.data; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; @@ -68,6 +68,8 @@ public class ProfileIntervals { } private int binarySearch(long value) { + if (rawData.size() == 0) + return -1; int lo = 0; int hi = rawData.size() - 1; @@ -84,7 +86,7 @@ public class ProfileIntervals { } } // not found, try nearest older with duration 0 - while (lo >= 0) { + while (lo >= 0 && lo < rawData.size()) { if (rawData.valueAt(lo).isEndingEvent()) return lo; lo--; diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 246e6f13d0..995a10ec28 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -31,10 +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.EventNewBasalProfile; +import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; @@ -42,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.data.Profile; import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync; public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @@ -272,7 +272,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { scheduleCareportalEventChange(); } - public void resetProfileSwitch() { + public void resetProfileSwitch() { try { TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); @@ -1342,14 +1342,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // ---------------- ProfileSwitch handling --------------- - public List getProfileSwitchDataFromTime(long mills, boolean ascending) { + public List getProfileSwitchData(boolean ascending) { try { Dao daoProfileSwitch = getDaoProfileSwitch(); List profileSwitches; QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder(); queryBuilder.orderBy("date", ascending); - Where where = queryBuilder.where(); - where.ge("date", mills); + queryBuilder.limit(20L); PreparedQuery preparedQuery = queryBuilder.prepare(); profileSwitches = daoProfileSwitch.query(preparedQuery); return profileSwitches; @@ -1381,8 +1380,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleProfileSwitchChange() { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventNewBasalProfileChange"); - MainApp.bus().post(new EventNewBasalProfile()); + log.debug("Firing EventProfileSwitchChange"); + MainApp.bus().post(new EventProfileSwitchChange()); scheduledProfileSwitchEventPost = null; } } @@ -1438,11 +1437,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (trJson.has("timeshift")) profileSwitch.timeshift = trJson.getInt("timeshift"); if (trJson.has("percentage")) - profileSwitch.percentage = trJson.getInt("percentage"); + profileSwitch.percentage = trJson.getInt("percentage"); if (trJson.has("profileJson")) - profileSwitch.profileJson = trJson.getString("profileJson"); + profileSwitch.profileJson = trJson.getString("profileJson"); if (trJson.has("profilePlugin")) - profileSwitch.profilePlugin = trJson.getString("profilePlugin"); + profileSwitch.profilePlugin = trJson.getString("profilePlugin"); createOrUpdate(profileSwitch); } catch (SQLException | JSONException e) { e.printStackTrace(); diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java index 2d82c3e478..ec27d916f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -8,14 +8,12 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.interfaces.Interval; -import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; +import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.DecimalFormatter; @DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES) -public class ProfileSwitch implements Interval { +public class ProfileSwitch implements Interval, DataPointWithLabelInterface { private static Logger log = LoggerFactory.getLogger(ProfileSwitch.class); @DatabaseField(id = true) @@ -106,6 +104,25 @@ public class ProfileSwitch implements Interval { // -------- 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 + diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java new file mode 100644 index 0000000000..476a571d70 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.events; + +/** + * Created by mike on 02.06.2017. + */ + +public class EventProfileSwitchChange { +} diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index d210d07620..5b7a8a8db0 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -10,8 +10,8 @@ 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.utils.ProfileIntervals; +import info.nightscout.androidaps.data.OverlappingIntervals; +import info.nightscout.androidaps.data.ProfileIntervals; /** * Created by mike on 14.06.2016. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java index e97f8a77f7..1a5f61de97 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java @@ -47,8 +47,8 @@ import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogr 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; -import info.nightscout.utils.ProfileIntervals; +import info.nightscout.androidaps.data.OverlappingIntervals; +import info.nightscout.androidaps.data.ProfileIntervals; /** * Created by mike on 05.08.2016. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java index 4a55b8ee0e..967dfc2684 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java @@ -227,6 +227,8 @@ public class IobCobCalculatorPlugin implements PluginBase { } public void calculateSensitivityData() { + if (MainApp.getConfigBuilder() == null) + return; // app still initializing //log.debug("Locking calculateSensitivityData"); synchronized (dataLock) { Profile profile = MainApp.getConfigBuilder().getProfile(); @@ -514,6 +516,8 @@ public class IobCobCalculatorPlugin implements PluginBase { @Subscribe public void onNewProfile(EventNewBasalProfile ev) { + if (MainApp.getConfigBuilder() == null) + return; // app still initializing Profile profile = MainApp.getConfigBuilder().getProfile(); dia = profile.getDia(); if (ev == null) { // on init no need of reset diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 6763013634..ba6e489b57 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -70,6 +70,7 @@ 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.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.Treatment; @@ -107,6 +108,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; @@ -1112,6 +1114,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, PointsGraphSeries seriesHigh; PointsGraphSeries predSeries; PointsWithLabelGraphSeries seriesTreatments; + VerticalTextsGraphSeries seriesProfileSwitch; // **** TEMP BASALS graph **** Double maxBasalValueFound = 0d; @@ -1419,7 +1422,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); } @@ -1432,6 +1435,24 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, seriesTreatments.setColor(Color.CYAN); } + // ProfileSwitch + List profileSwitches = MainApp.getConfigBuilder().getProfileSwitchesFromHistory().getList(); + List filteredProfileSwitches = new ArrayList(); + + for (int tx = 0; tx < profileSwitches.size(); tx++) { + ProfileSwitch t = profileSwitches.get(tx); + if (t.date < fromTime || t.date > now) continue; + filteredProfileSwitches.add(t); + } + ProfileSwitch[] profileSwitchArray = new ProfileSwitch[filteredProfileSwitches.size()]; + profileSwitchArray = filteredProfileSwitches.toArray(profileSwitchArray); + if (profileSwitchArray.length > 0) { + bgGraph.addSeries(seriesProfileSwitch = new VerticalTextsGraphSeries(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); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java new file mode 100644 index 0000000000..c27b2f0088 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java @@ -0,0 +1,326 @@ +package info.nightscout.androidaps.plugins.Overview.graphExtensions; + +/** + * GraphView + * Copyright (C) 2014 Jonas Gehring + *

+ * 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. + *

+ * 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. + *

+ * 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 . + *

+ * 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 extends BaseSeries { + /** + * 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 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; + float py = (float) (graphHeight * ratY + bounds.height() + 80); + canvas.save(); + canvas.rotate(-90, px, py); + canvas.drawText(value.getLabel(), px, py, mPaint); + canvas.drawRect(bounds.left + 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; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java index b11bc8c530..7e7f2ab7a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java @@ -102,7 +102,7 @@ public class PersistentNotificationPlugin implements PluginBase { if (getType() == type) { this.fragmentEnabled = fragmentEnabled; checkBusRegistration(); - updateNotification(); + //updateNotification(); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java index 5fbd12c21e..87ecddcfa4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -22,6 +23,8 @@ 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.EventNewBasalProfile; +import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTempTargetChange; @@ -31,8 +34,8 @@ import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.data.Profile; -import info.nightscout.utils.OverlappingIntervals; -import info.nightscout.utils.ProfileIntervals; +import info.nightscout.androidaps.data.OverlappingIntervals; +import info.nightscout.androidaps.data.ProfileIntervals; import info.nightscout.utils.SP; /** @@ -48,6 +51,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { private static OverlappingIntervals tempBasals = new OverlappingIntervals<>(); private static OverlappingIntervals extendedBoluses = new OverlappingIntervals<>(); private static OverlappingIntervals tempTargets = new OverlappingIntervals<>(); + private static ProfileIntervals profiles = new ProfileIntervals<>(); private static boolean fragmentEnabled = true; private static boolean fragmentVisible = true; @@ -119,11 +123,12 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { initializeTreatmentData(); initializeExtendedBolusData(); initializeTempTargetData(); + initializeProfileSwitchData(); } public static void initializeTreatmentData() { // Treatments - double dia = MainApp.getConfigBuilder().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); @@ -131,7 +136,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { public static void initializeTempBasalData() { // Treatments - double dia = MainApp.getConfigBuilder().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)); @@ -140,7 +145,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { public static void initializeExtendedBolusData() { // Treatments - double dia = MainApp.getConfigBuilder().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)); @@ -152,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; @@ -446,14 +455,20 @@ 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 null; + return (ProfileSwitch) profiles.getValueToTime(time); } @Override public ProfileIntervals getProfileSwitchesFromHistory() { - return null; + return profiles; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java index 2964e41ea8..96842aafbe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -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 { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java index 2ee2c4fe61..ad977e758d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java @@ -29,7 +29,7 @@ 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; /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 436b908ecd..acd82e227c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -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 { From d365fcd6a4619b69e32f140c9e530661d3f0ab43 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 2 Jun 2017 23:25:11 +0200 Subject: [PATCH 3/8] fix bugs & design tweaking --- .../androidaps/data/ProfileIntervals.java | 7 +- .../ConfigBuilder/ConfigBuilderPlugin.java | 1 + .../plugins/Overview/OverviewFragment.java | 16 +- .../VerticalTextsGraphSeries.java | 6 +- .../Treatments/TreatmentsFragment.java | 11 +- .../fragments/TreatmentsBolusFragment.java | 2 +- .../TreatmentsProfileSwitchFragment.java | 203 ++++++++++++++++++ .../TreatmentsTempTargetFragment.java | 4 +- app/src/main/res/layout/overview_fragment.xml | 19 +- .../main/res/layout/treatments_fragment.xml | 27 ++- .../treatments_profileswitch_fragment.xml | 28 +++ .../layout/treatments_profileswitch_item.xml | 81 +++++++ .../layout/treatments_temptarget_fragment.xml | 2 +- app/src/main/res/values-bg/strings.xml | 3 - app/src/main/res/values-cs/strings.xml | 4 +- app/src/main/res/values-de/strings.xml | 1 - app/src/main/res/values-es/strings.xml | 3 - app/src/main/res/values-it/strings.xml | 3 - app/src/main/res/values-ko/strings.xml | 3 - app/src/main/res/values-ru/strings.xml | 3 - app/src/main/res/values/strings.xml | 5 +- 21 files changed, 380 insertions(+), 52 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java create mode 100644 app/src/main/res/layout/treatments_profileswitch_fragment.xml create mode 100644 app/src/main/res/layout/treatments_profileswitch_item.xml diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java index e5ecea9f97..ef255ed901 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java +++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java @@ -77,15 +77,16 @@ public class ProfileIntervals { final int mid = (lo + hi) >>> 1; final Interval midVal = rawData.valueAt(mid); - if (midVal.before(value)) { + if (midVal.match(value)) { + return mid; // value found + } else if (midVal.before(value)) { lo = mid + 1; } else if (midVal.after(value)) { hi = mid - 1; - } else if (midVal.match(value)) { - return mid; // value found } } // not found, try nearest older with duration 0 + lo = lo - 1; while (lo >= 0 && lo < rawData.size()) { if (rawData.valueAt(lo).isEndingEvent()) return lo; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java index 1a5f61de97..ea081d23fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java @@ -998,6 +998,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain 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) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index ba6e489b57..55fe2d289a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -25,6 +25,7 @@ import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; +import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; @@ -268,6 +269,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, 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(); @@ -1441,7 +1455,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, for (int tx = 0; tx < profileSwitches.size(); tx++) { ProfileSwitch t = profileSwitches.get(tx); - if (t.date < fromTime || t.date > now) continue; + if (t.date < fromTime || t.date > endTime) continue; filteredProfileSwitches.add(t); } ProfileSwitch[] profileSwitchArray = new ProfileSwitch[filteredProfileSwitches.size()]; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java index c27b2f0088..75803c24b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphExtensions/VerticalTextsGraphSeries.java @@ -237,12 +237,12 @@ public class VerticalTextsGraphSeries ext Rect bounds = new Rect(); mPaint.getTextBounds(value.getLabel(), 0, value.getLabel().length(), bounds); mPaint.setStyle(Paint.Style.STROKE); - float px = endX; - float py = (float) (graphHeight * ratY + bounds.height() + 80); + 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(bounds.left + px - 3, bounds.top + py - 3, bounds.right + px + 3, bounds.bottom + py + 3, mPaint); + canvas.drawRect(px - 3, bounds.top + py - 3, bounds.right + px + 3, bounds.bottom + py + 3, mPaint); canvas.restore(); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java index 9644ff1be6..1bf66ca5ec 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java @@ -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)); } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java index c670fbbe16..c2bbd123e3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java @@ -183,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(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java new file mode 100644 index 0000000000..01955ba937 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -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 { + + ProfileIntervals profileSwitchList; + + RecyclerViewAdapter(ProfileIntervals 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); + } + }); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java index ad977e758d..d8a84b0e1c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java @@ -65,7 +65,7 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli 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())); @@ -180,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(); diff --git a/app/src/main/res/layout/overview_fragment.xml b/app/src/main/res/layout/overview_fragment.xml index 2f56efeda4..27e7cd1180 100644 --- a/app/src/main/res/layout/overview_fragment.xml +++ b/app/src/main/res/layout/overview_fragment.xml @@ -12,11 +12,12 @@ @@ -71,14 +72,14 @@ @@ -162,7 +163,7 @@ @@ -289,15 +290,17 @@ + android:layout_height="0dp" + android:layout_weight="1" /> - + + + + + +