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 9f3873cb93..7cdd287316 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -12,6 +12,8 @@ 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; @@ -21,6 +23,8 @@ 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; @@ -60,56 +64,60 @@ public class DataService extends IntentService { public DataService() { super("DataService"); - registerBus(); + MainApp.subscribe(this); } @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.getPlugin().getActiveBgSource() == null) { + if (ConfigBuilderPlugin.getActiveBgSource() == null) { xDripEnabled = true; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) { + } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) { xDripEnabled = true; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { + } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { xDripEnabled = false; nsClientEnabled = true; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { + } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = true; glimpEnabled = false; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { + } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = true; dexcomG5Enabled = false; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) { + } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = false; glimpEnabled = false; dexcomG5Enabled = true; poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) { + } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) { xDripEnabled = false; nsClientEnabled = false; mm640gEnabled = false; @@ -126,55 +134,53 @@ public class DataService extends IntentService { acceptNSData = acceptNSData || bundles.getBoolean("islocal"); } - - 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); + 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 (Config.logFunctionCalls) log.debug("onHandleIntent exit " + intent); DataReceiver.completeWakefulIntent(intent); @@ -195,167 +201,25 @@ public class DataService extends IntentService { @Override public void onDestroy() { super.onDestroy(); - MainApp.bus().unregister(this); + MainApp.unsubscribe(this); } - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); - } - - private void handleNewDataFromXDrip(Intent intent) { + private void processNewBgIntent(BgSourceInterface bgSource, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; - - 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); - } - } - } + bgSource.processNewData(bundle); } private void handleNewDataFromNSClient(Intent intent) { - Bundle bundles = intent.getExtras(); - if (bundles == null) return; - if (Config.logIncommingData) - log.debug("Got intent: " + intent.getAction()); - + Bundle bundle = intent.getExtras(); + if (bundle == null) return; if (intent.getAction().equals(Intents.ACTION_NEW_STATUS)) { - 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"); + 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"); log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName); try { if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) { @@ -377,9 +241,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 (bundles.containsKey("status")) { + if (bundle.containsKey("status")) { try { - JSONObject statusJson = new JSONObject(bundles.getString("status")); + JSONObject statusJson = new JSONObject(bundle.getString("status")); NSSettingsStatus.getInstance().setData(statusJson); if (Config.logIncommingData) log.debug("Received status: " + statusJson.toString()); @@ -396,8 +260,8 @@ public class DataService extends IntentService { } if (intent.getAction().equals(Intents.ACTION_NEW_DEVICESTATUS)) { try { - if (bundles.containsKey("devicestatus")) { - JSONObject devicestatusJson = new JSONObject(bundles.getString("devicestatus")); + if (bundle.containsKey("devicestatus")) { + JSONObject devicestatusJson = new JSONObject(bundle.getString("devicestatus")); NSDeviceStatus.getInstance().setData(devicestatusJson); if (devicestatusJson.has("pump")) { // Objectives 0 @@ -405,8 +269,8 @@ public class DataService extends IntentService { ObjectivesPlugin.saveProgress(); } } - if (bundles.containsKey("devicestatuses")) { - String devicestatusesstring = bundles.getString("devicestatuses"); + if (bundle.containsKey("devicestatuses")) { + String devicestatusesstring = bundle.getString("devicestatuses"); JSONArray jsonArray = new JSONArray(devicestatusesstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject devicestatusJson = jsonArray.getJSONObject(i); @@ -425,8 +289,8 @@ public class DataService extends IntentService { // Handle profile if (intent.getAction().equals(Intents.ACTION_NEW_PROFILE)) { try { - String activeProfile = bundles.getString("activeprofile"); - String profile = bundles.getString("profile"); + String activeProfile = bundle.getString("activeprofile"); + String profile = bundle.getString("profile"); ProfileStore profileStore = new ProfileStore(new JSONObject(profile)); NSProfilePlugin.getPlugin().storeNewProfile(profileStore); MainApp.bus().post(new EventNSProfileUpdateGUI()); @@ -439,12 +303,12 @@ public class DataService extends IntentService { if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { try { - if (bundles.containsKey("treatment")) { - JSONObject json = new JSONObject(bundles.getString("treatment")); + if (bundle.containsKey("treatment")) { + JSONObject json = new JSONObject(bundle.getString("treatment")); handleTreatmentFromNS(json, intent); } - if (bundles.containsKey("treatments")) { - String trstring = bundles.getString("treatments"); + if (bundle.containsKey("treatments")) { + String trstring = bundle.getString("treatments"); JSONArray jsonArray = new JSONArray(trstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); @@ -458,14 +322,14 @@ public class DataService extends IntentService { if (intent.getAction().equals(Intents.ACTION_REMOVED_TREATMENT)) { try { - if (bundles.containsKey("treatment")) { - String trstring = bundles.getString("treatment"); + if (bundle.containsKey("treatment")) { + String trstring = bundle.getString("treatment"); JSONObject json = new JSONObject(trstring); handleTreatmentFromNS(json); } - if (bundles.containsKey("treatments")) { - String trstring = bundles.getString("treatments"); + if (bundle.containsKey("treatments")) { + String trstring = bundle.getString("treatments"); JSONArray jsonArray = new JSONArray(trstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); @@ -478,36 +342,19 @@ public class DataService extends IntentService { } if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) { - 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); - } + SourceNSClientPlugin.getPlugin().processNewData(bundle); } if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) { try { - if (bundles.containsKey("mbg")) { - String mbgstring = bundles.getString("mbg"); + if (bundle.containsKey("mbg")) { + String mbgstring = bundle.getString("mbg"); JSONObject mbgJson = new JSONObject(mbgstring); storeMbg(mbgJson); } - if (bundles.containsKey("mbgs")) { - String sgvstring = bundles.getString("mbgs"); + if (bundle.containsKey("mbgs")) { + String sgvstring = bundle.getString("mbgs"); JSONArray jsonArray = new JSONArray(sgvstring); for (int i = 0; i < jsonArray.length(); i++) { JSONObject mbgJson = jsonArray.getJSONObject(i); @@ -522,12 +369,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, bundles); + EventNsFood evt = new EventNsFood(mode, bundle); MainApp.bus().post(evt); } if (intent.getAction().equals(Intents.ACTION_REMOVED_FOOD)) { - EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles); + EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundle); MainApp.bus().post(evt); } } @@ -545,7 +392,7 @@ public class DataService extends IntentService { MainApp.getDbHelper().deleteProfileSwitchById(_id); } - private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException { + private void handleTreatmentFromNS(JSONObject json, Intent intent) { // new DB model int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE; double insulin = JsonHelper.safeGetDouble(json, "insulin"); @@ -600,13 +447,6 @@ 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 bfbbfedbd1..272158f2ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java +++ b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java @@ -42,10 +42,6 @@ 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); } @@ -69,7 +65,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; @@ -81,7 +77,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; @@ -126,17 +122,6 @@ 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 5ddb7a80b2..d7ebfdc677 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.db; -import android.content.res.Resources; - import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @@ -38,6 +36,10 @@ 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; @@ -120,19 +122,11 @@ 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 5095195872..cbb48a69a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -28,7 +28,6 @@ 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; @@ -118,12 +117,28 @@ 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 a45ab083e7..d3d9f1e640 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java @@ -1,8 +1,14 @@ 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 { - boolean advancedFilteringSupported(); + List processNewData(Bundle bundle); } 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 820170dc0f..4404379196 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java @@ -27,10 +27,6 @@ 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 886eeb3db7..6a504e6f7e 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,12 +65,11 @@ public class ConfigBuilderPlugin extends PluginBase { return configBuilderPlugin; } - private BgSourceInterface activeBgSource; + private static 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; @@ -257,7 +256,7 @@ public class ConfigBuilderPlugin extends PluginBase { return commandQueue; } - public BgSourceInterface getActiveBgSource() { + public static BgSourceInterface getActiveBgSource() { return activeBgSource; } @@ -337,9 +336,6 @@ 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 3d17970edc..d68d4a2edc 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,17 +92,6 @@ 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 480646ccfc..e4a5be19b2 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,6 +20,7 @@ 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; @@ -32,7 +33,6 @@ 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,11 +57,9 @@ import info.nightscout.utils.SP; public class LoopPlugin extends PluginBase { private static Logger log = LoggerFactory.getLogger(LoopPlugin.class); - public static final String CHANNEL_ID = "AndroidAPS-Openloop"; - - long lastBgTriggeredRun = 0; - - protected static LoopPlugin loopPlugin; + private static final String CHANNEL_ID = "AndroidAPS-Openloop"; + private long lastBgTriggeredRun = 0; + private static LoopPlugin loopPlugin; @NonNull public static LoopPlugin getPlugin() { @@ -157,15 +155,20 @@ 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 f28a6eff8e..0f66501e58 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,6 +14,8 @@ 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; @@ -104,6 +106,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { } GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + BgReading bgReading = DatabaseHelper.actualBg(); Profile profile = MainApp.getConfigBuilder().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getActivePump(); @@ -121,7 +124,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { return; } - if (glucoseStatus == null) { + if (glucoseStatus == null || bgReading == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); if (Config.logAPSResult) log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); @@ -189,9 +192,11 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed); inputConstraints.copyReasons(smbAllowed); - Constraint advancedFiltering = new Constraint<>(!tempBasalFallback); - MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); - inputConstraints.copyReasons(advancedFiltering); + Constraint bgFiltered = new Constraint<>(bgReading.isFiltered); + if (!bgReading.isFiltered) { + bgFiltered.set(false, MainApp.gs(R.string.smbalwaysdisabled), this); + } + inputConstraints.copyReasons(bgFiltered); Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); Profiler.log(log, "SMB data gathering", start); @@ -202,7 +207,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { lastAutosensResult.ratio, //autosensDataRatio isTempTarget, smbAllowed.value(), - advancedFiltering.value() + bgReading.isFiltered ); } 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 af040c8c90..8d442d4d70 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,17 +1,33 @@ 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; @@ -34,7 +50,39 @@ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterfac } @Override - public boolean advancedFilteringSupported() { - return true; + 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; } } 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 38b891ff65..b5fb2ca294 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,6 +1,15 @@ 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; @@ -29,7 +38,17 @@ public class SourceGlimpPlugin extends PluginBase implements BgSourceInterface { } @Override - public boolean advancedFilteringSupported() { - return false; + 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(); } } 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 041b084efd..196529f1d5 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,6 +1,20 @@ 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; @@ -10,6 +24,8 @@ 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() { @@ -28,7 +44,44 @@ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface } @Override - public boolean advancedFilteringSupported() { - return false; + 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; } } 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 c99fbcb9bb..c40fbb4806 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,16 +1,31 @@ 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; @@ -20,9 +35,6 @@ 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) @@ -35,17 +47,39 @@ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterfac } @Override - public boolean advancedFilteringSupported() { - return isAdvancedFilteringEnabled; + 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 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 13cb99d392..2ed3ca0cf7 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,16 +1,34 @@ 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; @@ -32,8 +50,40 @@ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface } @Override - public boolean advancedFilteringSupported() { - return false; - } + 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; + } } 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 fa61c9ea61..2c7f399beb 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,6 +1,19 @@ 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; @@ -10,10 +23,9 @@ 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) @@ -31,11 +43,18 @@ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { } @Override - public boolean advancedFilteringSupported() { - return advancedFiltering; - } + public List processNewData(Bundle bundle) { + BgReading bgReading = new BgReading(); - public void setSource(String source) { - this.advancedFiltering = source.contains("G5 Native"); + 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(); } } 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 47fe4acd6a..c3188db587 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 queue/running"); + log.debug("Rejecting SMB since a bolus is queued/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 00d5e39821..a425cc5d52 100644 --- a/app/src/main/java/info/nightscout/utils/NSUpload.java +++ b/app/src/main/java/info/nightscout/utils/NSUpload.java @@ -469,6 +469,8 @@ 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 655cc23282..8d893c3af8 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java @@ -111,16 +111,6 @@ 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); @@ -233,13 +223,14 @@ 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(3, d.getReasonList().size()); + Assert.assertEquals(d.getReasonList().toString(),2, d.getReasonList().size()); Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons()); } @@ -250,11 +241,13 @@ 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(4, d.getReasonList().size()); + Assert.assertEquals(d.getReasonList().toString(), 2, 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 77a91046ab..4e3ab763fa 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,16 +89,6 @@ 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 042aaeadbf..fcf83cd745 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,9 +14,4 @@ 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 045552c8da..1729a1ef5e 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,9 +14,4 @@ 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 9bbe86da40..7cd7f36d6f 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,9 +14,4 @@ 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 3ca70a900b..787eb65351 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,9 +12,4 @@ 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 f85719dc47..9e0925b332 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,22 +1,99 @@ 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.plugins.Source.SourceXdripPlugin; +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; @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 getPlugin() { + public void pluginInitializes() { Assert.assertNotEquals(null, SourceXdripPlugin.getPlugin()); } + // TODO + @Ignore("Bundle needs to be properly mocked or Robolectrics issues with SQLite resolved") @Test - public void advancedFilteringSupported() { - Assert.assertEquals(false, SourceXdripPlugin.getPlugin().advancedFilteringSupported()); + 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; } } \ No newline at end of file