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 7cdd287316..9f3873cb93 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -12,8 +12,6 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Objects; - import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -23,8 +21,6 @@ import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventNsTreatment; -import info.nightscout.androidaps.interfaces.BgSourceInterface; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; @@ -64,60 +60,56 @@ public class DataService extends IntentService { public DataService() { super("DataService"); - MainApp.subscribe(this); + registerBus(); } @Override protected void onHandleIntent(final Intent intent) { - if (intent == null) - return; - if (Config.logIncommingData) - log.debug("Got intent: " + intent.getAction()); if (Config.logFunctionCalls) log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras())); - if (ConfigBuilderPlugin.getActiveBgSource() == null) { + if (ConfigBuilderPlugin.getPlugin().getActiveBgSource() == null) { xDripEnabled = true; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) { + } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) { xDripEnabled = true; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { + } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { xDripEnabled = false; nsClientEnabled = true; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { + } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = true; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { + } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = true; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) { + } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = true; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) { + } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = false; @@ -134,53 +126,55 @@ public class DataService extends IntentService { acceptNSData = acceptNSData || bundles.getBoolean("islocal"); } - final String action = intent.getAction(); - if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { - if (xDripEnabled) { - processNewBgIntent(SourceXdripPlugin.getPlugin(), intent); - } - } else if (Intents.NS_EMULATOR.equals(action)) { - if (mm640gEnabled) { - processNewBgIntent(SourceMM640gPlugin.getPlugin(), intent); - } - } else if (Intents.GLIMP_BG.equals(action)) { - if (glimpEnabled) { - processNewBgIntent(SourceGlimpPlugin.getPlugin(), intent); - } - } else if (Intents.DEXCOMG5_BG.equals(action)) { - if (dexcomG5Enabled) { - processNewBgIntent(SourceDexcomG5Plugin.getPlugin(), intent); - } - } else if (Intents.POCTECH_BG.equals(action)) { - if (poctechEnabled) { - processNewBgIntent(SourcePoctechPlugin.getPlugin(), intent); - } - } else if (Intents.ACTION_NEW_SGV.equals(action)) { - if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true)) - handleNewDataFromNSClient(intent); - // Objectives 0 - ObjectivesPlugin.bgIsAvailableInNS = true; - ObjectivesPlugin.saveProgress(); - } else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) { - // always handle Profile if NSProfile is enabled without looking at nsUploadOnly - handleNewDataFromNSClient(intent); - } else if (acceptNSData && - (Intents.ACTION_NEW_TREATMENT.equals(action) || - Intents.ACTION_CHANGED_TREATMENT.equals(action) || - Intents.ACTION_REMOVED_TREATMENT.equals(action) || - Intents.ACTION_NEW_STATUS.equals(action) || - Intents.ACTION_NEW_DEVICESTATUS.equals(action) || - Intents.ACTION_NEW_FOOD.equals(action) || - Intents.ACTION_CHANGED_FOOD.equals(action) || - Intents.ACTION_REMOVED_FOOD.equals(action) || - Intents.ACTION_NEW_CAL.equals(action) || - Intents.ACTION_NEW_MBG.equals(action)) - ) { - handleNewDataFromNSClient(intent); - } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { - handleNewSMS(intent); - } + if (intent != null) { + final String action = intent.getAction(); + if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { + if (xDripEnabled) { + handleNewDataFromXDrip(intent); + } + } else if (Intents.NS_EMULATOR.equals(action)) { + if (mm640gEnabled) { + handleNewDataFromMM640g(intent); + } + } else if (Intents.GLIMP_BG.equals(action)) { + if (glimpEnabled) { + handleNewDataFromGlimp(intent); + } + } else if (Intents.DEXCOMG5_BG.equals(action)) { + if (dexcomG5Enabled) { + handleNewDataFromDexcomG5(intent); + } + } else if (Intents.POCTECH_BG.equals(action)) { + if (poctechEnabled) { + handleNewDataFromPoctech(intent); + } + } else if (Intents.ACTION_NEW_SGV.equals(action)) { + if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true)) + handleNewDataFromNSClient(intent); + // Objectives 0 + ObjectivesPlugin.bgIsAvailableInNS = true; + ObjectivesPlugin.saveProgress(); + } else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) { + // always handle Profile if NSProfile is enabled without looking at nsUploadOnly + handleNewDataFromNSClient(intent); + } else if (acceptNSData && + (Intents.ACTION_NEW_TREATMENT.equals(action) || + Intents.ACTION_CHANGED_TREATMENT.equals(action) || + Intents.ACTION_REMOVED_TREATMENT.equals(action) || + Intents.ACTION_NEW_STATUS.equals(action) || + Intents.ACTION_NEW_DEVICESTATUS.equals(action) || + Intents.ACTION_NEW_FOOD.equals(action) || + Intents.ACTION_CHANGED_FOOD.equals(action) || + Intents.ACTION_REMOVED_FOOD.equals(action) || + Intents.ACTION_NEW_CAL.equals(action) || + Intents.ACTION_NEW_MBG.equals(action)) + ) { + handleNewDataFromNSClient(intent); + } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { + handleNewSMS(intent); + } + } if (Config.logFunctionCalls) log.debug("onHandleIntent exit " + intent); DataReceiver.completeWakefulIntent(intent); @@ -201,25 +195,167 @@ public class DataService extends IntentService { @Override public void onDestroy() { super.onDestroy(); - MainApp.unsubscribe(this); + MainApp.bus().unregister(this); } - private void processNewBgIntent(BgSourceInterface bgSource, Intent intent) { + private void registerBus() { + try { + MainApp.bus().unregister(this); + } catch (RuntimeException x) { + // Ignore + } + MainApp.bus().register(this); + } + + private void handleNewDataFromXDrip(Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; - bgSource.processNewData(bundle); + + BgReading bgReading = new BgReading(); + + bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE); + bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME); + bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP); + bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); + String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified"); + SourceXdripPlugin.getPlugin().setSource(source); + MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP"); + } + + private void handleNewDataFromGlimp(Intent intent) { + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + bgReading.value = bundle.getDouble("mySGV"); + bgReading.direction = bundle.getString("myTrend"); + bgReading.date = bundle.getLong("myTimestamp"); + bgReading.raw = 0; + + MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP"); + } + + private void handleNewDataFromDexcomG5(Intent intent) { + // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + String data = bundle.getString("data"); + log.debug("Received Dexcom Data", data); + + try { + JSONArray jsonArray = new JSONArray(data); + log.debug("Received Dexcom Data size:" + jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + bgReading.value = json.getInt("m_value"); + bgReading.direction = json.getString("m_trend"); + bgReading.date = json.getLong("m_time") * 1000L; + bgReading.raw = 0; + boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5"); + if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + NSUpload.uploadBg(bgReading); + } + if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { + NSUpload.sendToXdrip(bgReading); + } + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + + private void handleNewDataFromPoctech(Intent intent) { + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + String data = bundle.getString("data"); + log.debug("Received Poctech Data", data); + + try { + JSONArray jsonArray = new JSONArray(data); + log.debug("Received Poctech Data size:" + jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + bgReading.value = json.getDouble("current"); + bgReading.direction = json.getString("direction"); + bgReading.date = json.getLong("date"); + bgReading.raw = json.getDouble("raw"); + if (JsonHelper.safeGetString(json, "utils", Constants.MGDL).equals("mmol/L")) + bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL; + boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech"); + if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + NSUpload.uploadBg(bgReading); + } + if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { + NSUpload.sendToXdrip(bgReading); + } + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + + private void handleNewDataFromMM640g(Intent intent) { + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + final String collection = bundle.getString("collection"); + if (collection == null) return; + + if (collection.equals("entries")) { + final String data = bundle.getString("data"); + + if ((data != null) && (data.length() > 0)) { + try { + final JSONArray json_array = new JSONArray(data); + for (int i = 0; i < json_array.length(); i++) { + final JSONObject json_object = json_array.getJSONObject(i); + final String type = json_object.getString("type"); + switch (type) { + case "sgv": + BgReading bgReading = new BgReading(); + + bgReading.value = json_object.getDouble("sgv"); + bgReading.direction = json_object.getString("direction"); + bgReading.date = json_object.getLong("date"); + bgReading.raw = json_object.getDouble("sgv"); + + MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g"); + break; + default: + log.debug("Unknown entries type: " + type); + } + } + } catch (JSONException e) { + log.error("Got JSON exception: " + e); + } + } + } } private void handleNewDataFromNSClient(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; + Bundle bundles = intent.getExtras(); + if (bundles == null) return; + if (Config.logIncommingData) + log.debug("Got intent: " + intent.getAction()); + if (intent.getAction().equals(Intents.ACTION_NEW_STATUS)) { - if (bundle.containsKey("nsclientversioncode")) { - ConfigBuilderPlugin.nightscoutVersionCode = bundle.getInt("nightscoutversioncode"); // for ver 1.2.3 contains 10203 - ConfigBuilderPlugin.nightscoutVersionName = bundle.getString("nightscoutversionname"); - ConfigBuilderPlugin.nsClientVersionCode = bundle.getInt("nsclientversioncode"); // for ver 1.17 contains 117 - ConfigBuilderPlugin.nsClientVersionName = bundle.getString("nsclientversionname"); + if (bundles.containsKey("nsclientversioncode")) { + ConfigBuilderPlugin.nightscoutVersionCode = bundles.getInt("nightscoutversioncode"); // for ver 1.2.3 contains 10203 + ConfigBuilderPlugin.nightscoutVersionName = bundles.getString("nightscoutversionname"); + ConfigBuilderPlugin.nsClientVersionCode = bundles.getInt("nsclientversioncode"); // for ver 1.17 contains 117 + ConfigBuilderPlugin.nsClientVersionName = bundles.getString("nsclientversionname"); log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName); try { if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) { @@ -241,9 +377,9 @@ public class DataService extends IntentService { Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } - if (bundle.containsKey("status")) { + if (bundles.containsKey("status")) { try { - JSONObject statusJson = new JSONObject(bundle.getString("status")); + JSONObject statusJson = new JSONObject(bundles.getString("status")); NSSettingsStatus.getInstance().setData(statusJson); if (Config.logIncommingData) log.debug("Received status: " + statusJson.toString()); @@ -260,8 +396,8 @@ public class DataService extends IntentService { } if (intent.getAction().equals(Intents.ACTION_NEW_DEVICESTATUS)) { try { - if (bundle.containsKey("devicestatus")) { - JSONObject devicestatusJson = new JSONObject(bundle.getString("devicestatus")); + if (bundles.containsKey("devicestatus")) { + JSONObject devicestatusJson = new JSONObject(bundles.getString("devicestatus")); NSDeviceStatus.getInstance().setData(devicestatusJson); if (devicestatusJson.has("pump")) { // Objectives 0 @@ -269,8 +405,8 @@ public class DataService extends IntentService { ObjectivesPlugin.saveProgress(); } } - if (bundle.containsKey("devicestatuses")) { - String devicestatusesstring = bundle.getString("devicestatuses"); + if (bundles.containsKey("devicestatuses")) { + String devicestatusesstring = bundles.getString("devicestatuses"); JSONArray jsonArray = new JSONArray(devicestatusesstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject devicestatusJson = jsonArray.getJSONObject(i); @@ -289,8 +425,8 @@ public class DataService extends IntentService { // Handle profile if (intent.getAction().equals(Intents.ACTION_NEW_PROFILE)) { try { - String activeProfile = bundle.getString("activeprofile"); - String profile = bundle.getString("profile"); + String activeProfile = bundles.getString("activeprofile"); + String profile = bundles.getString("profile"); ProfileStore profileStore = new ProfileStore(new JSONObject(profile)); NSProfilePlugin.getPlugin().storeNewProfile(profileStore); MainApp.bus().post(new EventNSProfileUpdateGUI()); @@ -303,12 +439,12 @@ public class DataService extends IntentService { if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { try { - if (bundle.containsKey("treatment")) { - JSONObject json = new JSONObject(bundle.getString("treatment")); + if (bundles.containsKey("treatment")) { + JSONObject json = new JSONObject(bundles.getString("treatment")); handleTreatmentFromNS(json, intent); } - if (bundle.containsKey("treatments")) { - String trstring = bundle.getString("treatments"); + if (bundles.containsKey("treatments")) { + String trstring = bundles.getString("treatments"); JSONArray jsonArray = new JSONArray(trstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); @@ -322,14 +458,14 @@ public class DataService extends IntentService { if (intent.getAction().equals(Intents.ACTION_REMOVED_TREATMENT)) { try { - if (bundle.containsKey("treatment")) { - String trstring = bundle.getString("treatment"); + if (bundles.containsKey("treatment")) { + String trstring = bundles.getString("treatment"); JSONObject json = new JSONObject(trstring); handleTreatmentFromNS(json); } - if (bundle.containsKey("treatments")) { - String trstring = bundle.getString("treatments"); + if (bundles.containsKey("treatments")) { + String trstring = bundles.getString("treatments"); JSONArray jsonArray = new JSONArray(trstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); @@ -342,19 +478,36 @@ public class DataService extends IntentService { } if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) { - SourceNSClientPlugin.getPlugin().processNewData(bundle); + try { + if (bundles.containsKey("sgv")) { + String sgvstring = bundles.getString("sgv"); + JSONObject sgvJson = new JSONObject(sgvstring); + storeSgv(sgvJson); + } + + if (bundles.containsKey("sgvs")) { + String sgvstring = bundles.getString("sgvs"); + JSONArray jsonArray = new JSONArray(sgvstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject sgvJson = jsonArray.getJSONObject(i); + storeSgv(sgvJson); + } + } + } catch (Exception e) { + log.error("Unhandled exception", e); + } } if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) { try { - if (bundle.containsKey("mbg")) { - String mbgstring = bundle.getString("mbg"); + if (bundles.containsKey("mbg")) { + String mbgstring = bundles.getString("mbg"); JSONObject mbgJson = new JSONObject(mbgstring); storeMbg(mbgJson); } - if (bundle.containsKey("mbgs")) { - String sgvstring = bundle.getString("mbgs"); + if (bundles.containsKey("mbgs")) { + String sgvstring = bundles.getString("mbgs"); JSONArray jsonArray = new JSONArray(sgvstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject mbgJson = jsonArray.getJSONObject(i); @@ -369,12 +522,12 @@ public class DataService extends IntentService { if (intent.getAction().equals(Intents.ACTION_NEW_FOOD) || intent.getAction().equals(Intents.ACTION_CHANGED_FOOD)) { int mode = Intents.ACTION_NEW_FOOD.equals(intent.getAction()) ? EventNsFood.ADD : EventNsFood.UPDATE; - EventNsFood evt = new EventNsFood(mode, bundle); + EventNsFood evt = new EventNsFood(mode, bundles); MainApp.bus().post(evt); } if (intent.getAction().equals(Intents.ACTION_REMOVED_FOOD)) { - EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundle); + EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles); MainApp.bus().post(evt); } } @@ -392,7 +545,7 @@ public class DataService extends IntentService { MainApp.getDbHelper().deleteProfileSwitchById(_id); } - private void handleTreatmentFromNS(JSONObject json, Intent intent) { + private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException { // new DB model int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE; double insulin = JsonHelper.safeGetDouble(json, "insulin"); @@ -447,6 +600,13 @@ public class DataService extends IntentService { log.debug("Adding/Updating new MBG: " + careportalEvent.log()); } + private void storeSgv(JSONObject sgvJson) { + NSSgv nsSgv = new NSSgv(sgvJson); + BgReading bgReading = new BgReading(nsSgv); + MainApp.getDbHelper().createIfNotExists(bgReading, "NS"); + SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills")); + } + private void handleNewSMS(Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; diff --git a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java index 272158f2ed..bfbbfedbd1 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java +++ b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java @@ -42,6 +42,10 @@ public class ConstraintChecker implements ConstraintsInterface { return isSMBModeEnabled(new Constraint<>(true)); } + public Constraint isAdvancedFilteringEnabled() { + return isAdvancedFilteringEnabled(new Constraint<>(true)); + } + public Constraint getMaxBasalAllowed(Profile profile) { return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile); } @@ -65,7 +69,7 @@ public class ConstraintChecker implements ConstraintsInterface { @Override public Constraint isLoopInvocationAllowed(Constraint value) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); + ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); for (PluginBase p : constraintsPlugins) { ConstraintsInterface constraint = (ConstraintsInterface) p; if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; @@ -77,7 +81,7 @@ public class ConstraintChecker implements ConstraintsInterface { @Override public Constraint isClosedLoopAllowed(Constraint value) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); + ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); for (PluginBase p : constraintsPlugins) { ConstraintsInterface constraint = (ConstraintsInterface) p; if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; @@ -122,6 +126,17 @@ public class ConstraintChecker implements ConstraintsInterface { return value; } + @Override + public Constraint isAdvancedFilteringEnabled(Constraint value) { + ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); + for (PluginBase p : constraintsPlugins) { + ConstraintsInterface constraint = (ConstraintsInterface) p; + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; + constraint.isAdvancedFilteringEnabled(value); + } + return value; + } + @Override public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java index d7ebfdc677..5ddb7a80b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.db; +import android.content.res.Resources; + import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @@ -36,10 +38,6 @@ public class BgReading implements DataPointWithLabelInterface { public String direction; @DatabaseField public double raw; - @DatabaseField - public boolean isFiltered; - @DatabaseField - public String sourcePlugin; @DatabaseField public int source = Source.NONE; @@ -122,11 +120,19 @@ public class BgReading implements DataPointWithLabelInterface { ", value=" + value + ", direction=" + direction + ", raw=" + raw + - ", filtered=" + isFiltered + - ", sourcePlugin=" + sourcePlugin + '}'; } + public boolean isDataChanging(BgReading other) { + if (date != other.date) { + log.error("Comparing different"); + return false; + } + if (value != other.value) + return true; + return false; + } + public boolean isEqual(BgReading other) { if (date != other.date) { log.error("Comparing different"); 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 cbb48a69a6..5095195872 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -28,6 +28,7 @@ import java.util.concurrent.ScheduledFuture; 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.OverlappingIntervals; import info.nightscout.androidaps.data.Profile; @@ -117,28 +118,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); TableUtils.createTableIfNotExists(connectionSource, TDD.class); - - // soft migration without changing DB version - createColumnIfNotExists(getDaoBgReadings(), DatabaseHelper.DATABASE_BGREADINGS, - "isFiltered", "integer"); - createColumnIfNotExists(getDaoBgReadings(), DatabaseHelper.DATABASE_BGREADINGS, - "sourcePlugin", "text"); - } catch (SQLException e) { log.error("Can't create database", e); throw new RuntimeException(e); } } - private void createColumnIfNotExists(Dao dao, String table, String name, String type) { - try { - final String statement = "ALTER TABLE `" + table + "` ADD COLUMN `" + name + "` " + type; - dao.executeRaw(statement); - } catch (SQLException e) { - // row already exists - } - } - @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { try { diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java index d3d9f1e640..a45ab083e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java @@ -1,14 +1,8 @@ package info.nightscout.androidaps.interfaces; -import android.os.Bundle; - -import java.util.List; - -import info.nightscout.androidaps.db.BgReading; - /** * Created by mike on 20.06.2016. */ public interface BgSourceInterface { - List processNewData(Bundle bundle); + boolean advancedFilteringSupported(); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java index 4404379196..820170dc0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java @@ -27,6 +27,10 @@ public interface ConstraintsInterface { return value; } + default Constraint isAdvancedFilteringEnabled(Constraint value) { + return value; + } + default Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { return absoluteRate; } 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 6a504e6f7e..886eeb3db7 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 @@ -65,11 +65,12 @@ public class ConfigBuilderPlugin extends PluginBase { return configBuilderPlugin; } - private static BgSourceInterface activeBgSource; + private BgSourceInterface activeBgSource; private static PumpInterface activePump; private static ProfileInterface activeProfile; private static TreatmentsInterface activeTreatments; private static APSInterface activeAPS; + private static LoopPlugin activeLoop; private static InsulinInterface activeInsulin; private static SensitivityInterface activeSensitivity; @@ -256,7 +257,7 @@ public class ConfigBuilderPlugin extends PluginBase { return commandQueue; } - public static BgSourceInterface getActiveBgSource() { + public BgSourceInterface getActiveBgSource() { return activeBgSource; } @@ -336,6 +337,9 @@ public class ConfigBuilderPlugin extends PluginBase { } this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP); + // PluginType.LOOP + activeLoop = this.determineActivePlugin(PluginType.LOOP); + // PluginType.TREATMENT activeTreatments = this.determineActivePlugin(PluginType.TREATMENT); } 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 d68d4a2edc..3d17970edc 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 @@ -92,6 +92,17 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { return value; } + @Override + public Constraint isAdvancedFilteringEnabled(Constraint value) { + BgSourceInterface bgSource = MainApp.getConfigBuilder().getActiveBgSource(); + + if (bgSource != null) { + if (!bgSource.advancedFilteringSupported()) + value.set(false, MainApp.gs(R.string.smbalwaysdisabled), this); + } + return value; + } + @Override public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java index e4a5be19b2..480646ccfc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java @@ -20,7 +20,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; -import java.util.Objects; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; @@ -33,6 +32,7 @@ import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNewBG; +import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginBase; @@ -57,9 +57,11 @@ import info.nightscout.utils.SP; public class LoopPlugin extends PluginBase { private static Logger log = LoggerFactory.getLogger(LoopPlugin.class); - private static final String CHANNEL_ID = "AndroidAPS-Openloop"; - private long lastBgTriggeredRun = 0; - private static LoopPlugin loopPlugin; + public static final String CHANNEL_ID = "AndroidAPS-Openloop"; + + long lastBgTriggeredRun = 0; + + protected static LoopPlugin loopPlugin; @NonNull public static LoopPlugin getPlugin() { @@ -155,20 +157,15 @@ public class LoopPlugin extends PluginBase { // already looped with that value return; } - PluginBase bgSource = (PluginBase) ConfigBuilderPlugin.getActiveBgSource(); - if (bgSource == null) { - // no BG source active - return; - } - if (!Objects.equals(bgReading.sourcePlugin, bgSource.getName())) { - // reading not from active BG source (likely coming in from NS) - return; - } lastBgTriggeredRun = bgReading.date; invoke("AutosenseCalculation for " + bgReading, true); } + public long suspendedTo() { + return loopSuspendedTill; + } + public void suspendTo(long endTime) { loopSuspendedTill = endTime; isSuperBolus = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java index 0f66501e58..f28a6eff8e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java @@ -14,8 +14,6 @@ import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.APSInterface; @@ -106,7 +104,6 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { } GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); - BgReading bgReading = DatabaseHelper.actualBg(); Profile profile = MainApp.getConfigBuilder().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getActivePump(); @@ -124,7 +121,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { return; } - if (glucoseStatus == null || bgReading == null) { + if (glucoseStatus == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); if (Config.logAPSResult) log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); @@ -192,11 +189,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed); inputConstraints.copyReasons(smbAllowed); - Constraint bgFiltered = new Constraint<>(bgReading.isFiltered); - if (!bgReading.isFiltered) { - bgFiltered.set(false, MainApp.gs(R.string.smbalwaysdisabled), this); - } - inputConstraints.copyReasons(bgFiltered); + Constraint advancedFiltering = new Constraint<>(!tempBasalFallback); + MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); + inputConstraints.copyReasons(advancedFiltering); Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); Profiler.log(log, "SMB data gathering", start); @@ -207,7 +202,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { lastAutosensResult.ratio, //autosensDataRatio isTempTarget, smbAllowed.value(), - bgReading.isFiltered + advancedFiltering.value() ); } catch (JSONException e) { log.error(e.getMessage()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java index 8d442d4d70..af040c8c90 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java @@ -1,33 +1,17 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.utils.NSUpload; -import info.nightscout.utils.SP; /** * Created by mike on 28.11.2017. */ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterface { - private static final Logger log = LoggerFactory.getLogger(SourceDexcomG5Plugin.class); private static SourceDexcomG5Plugin plugin = null; @@ -50,39 +34,7 @@ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterfac } @Override - public List processNewData(Bundle bundle) { - List bgReadings = new ArrayList<>(); - - String data = bundle.getString("data"); - // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle - log.debug("Received Dexcom Data", data); - - try { - JSONArray jsonArray = new JSONArray(data); - log.debug("Received Dexcom Data size:" + jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - BgReading bgReading = new BgReading(); - bgReading.value = json.getInt("m_value"); - bgReading.direction = json.getString("m_trend"); - bgReading.date = json.getLong("m_time") * 1000L; - bgReading.raw = 0; - bgReading.isFiltered = true; - bgReading.sourcePlugin = getName(); - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - if (isNew) { - bgReadings.add(bgReading); - if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading); - } - if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading); - } - } - } - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - return bgReadings; + public boolean advancedFilteringSupported() { + return true; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java index b5fb2ca294..38b891ff65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java @@ -1,15 +1,6 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; - -import com.google.common.collect.Lists; - -import java.util.Collections; -import java.util.List; - -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -38,17 +29,7 @@ public class SourceGlimpPlugin extends PluginBase implements BgSourceInterface { } @Override - public List processNewData(Bundle bundle) { - BgReading bgReading = new BgReading(); - - bgReading.value = bundle.getDouble("mySGV"); - bgReading.direction = bundle.getString("myTrend"); - bgReading.date = bundle.getLong("myTimestamp"); - bgReading.raw = 0; - bgReading.isFiltered = false; - bgReading.sourcePlugin = getName(); - - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - return isNew ? Lists.newArrayList(bgReading) : Collections.emptyList(); + public boolean advancedFilteringSupported() { + return false; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java index 196529f1d5..041b084efd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java @@ -1,20 +1,6 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -24,8 +10,6 @@ import info.nightscout.androidaps.interfaces.PluginType; * Created by mike on 05.08.2016. */ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface { - private static final Logger log = LoggerFactory.getLogger(SourceMM640gPlugin.class); - private static SourceMM640gPlugin plugin = null; public static SourceMM640gPlugin getPlugin() { @@ -44,44 +28,7 @@ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface } @Override - public List processNewData(Bundle bundle) { - List bgReadings = new ArrayList<>(); - - if (Objects.equals(bundle.getString("collection"), "entries")) { - final String data = bundle.getString("data"); - - if ((data != null) && (data.length() > 0)) { - try { - final JSONArray json_array = new JSONArray(data); - for (int i = 0; i < json_array.length(); i++) { - final JSONObject json_object = json_array.getJSONObject(i); - final String type = json_object.getString("type"); - switch (type) { - case "sgv": - BgReading bgReading = new BgReading(); - - bgReading.value = json_object.getDouble("sgv"); - bgReading.direction = json_object.getString("direction"); - bgReading.date = json_object.getLong("date"); - bgReading.raw = json_object.getDouble("sgv"); - bgReading.isFiltered = true; - bgReading.sourcePlugin = getName(); - - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - if (isNew) { - bgReadings.add(bgReading); - } - break; - default: - log.debug("Unknown entries type: " + type); - } - } - } catch (JSONException e) { - log.error("Got JSON exception: " + e); - } - } - } - - return bgReadings; + public boolean advancedFilteringSupported() { + return false; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java index c40fbb4806..c99fbcb9bb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java @@ -1,31 +1,16 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; -import info.nightscout.utils.JsonHelper; /** * Created by mike on 05.08.2016. */ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterface { - private static final Logger log = LoggerFactory.getLogger(SourceNSClientPlugin.class); private static SourceNSClientPlugin plugin = null; @@ -35,6 +20,9 @@ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterfac return plugin; } + private long lastBGTimeStamp = 0; + private boolean isAdvancedFilteringEnabled = false; + private SourceNSClientPlugin() { super(new PluginDescription() .mainType(PluginType.BGSOURCE) @@ -47,39 +35,17 @@ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterfac } @Override - public List processNewData(Bundle bundle) { - List sgvs = new ArrayList<>(); - try { - if (bundle.containsKey("sgv")) { - String sgvstring = bundle.getString("sgv"); - JSONObject sgvJson = new JSONObject(sgvstring); - BgReading bgReading = new BgReading(new NSSgv(sgvJson)); - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - if (isNew) { - sgvs.add(bgReading); - } - } - - if (bundle.containsKey("sgvs")) { - String sgvstring = bundle.getString("sgvs"); - JSONArray jsonArray = new JSONArray(sgvstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject sgvJson = jsonArray.getJSONObject(i); - BgReading bgReading = new BgReading(new NSSgv(sgvJson)); - String sourceDescription = JsonHelper.safeGetString(sgvJson, "device"); - bgReading.isFiltered = sourceDescription != null - && (sourceDescription.contains("G5 Native") || sourceDescription.contains("AndroidAPS-DexcomG5")); - bgReading.sourcePlugin = getName(); - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - if (isNew) { - sgvs.add(bgReading); - } - } - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - return sgvs; + public boolean advancedFilteringSupported() { + return isAdvancedFilteringEnabled; } + public void detectSource(String source, long timeStamp) { + if (timeStamp > lastBGTimeStamp) { + if (source.contains("G5 Native") || source.contains("AndroidAPS-DexcomG5")) + isAdvancedFilteringEnabled = true; + else + isAdvancedFilteringEnabled = false; + lastBGTimeStamp = timeStamp; + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java index 2ed3ca0cf7..13cb99d392 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java @@ -1,34 +1,16 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; - import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.utils.JsonHelper; -import info.nightscout.utils.NSUpload; -import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. */ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface { - private static final Logger log = LoggerFactory.getLogger(SourcePoctechPlugin.class); private static SourcePoctechPlugin plugin = null; @@ -50,40 +32,8 @@ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface } @Override - public List processNewData(Bundle bundle) { - List bgReadings = new ArrayList<>(); - - String data = bundle.getString("data"); - log.debug("Received Poctech Data", data); - - try { - JSONArray jsonArray = new JSONArray(data); - log.debug("Received Poctech Data size:" + jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - BgReading bgReading = new BgReading(); - bgReading.value = json.getDouble("current"); - bgReading.direction = json.getString("direction"); - bgReading.date = json.getLong("date"); - bgReading.raw = json.getDouble("raw"); - bgReading.isFiltered = false; - bgReading.sourcePlugin = getName(); - if (JsonHelper.safeGetString(json, "utils", Constants.MGDL).equals("mmol/L")) - bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL; - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - if (isNew) { - bgReadings.add(bgReading); - if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading); - } - if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading); - } - } - } - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - return bgReadings; + public boolean advancedFilteringSupported() { + return false; } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java index 2c7f399beb..fa61c9ea61 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java @@ -1,19 +1,6 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; - -import com.google.common.collect.Lists; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.List; - -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -23,9 +10,10 @@ import info.nightscout.androidaps.interfaces.PluginType; * Created by mike on 05.08.2016. */ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { - private static final Logger log = LoggerFactory.getLogger(SourceXdripPlugin.class); private static SourceXdripPlugin plugin = null; + + boolean advancedFiltering; public static SourceXdripPlugin getPlugin() { if (plugin == null) @@ -43,18 +31,11 @@ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { } @Override - public List processNewData(Bundle bundle) { - BgReading bgReading = new BgReading(); + public boolean advancedFilteringSupported() { + return advancedFiltering; + } - bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE); - bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME); - bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP); - bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); - String sourceDescription = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, ""); - bgReading.isFiltered = sourceDescription.equals("G5 Native"); - bgReading.sourcePlugin = getName(); - - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, getName()); - return isNew ? Lists.newArrayList(bgReading) : Collections.emptyList(); + public void setSource(String source) { + this.advancedFiltering = source.contains("G5 Native"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index c3188db587..47fe4acd6a 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -180,7 +180,7 @@ public class CommandQueue { if (type == Command.CommandType.SMB_BOLUS) { if (isRunning(Command.CommandType.BOLUS) || bolusInQueue()) { - log.debug("Rejecting SMB since a bolus is queued/running"); + log.debug("Rejecting SMB since a bolus is queue/running"); return false; } if (detailedBolusInfo.lastKnownBolusTime < TreatmentsPlugin.getPlugin().getLastBolusTime()) { diff --git a/app/src/main/java/info/nightscout/utils/NSUpload.java b/app/src/main/java/info/nightscout/utils/NSUpload.java index a425cc5d52..00d5e39821 100644 --- a/app/src/main/java/info/nightscout/utils/NSUpload.java +++ b/app/src/main/java/info/nightscout/utils/NSUpload.java @@ -469,8 +469,6 @@ public class NSUpload { data.put("sgv", reading.value); data.put("direction", reading.direction); data.put("type", "sgv"); - data.put("isFiltered", reading.isFiltered); - data.put("sourcePlugin", reading.sourcePlugin); } catch (JSONException e) { log.error("Unhandled exception", e); } diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java index 8d893c3af8..655cc23282 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java @@ -111,6 +111,16 @@ public class ConstraintsCheckerTest { Assert.assertEquals(Boolean.FALSE, c.value()); } + @Test + public void isAdvancedFilteringEnabledTest() throws Exception { + when(MainApp.getConfigBuilder().getActiveBgSource()).thenReturn(SourceGlimpPlugin.getPlugin()); + + Constraint c = constraintChecker.isAdvancedFilteringEnabled(); + Assert.assertEquals(true, c.getReasonList().size() == 1); // Safety + Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 1); // Safety + Assert.assertEquals(Boolean.FALSE, c.value()); + } + @Test public void isSMBModeEnabledTest() throws Exception { objectivesPlugin.objectives.get(7).setStartedOn(null); @@ -223,14 +233,13 @@ public class ConstraintsCheckerTest { // No limit by default when(SP.getDouble(R.string.key_openapsma_max_iob, 1.5d)).thenReturn(1.5d); when(SP.getString(R.string.key_age, "")).thenReturn("teenage"); + OpenAPSMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, true); OpenAPSAMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, true); - OpenAPSMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, false); - OpenAPSSMBPlugin.getPlugin().setPluginEnabled(PluginType.APS, false); // Apply all limits Constraint d = constraintChecker.getMaxIOBAllowed(); Assert.assertEquals(1.5d, d.value()); - Assert.assertEquals(d.getReasonList().toString(),2, d.getReasonList().size()); + Assert.assertEquals(3, d.getReasonList().size()); Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons()); } @@ -241,13 +250,11 @@ public class ConstraintsCheckerTest { when(SP.getDouble(R.string.key_openapssmb_max_iob, 3d)).thenReturn(3d); when(SP.getString(R.string.key_age, "")).thenReturn("teenage"); OpenAPSSMBPlugin.getPlugin().setPluginEnabled(PluginType.APS, true); - OpenAPSAMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, false); - OpenAPSMAPlugin.getPlugin().setPluginEnabled(PluginType.APS, false); // Apply all limits Constraint d = constraintChecker.getMaxIOBAllowed(); Assert.assertEquals(3d, d.value()); - Assert.assertEquals(d.getReasonList().toString(), 2, d.getReasonList().size()); + Assert.assertEquals(4, d.getReasonList().size()); Assert.assertEquals("Safety: Limiting IOB to 3.0 U because of max value in preferences", d.getMostLimitedReasons()); } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java index 4e3ab763fa..77a91046ab 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java @@ -89,6 +89,16 @@ public class SafetyPluginTest { Assert.assertEquals(Boolean.FALSE, c.value()); } + @Test + public void bgsourceShouldPreventSMBAlways() throws Exception { + when(MainApp.getConfigBuilder().getActiveBgSource()).thenReturn(SourceGlimpPlugin.getPlugin()); + + Constraint c = new Constraint<>(true); + c = safetyPlugin.isAdvancedFilteringEnabled(c); + Assert.assertEquals("Safety: SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering", c.getReasons()); + Assert.assertEquals(Boolean.FALSE, c.value()); + } + @Test public void basalRateShouldBeLimited() throws Exception { when(SP.getDouble(R.string.key_openapsma_max_basal, 1d)).thenReturn(1d); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5PluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5PluginTest.java index fcf83cd745..042aaeadbf 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5PluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5PluginTest.java @@ -14,4 +14,9 @@ public class SourceDexcomG5PluginTest { public void getPlugin() { Assert.assertNotEquals(null, SourceDexcomG5Plugin.getPlugin()); } + + @Test + public void advancedFilteringSupported() { + Assert.assertEquals(true, SourceDexcomG5Plugin.getPlugin().advancedFilteringSupported()); + } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPluginTest.java index 1729a1ef5e..045552c8da 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPluginTest.java @@ -14,4 +14,9 @@ public class SourceGlimpPluginTest { public void getPlugin() { Assert.assertNotEquals(null, SourceGlimpPlugin.getPlugin()); } + + @Test + public void advancedFilteringSupported() { + Assert.assertEquals(false, SourceGlimpPlugin.getPlugin().advancedFilteringSupported()); + } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPluginTest.java index 7cd7f36d6f..9bbe86da40 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPluginTest.java @@ -14,4 +14,9 @@ public class SourceMM640gPluginTest { public void getPlugin() { Assert.assertNotEquals(null, SourceMM640gPlugin.getPlugin()); } + + @Test + public void advancedFilteringSupported() { + Assert.assertEquals(false, SourceMM640gPlugin.getPlugin().advancedFilteringSupported()); + } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPluginTest.java index 787eb65351..3ca70a900b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPluginTest.java @@ -12,4 +12,9 @@ public class SourceNSClientPluginTest { public void getPlugin() { Assert.assertNotEquals(null, SourceNSClientPlugin.getPlugin()); } + + @Test + public void advancedFilteringSupported() { + Assert.assertEquals(false, SourceNSClientPlugin.getPlugin().advancedFilteringSupported()); + } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceXdripPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceXdripPluginTest.java index 9e0925b332..f85719dc47 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceXdripPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/Source/SourceXdripPluginTest.java @@ -1,99 +1,22 @@ package info.nightscout.androidaps.plugins.Source; -import android.os.Bundle; -import android.support.annotation.NonNull; - import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.Services.Intents; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.DatabaseHelper; - -import static junit.framework.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, DatabaseHelper.class}) public class SourceXdripPluginTest { - private SourceXdripPlugin plugin = SourceXdripPlugin.getPlugin(); - - @Before - public void prepareTest() { - PowerMockito.mockStatic(MainApp.class); - when(MainApp.gs(0)).thenReturn(""); - DatabaseHelper databaseHelper = mock(DatabaseHelper.class); - when(MainApp.getDbHelper()).thenReturn(databaseHelper); - when(databaseHelper.createIfNotExists(any(), any())).thenReturn(true); - } - @Test - public void pluginInitializes() { + public void getPlugin() { Assert.assertNotEquals(null, SourceXdripPlugin.getPlugin()); } - // TODO - @Ignore("Bundle needs to be properly mocked or Robolectrics issues with SQLite resolved") @Test - public void bgWithUnknownSourceIsMarkedUnfiltered() { - Bundle bundle = createBroadcastBundle(); - BgReading bgReadings = plugin.processNewData(bundle).get(0); - assertFalse(bgReadings.isFiltered); - } - - // TODO - @Ignore("Bundle needs to be properly mocked or Robolectrics issues with SQLite resolved") - @Test - public void bgWithSourceG5NativeIsMarkedFiltered() { - Bundle bundle = createBroadcastBundle(); - bundle.putString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "G5 Native"); - - BgReading bgReadings = plugin.processNewData(bundle).get(0); - assertTrue(bgReadings.isFiltered); - } - - /* - // TODO - @Ignore("Bundle needs to be properly mocked or Robolectrics issues with SQLite resolved") - @Test - public void bgWithWithGoodNoiseIsMarkedFiltered() { - Bundle bundle = createBroadcastBundle(); - bundle.putString(Intents.EXTRA_NOISE, "1.0"); - - BgReading bgReadings = plugin.processNewData(bundle).get(0); - assertTrue(bgReadings.isFiltered); - } - - // TODO - @Ignore("Bundle needs to be properly mocked or Robolectrics issues with SQLite resolved") - @Test - public void bgWithWithExcessiveNoiseDataIsMarkedFiltered() { - Bundle bundle = createBroadcastBundle(); - bundle.putString(Intents.EXTRA_NOISE, "80.0"); - - BgReading bgReadings = plugin.processNewData(bundle).get(0); - assertTrue(bgReadings.isFiltered); - } - */ - - @NonNull - private Bundle createBroadcastBundle() { - Bundle bundle = new Bundle(); - bundle.putDouble(Intents.EXTRA_BG_ESTIMATE, 100.0); - bundle.putString(Intents.EXTRA_BG_SLOPE_NAME, "DoubleDown"); - bundle.putLong(Intents.EXTRA_TIMESTAMP, 0L); - bundle.putDouble(Intents.EXTRA_RAW, 430.0); - return bundle; + public void advancedFilteringSupported() { + Assert.assertEquals(false, SourceXdripPlugin.getPlugin().advancedFilteringSupported()); } } \ No newline at end of file