diff --git a/app/build.gradle b/app/build.gradle index 18cf49f1b8..b0f2c864ec 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -157,5 +157,11 @@ dependencies { androidTestCompile "com.google.dexmaker:dexmaker:1.2" androidTestCompile "com.google.dexmaker:dexmaker-mockito:1.2" compile(name:'android-edittext-validator-v1.3.4-mod', ext:'aar') + compile ('io.socket:socket.io-client:0.8.3') { + // excluding org.json which is provided by Android + exclude group: 'org.json', module: 'json' + } + compile 'com.google.code.gson:gson:2.4' + compile 'com.google.guava:guava:18.0' } \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 8f500c4421..310ad6d42c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -14,6 +14,8 @@ + + @@ -29,11 +31,14 @@ + - + @@ -42,6 +47,7 @@ + @@ -68,20 +74,44 @@ - - + + + + + + + + + + + + + + + + + + + - - - - - + + + + + + - + \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java index 52cb5d85a1..da0feef01f 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -32,12 +32,12 @@ public class Constants { public static final int CPP_MAX_PERCENTAGE = 200; // Defaults for settings - public static final String MAX_BG_DEFAULT_MGDL = "180"; - public static final String MAX_BG_DEFAULT_MMOL = "10"; - public static final String MIN_BG_DEFAULT_MGDL = "100"; - public static final String MIN_BG_DEFAULT_MMOL = "5"; - public static final String TARGET_BG_DEFAULT_MGDL = "150"; - public static final String TARGET_BG_DEFAULT_MMOL = "7"; + public static final Double MAX_BG_DEFAULT_MGDL = 180d; + public static final Double MAX_BG_DEFAULT_MMOL = 10d; + public static final Double MIN_BG_DEFAULT_MGDL = 100d; + public static final Double MIN_BG_DEFAULT_MMOL = 5d; + public static final Double TARGET_BG_DEFAULT_MGDL = 150d; + public static final Double TARGET_BG_DEFAULT_MMOL = 7d; // Very Hard Limits Ranges // First value is the Lowest and second value is the Highest a Limit can define @@ -52,4 +52,7 @@ public class Constants { //DanaR public static final double dailyLimitWarning = 0.95d; + + //NSClientInternal + public static final int MAX_LOG_LINES = 100; } diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 36931ccd5b..603b0e2699 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -36,10 +36,11 @@ import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.tabs.SlidingTabLayout; import info.nightscout.androidaps.tabs.TabPageAdapter; -import info.nightscout.utils.LogDialog; import info.nightscout.utils.ImportExportPrefs; import info.nightscout.utils.LocaleHelper; +import info.nightscout.utils.LogDialog; import info.nightscout.utils.PasswordProtection; +import info.nightscout.utils.SP; public class MainActivity extends AppCompatActivity { private static Logger log = LoggerFactory.getLogger(MainActivity.class); @@ -86,7 +87,6 @@ public class MainActivity extends AppCompatActivity { @Subscribe public void onStatusEvent(final EventRefreshGui ev) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String lang = SP.getString("language", "en"); LocaleHelper.setLocale(getApplicationContext(), lang); runOnUiThread(new Runnable() { diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 415e30c1ce..09014619cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -27,6 +27,7 @@ import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanFragment; import info.nightscout.androidaps.plugins.LocalProfile.LocalProfileFragment; import info.nightscout.androidaps.plugins.Loop.LoopFragment; import info.nightscout.androidaps.plugins.MDI.MDIFragment; +import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalFragment; import info.nightscout.androidaps.plugins.NSProfile.NSProfileFragment; import info.nightscout.androidaps.plugins.Objectives.ObjectivesFragment; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment; @@ -103,6 +104,7 @@ public class MainApp extends Application { if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this)); pluginsList.add(new PersistentNotificationPlugin(this)); + pluginsList.add(NSClientInternalFragment.getPlugin()); pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin()); diff --git a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java index d9807e9d00..99b7ee76bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java @@ -18,6 +18,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.DanaR.BluetoothDevicePreference; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.Wear.WearPlugin; @@ -36,7 +37,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - MainApp.bus().post(new EventPreferenceChange()); + MainApp.bus().post(new EventPreferenceChange(key)); if (key.equals("language")) { String lang = sharedPreferences.getString("language", "en"); LocaleHelper.setLocale(getApplicationContext(), lang); @@ -111,6 +112,10 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre if (virtualPumpPlugin != null && virtualPumpPlugin.isEnabled(PluginBase.PUMP)) { addPreferencesFromResource(R.xml.pref_virtualpump); } + NSClientInternalPlugin nsClientInternalPlugin = (NSClientInternalPlugin) MainApp.getSpecificPlugin(NSClientInternalPlugin.class); + if (nsClientInternalPlugin != null && nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) { + addPreferencesFromResource(R.xml.pref_nsclientinternal); + } if (Config.SMSCOMMUNICATORENABLED) addPreferencesFromResource(R.xml.pref_smscommunicator); addPreferencesFromResource(R.xml.pref_others); 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 100a452ede..b27a1a85b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -49,8 +49,8 @@ import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin; import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; import info.nightscout.androidaps.receivers.DataReceiver; -import info.nightscout.client.data.NSProfile; -import info.nightscout.client.data.NSSgv; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; public class DataService extends IntentService { diff --git a/app/src/main/java/info/nightscout/androidaps/Services/Intents.java b/app/src/main/java/info/nightscout/androidaps/Services/Intents.java index 921b04b936..4787838d4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/Intents.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/Intents.java @@ -11,11 +11,13 @@ public interface Intents { String ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG"; String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL"; String ACTION_NEW_STATUS = "info.nightscout.client.NEW_STATUS"; + String ACTION_QUEUE_STATUS = "info.nightscout.client.QUEUE_STATUS"; // App -> NSClient String ACTION_DATABASE = "info.nightscout.client.DBACCESS"; String ACTION_RESTART = "info.nightscout.client.RESTART"; + String ACTION_RESEND = "info.nightscout.client.RESEND"; // xDrip -> App String RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_BG_ESTIMATE"; diff --git a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java index f2a6ad0df2..ce0a94ef5a 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java +++ b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java @@ -6,9 +6,8 @@ import org.json.JSONObject; import java.util.Date; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.Round; diff --git a/app/src/main/java/info/nightscout/androidaps/data/MealData.java b/app/src/main/java/info/nightscout/androidaps/data/MealData.java index b8e73c3e00..18919c3c8a 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/MealData.java +++ b/app/src/main/java/info/nightscout/androidaps/data/MealData.java @@ -10,7 +10,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.OpenAPSAMA.Autosens; import info.nightscout.androidaps.plugins.OpenAPSAMA.AutosensResult; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; /** * Created by mike on 04.01.2017. diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index 7ce7c14678..a2a5b91870 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.data; -import android.os.Parcel; -import android.os.Parcelable; import android.text.Html; import android.text.Spanned; @@ -10,7 +8,7 @@ import org.json.JSONObject; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.Round; 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 6dcf282e6c..951d370bf3 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -10,7 +10,7 @@ import org.slf4j.LoggerFactory; import java.util.Date; import info.nightscout.androidaps.Constants; -import info.nightscout.client.data.NSSgv; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.utils.DecimalFormatter; @DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS) diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java index 99389777d5..d15ab436da 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java @@ -11,7 +11,7 @@ import java.util.Date; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; diff --git a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java index f8c2f3b829..a8afacd767 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -15,7 +15,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java new file mode 100644 index 0000000000..38331ca581 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.events; + +/** + * Created by mike on 17.02.2017. + */ + +public class EventConfigBuilderChange { +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java index 61feaa0897..3e270e8a1b 100644 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java @@ -1,6 +1,6 @@ package info.nightscout.androidaps.events; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; /** * Created by mike on 04.06.2016. diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java index b4b430bb1e..76da0a4e67 100644 --- a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java +++ b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java @@ -1,7 +1,25 @@ package info.nightscout.androidaps.events; +import info.nightscout.androidaps.MainApp; + /** * Created by mike on 19.06.2016. */ public class EventPreferenceChange { + public String changedKey; + public EventPreferenceChange(String key) { + changedKey = key; + } + + public EventPreferenceChange(int resourceID) { + changedKey = MainApp.sResources.getString(resourceID); + } + + public boolean isChanged(int id) { + return changedKey.equals(MainApp.sResources.getString(id)); + } + + public boolean isChanged(String id) { + return changedKey.equals(id); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java new file mode 100644 index 0000000000..ab697e4840 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java @@ -0,0 +1,50 @@ +package info.nightscout.androidaps.events; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; + +/** + * Created by mike on 19.02.2017. + */ + +public class EventPumpStatusChanged { + public static final int CONNECTING = 0; + public static final int CONNECTED = 1; + public static final int PERFORMING = 2; + public static final int DISCONNECTING = 3; + public static final int DISCONNECTED = 4; + + public int sStatus = DISCONNECTED; + public int sSecondsElapsed = 0; + public String sPerfomingAction = ""; + + public EventPumpStatusChanged(int status) { + sStatus = status; + sSecondsElapsed = 0; + } + + public EventPumpStatusChanged(int status, int secondsElapsed) { + sStatus = status; + sSecondsElapsed = secondsElapsed; + } + + public EventPumpStatusChanged(String action) { + sStatus = PERFORMING; + sSecondsElapsed = 0; + sPerfomingAction = action; + } + + public String textStatus() { + if (sStatus == CONNECTING) + return String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), sSecondsElapsed); + else if (sStatus == CONNECTED) + return MainApp.sResources.getString(R.string.connected); + else if (sStatus == PERFORMING) + return sPerfomingAction; + else if (sStatus == DISCONNECTING) + return MainApp.sResources.getString(R.string.disconnecting); + else if (sStatus == DISCONNECTED) + return ""; + return ""; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java index ae28697834..0924723776 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java @@ -2,7 +2,7 @@ package info.nightscout.androidaps.interfaces; import android.support.annotation.Nullable; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; /** * Created by mike on 14.06.2016. diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java index 550b05103e..6b6d8e856f 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java @@ -8,8 +8,7 @@ import java.util.Date; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.TempBasal; -import info.nightscout.androidaps.plugins.Loop.APSResult; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; /** * Created by mike on 04.06.2016. @@ -30,8 +29,8 @@ public interface PumpInterface { int setNewBasalProfile(NSProfile profile); boolean isThisProfileSet(NSProfile profile); - Date lastStatusTime(); - void updateStatus(String reason); + Date lastDataTime(); + void refreshDataFromPump(String reason); double getBaseBasalRate(); // base basal rate, not temp basal double getTempBasalAbsoluteRate(); @@ -52,7 +51,9 @@ public interface PumpInterface { JSONObject getJSONStatus(); String deviceID(); + // Pump capabilities PumpDescription getPumpDescription(); - public String shortStatus(boolean veryShort); + // Short info for SMS, Wear etc + String shortStatus(boolean veryShort); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java index a170ea0e02..3331228f65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java @@ -28,6 +28,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.PlusMinusEditText; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; public class FillDialog extends DialogFragment implements OnClickListener { @@ -72,10 +73,9 @@ public class FillDialog extends DialogFragment implements OnClickListener { Button button3 = (Button) view.findViewById(R.id.fill_preset_button3); View divider = view.findViewById(R.id.fill_preset_divider); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - amount1 = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button1", "0.3")))); - amount2 = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button2", "0")))); - amount3 = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button3", "0")))); + amount1 = SP.getDouble("fill_button1", 0.3); + amount2 = SP.getDouble("fill_button2", 0d); + amount3 = SP.getDouble("fill_button3", 0d); if(amount1 >0) { button1.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java index ea0ef114e8..f29d6e18ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.SafeParse; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java index 4c93b88102..b7fcab69a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java @@ -3,11 +3,9 @@ package info.nightscout.androidaps.plugins.Careportal.Dialogs; import android.app.Activity; import android.content.DialogInterface; -import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; -import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AlertDialog; @@ -42,7 +40,6 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Date; - import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -53,10 +50,11 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; -import info.nightscout.client.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.PlusMinusEditText; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; import info.nightscout.utils.Translator; @@ -391,7 +389,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick JSONObject gatherData() { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String enteredBy = SP.getString("careportal_enteredby", ""); JSONObject data = new JSONObject(); try { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/CircadianPercentageProfile/CircadianPercentageProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/CircadianPercentageProfile/CircadianPercentageProfilePlugin.java index 56aa813c29..201b2ac37b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/CircadianPercentageProfile/CircadianPercentageProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/CircadianPercentageProfile/CircadianPercentageProfilePlugin.java @@ -15,8 +15,9 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; @@ -66,7 +67,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte @Override public String getNameShort() { String name = MainApp.sResources.getString(R.string.circadian_percentage_profile_shortname); - if (!name.trim().isEmpty()){ + if (!name.trim().isEmpty()) { //only if translation exists return name; } @@ -125,75 +126,19 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte void loadSettings() { if (Config.logPrefsChange) log.debug("Loading stored settings"); - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - if (settings.contains(SETTINGS_PREFIX + "mgdl")) - try { - mgdl = settings.getBoolean(SETTINGS_PREFIX + "mgdl", true); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else mgdl = true; - if (settings.contains(SETTINGS_PREFIX + "mmol")) - try { - mmol = settings.getBoolean(SETTINGS_PREFIX + "mmol", false); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else mmol = false; - if (settings.contains(SETTINGS_PREFIX + "dia")) - try { - dia = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "dia", "3")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else dia = 3d; - if (settings.contains(SETTINGS_PREFIX + "targetlow")) - try { - targetLow = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "targetlow", "80")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else targetLow = 80d; - if (settings.contains(SETTINGS_PREFIX + "targethigh")) - try { - targetHigh = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "targethigh", "120")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else targetHigh = 120d; - if (settings.contains(SETTINGS_PREFIX + "percentage")) - try { - percentage = SafeParse.stringToInt(settings.getString(SETTINGS_PREFIX + "percentage", "100")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else percentage = 100; - - if (settings.contains(SETTINGS_PREFIX + "timeshift")) - try { - timeshift = SafeParse.stringToInt(settings.getString(SETTINGS_PREFIX + "timeshift", "0")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else timeshift = 0; + mgdl = SP.getBoolean(SETTINGS_PREFIX + "mgdl", true); + mmol = SP.getBoolean(SETTINGS_PREFIX + "mmol", false); + dia = SP.getDouble(SETTINGS_PREFIX + "dia", 3d); + targetLow = SP.getDouble(SETTINGS_PREFIX + "targetlow", 80d); + targetHigh = SP.getDouble(SETTINGS_PREFIX + "targethigh", 120d); + percentage = SP.getInt(SETTINGS_PREFIX + "percentage", 100); + timeshift = SP.getInt(SETTINGS_PREFIX + "timeshift", 0); for (int i = 0; i < 24; i++) { - try { - basebasal[i] = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "basebasal" + i, DecimalFormatter.to2Decimal(basebasal[i]))); - } catch (Exception e) { - log.debug(e.getMessage()); - } - try { - baseic[i] = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "baseic" + i, DecimalFormatter.to2Decimal(baseic[i]))); - } catch (Exception e) { - log.debug(e.getMessage()); - } - try { - baseisf[i] = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "baseisf" + i, DecimalFormatter.to2Decimal(baseisf[i]))); - } catch (Exception e) { - log.debug(e.getMessage()); - } + basebasal[i] = SP.getDouble(SETTINGS_PREFIX + "basebasal" + i, basebasal[i]); + baseic[i] = SP.getDouble(SETTINGS_PREFIX + "baseic" + i, baseic[i]); + baseisf[i] = SP.getDouble(SETTINGS_PREFIX + "baseisf" + i, baseisf[i]); } @@ -227,7 +172,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte } profile.put("carbratio", icArray); - JSONArray isfArray = new JSONArray(); + JSONArray isfArray = new JSONArray(); for (int i = 0; i < 24; i++) { isfArray.put(new JSONObject().put("timeAsSeconds", i * 60 * 60).put("value", baseisf[(offset + i) % 24] * 100d / percentage)); } @@ -259,7 +204,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte } private void performLimitCheck() { - if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE){ + if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) { String msg = String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Percentage"); log.error(msg); MainApp.getConfigBuilder().uploadError(msg); @@ -289,13 +234,15 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte return profileString(baseisf, 0, 100, false); } - String baseBasalString() {return profileString(basebasal, 0, 100, true);} + String baseBasalString() { + return profileString(basebasal, 0, 100, true); + } - public double baseBasalSum(){ + public double baseBasalSum() { return sum(basebasal); } - public double percentageBasalSum(){ + public double percentageBasalSum() { double result = 0; for (int i = 0; i < basebasal.length; i++) { result += SafeParse.stringToDouble(DecimalFormatter.to2Decimal(basebasal[i] * percentage / 100d)); @@ -304,7 +251,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte } - public static double sum(double values[]){ + public static double sum(double values[]) { double result = 0; for (int i = 0; i < values.length; i++) { result += values[i]; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java index bf9f3fb0b2..4b0ce3bd0a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.BgSourceInterface; @@ -197,6 +198,7 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase { onEnabledCategoryChanged(plugin, type); configBuilderPlugin.storeSettings(); MainApp.bus().post(new EventRefreshGui(true)); + MainApp.bus().post(new EventConfigBuilderChange()); getPlugin().logPluginStatus(); } }); 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 a0b2a7b3b0..a10c182ad4 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 @@ -54,8 +54,9 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperAc import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.client.data.DbLogger; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.BatteryLevel; import info.nightscout.utils.DateUtil; /** @@ -390,13 +391,13 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain } @Override - public Date lastStatusTime() { - return activePump.lastStatusTime(); + public Date lastDataTime() { + return activePump.lastDataTime(); } @Override - public void updateStatus(String reason) { - activePump.updateStatus(reason); + public void refreshDataFromPump(String reason) { + activePump.refreshDataFromPump(reason); } @Override @@ -482,7 +483,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain carbs = applyCarbsConstraints(carbs); BolusProgressDialog bolusProgressDialog = null; - if (context != null ) { + if (context != null) { bolusProgressDialog = new BolusProgressDialog(); bolusProgressDialog.setInsulin(insulin); bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); @@ -682,7 +683,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain public String deviceID() { if (activePump != null) return activePump.deviceID(); - else return "Unknown"; + else return "No Pump active!"; } @Override @@ -966,6 +967,8 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain requested.put("temp", "absolute"); deviceStatus.enacted.put("requested", requested); } + } else { + log.debug("OpenAPS data too old to upload"); } if (activePump != null) { deviceStatus.device = "openaps://" + deviceID(); @@ -973,11 +976,17 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain if (pumpstatus != null) { deviceStatus.pump = getJSONStatus(); } - - deviceStatus.created_at = DateUtil.toISOString(new Date()); - - deviceStatus.sendToNSClient(); } + + int batteryLevel = BatteryLevel.getBatteryLevel(); + if (batteryLevel != BatteryLevel.lastUploadedLevel) { + JSONObject uploaderBattery = new JSONObject(); + uploaderBattery.put("uploaderBattery", batteryLevel); + deviceStatus.uploaderBattery = uploaderBattery; + BatteryLevel.lastUploadedLevel = batteryLevel; + } + deviceStatus.created_at = DateUtil.toISOString(new Date()); + deviceStatus.sendToNSClient(); } catch (JSONException e) { e.printStackTrace(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRFragment.java index 7c59790e35..c0faeddef1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRFragment.java @@ -24,13 +24,12 @@ import java.util.Date; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog; import info.nightscout.androidaps.plugins.DanaR.History.DanaRHistoryActivity; import info.nightscout.androidaps.plugins.DanaR.History.DanaRStatsActivity; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; @@ -166,18 +165,18 @@ public class DanaRFragment extends Fragment implements FragmentBase { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged c) { Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread( new Runnable() { @Override public void run() { - if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) + if (c.sStatus == EventPumpStatusChanged.CONNECTING) btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); - else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) + else if (c.sStatus == EventPumpStatusChanged.CONNECTED) btConnectionView.setText("{fa-bluetooth}"); - else + else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED) btConnectionView.setText("{fa-bluetooth-b}"); } } @@ -195,11 +194,6 @@ public class DanaRFragment extends Fragment implements FragmentBase { updateGUI(); } - @Subscribe - public void onStatusEvent(final EventPreferenceChange s) { - updateGUI(); - } - // GUI functions private void updateGUI() { Activity activity = getActivity(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPlugin.java index 7889471d6b..556c6d9770 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPlugin.java @@ -40,7 +40,7 @@ import info.nightscout.androidaps.plugins.NSProfile.NSProfilePlugin; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.Round; @@ -285,12 +285,12 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf } @Override - public Date lastStatusTime() { + public Date lastDataTime() { return getDanaRPump().lastConnection; } @Override - public void updateStatus(String reason) { + public void refreshDataFromPump(String reason) { if (!isConnected() && !isConnecting()) { doConnect(reason); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPump.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPump.java index 1e9808becd..c68bac86ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPump.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/DanaRPump.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.DanaR; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -11,9 +8,9 @@ import java.text.DecimalFormat; import java.util.Date; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.client.data.NSProfile; -import info.nightscout.utils.SafeParse; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; /** * Created by mike on 04.07.2016. @@ -122,8 +119,7 @@ public class DanaRPump { // Evening / 17:00–21:59 // Night / 22:00–5:59 - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - double dia = SafeParse.stringToDouble(SP.getString("danarprofile_dia", "3")); + double dia = SP.getDouble(R.string.key_danarprofile_dia, 3d); try { json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Dialogs/ProfileViewDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Dialogs/ProfileViewDialog.java index 3cb21f4221..1cedf012fd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Dialogs/ProfileViewDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Dialogs/ProfileViewDialog.java @@ -15,12 +15,10 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DecimalFormatter; /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRHistoryActivity.java index 4056943e70..994d5b629e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRHistoryActivity.java @@ -32,19 +32,18 @@ import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Date; import java.util.List; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DanaRHistoryRecord; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.ToastUtils; @@ -307,7 +306,7 @@ public class DanaRHistoryActivity extends Activity { case RecordTypes.RECORD_TYPE_DAILY: holder.dailybasal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + "U"); holder.dailybolus.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + "U"); - holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()+ record.getRecordDailyBasal()) + "U"); + holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus() + record.getRecordDailyBasal()) + "U"); holder.time.setText(DateUtil.dateString(record.getRecordDate())); holder.time.setVisibility(View.VISIBLE); holder.value.setVisibility(View.GONE); @@ -435,21 +434,12 @@ public class DanaRHistoryActivity extends Activity { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged s) { runOnUiThread( new Runnable() { @Override public void run() { - if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { - statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed)); - log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s"); - } else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) { - statusView.setText(MainApp.sResources.getString(R.string.connected)); - log.debug("EventDanaRConnectionStatus: Connected"); - } else { - statusView.setText(MainApp.sResources.getString(R.string.disconnected)); - log.debug("EventDanaRConnectionStatus: Disconnected"); - } + statusView.setText(s.textStatus()); } } ); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRNSHistorySync.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRNSHistorySync.java index 327465eba2..205d83df9c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRNSHistorySync.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRNSHistorySync.java @@ -14,7 +14,7 @@ import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.ToastUtils; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRStatsActivity.java index 674213d66f..7d5bf0c548 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/History/DanaRStatsActivity.java @@ -48,12 +48,12 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DanaRHistoryRecord; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.SafeParse; @@ -68,11 +68,11 @@ public class DanaRStatsActivity extends Activity { private Handler mHandler; private static HandlerThread mHandlerThread; - TextView statusView, statsMessage,totalBaseBasal2; + TextView statusView, statsMessage, totalBaseBasal2; EditText totalBaseBasal; Button reloadButton; LinearLayoutManager llm; - TableLayout tl,ctl,etl; + TableLayout tl, ctl, etl; String TBB; double magicNumber; DecimalFormat decimalFormat; @@ -118,15 +118,15 @@ public class DanaRStatsActivity extends Activity { public boolean dispatchTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { View myView = getCurrentFocus(); - if ( myView instanceof EditText) { + if (myView instanceof EditText) { Rect rect = new Rect(); myView.getGlobalVisibleRect(rect); - if (!rect.contains((int)event.getRawX(), (int)event.getRawY())) { + if (!rect.contains((int) event.getRawX(), (int) event.getRawY())) { myView.clearFocus(); } } } - return super.dispatchTouchEvent( event ); + return super.dispatchTouchEvent(event); } ServiceConnection mConnection = new ServiceConnection() { @@ -172,11 +172,11 @@ public class DanaRStatsActivity extends Activity { totalBaseBasal.setText(TBB); ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile(); - if (pi != null && pi instanceof CircadianPercentageProfilePlugin){ - double cppTBB = ((CircadianPercentageProfilePlugin)pi).baseBasalSum(); + if (pi != null && pi instanceof CircadianPercentageProfilePlugin) { + double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum(); totalBaseBasal.setText(decimalFormat.format(cppTBB)); SharedPreferences.Editor edit = preferences.edit(); - edit.putString("TBB",totalBaseBasal.getText().toString()); + edit.putString("TBB", totalBaseBasal.getText().toString()); edit.commit(); TBB = preferences.getString("TBB", ""); } @@ -312,7 +312,7 @@ public class DanaRStatsActivity extends Activity { totalBaseBasal.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if(actionId== EditorInfo.IME_ACTION_DONE){ + if (actionId == EditorInfo.IME_ACTION_DONE) { totalBaseBasal.clearFocus(); return true; } @@ -323,11 +323,11 @@ public class DanaRStatsActivity extends Activity { totalBaseBasal.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { - if(hasFocus){ + if (hasFocus) { totalBaseBasal.getText().clear(); } else { SharedPreferences.Editor edit = preferences.edit(); - edit.putString("TBB",totalBaseBasal.getText().toString()); + edit.putString("TBB", totalBaseBasal.getText().toString()); edit.commit(); TBB = preferences.getString("TBB", ""); loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY); @@ -362,15 +362,14 @@ public class DanaRStatsActivity extends Activity { cleanTable(etl); DateFormat df = new SimpleDateFormat("dd.MM."); - if(TextUtils.isEmpty(TBB)) { + if (TextUtils.isEmpty(TBB)) { totalBaseBasal.setError("Please Enter Total Base Basal"); return; - } - else { + } else { magicNumber = SafeParse.stringToDouble(TBB); } - magicNumber *=2; + magicNumber *= 2; totalBaseBasal2.setText(decimalFormat.format(magicNumber)); int i = 0; @@ -379,45 +378,45 @@ public class DanaRStatsActivity extends Activity { double weighted05 = 0d; double weighted07 = 0d; - for (DanaRHistoryRecord record: historyList) { - double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); + for (DanaRHistoryRecord record : historyList) { + double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal(); // Create the table row TableRow tr = new TableRow(DanaRStatsActivity.this); - if(i%2!=0) tr.setBackgroundColor(Color.DKGRAY); - tr.setId(100+i); + if (i % 2 != 0) tr.setBackgroundColor(Color.DKGRAY); + tr.setId(100 + i); tr.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); // Here create the TextView dynamically TextView labelDATE = new TextView(DanaRStatsActivity.this); - labelDATE.setId(200+i); + labelDATE.setId(200 + i); labelDATE.setText(df.format(new Date(record.getRecordDate()))); labelDATE.setTextColor(Color.WHITE); tr.addView(labelDATE); TextView labelBASAL = new TextView(DanaRStatsActivity.this); - labelBASAL.setId(300+i); + labelBASAL.setId(300 + i); labelBASAL.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + " U"); labelBASAL.setTextColor(Color.WHITE); tr.addView(labelBASAL); TextView labelBOLUS = new TextView(DanaRStatsActivity.this); - labelBOLUS.setId(400+i); + labelBOLUS.setId(400 + i); labelBOLUS.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + " U"); labelBOLUS.setTextColor(Color.WHITE); tr.addView(labelBOLUS); TextView labelTDD = new TextView(DanaRStatsActivity.this); - labelTDD.setId(500+i); + labelTDD.setId(500 + i); labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U"); labelTDD.setTextColor(Color.WHITE); tr.addView(labelTDD); TextView labelRATIO = new TextView(DanaRStatsActivity.this); - labelRATIO.setId(600+i); - labelRATIO.setText(Math.round(100*tdd/magicNumber) +" %"); + labelRATIO.setId(600 + i); + labelRATIO.setText(Math.round(100 * tdd / magicNumber) + " %"); labelRATIO.setTextColor(Color.WHITE); tr.addView(labelRATIO); @@ -431,28 +430,28 @@ public class DanaRStatsActivity extends Activity { // Create the cumtable row TableRow ctr = new TableRow(DanaRStatsActivity.this); - if(i%2==0) ctr.setBackgroundColor(Color.DKGRAY); - ctr.setId(700+i); + if (i % 2 == 0) ctr.setBackgroundColor(Color.DKGRAY); + ctr.setId(700 + i); ctr.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); // Here create the TextView dynamically TextView labelDAYS = new TextView(DanaRStatsActivity.this); - labelDAYS.setId(800+i); + labelDAYS.setId(800 + i); labelDAYS.setText("" + i); labelDAYS.setTextColor(Color.WHITE); ctr.addView(labelDAYS); TextView labelCUMTDD = new TextView(DanaRStatsActivity.this); - labelCUMTDD.setId(900+i); - labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum/i) + " U"); + labelCUMTDD.setId(900 + i); + labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum / i) + " U"); labelCUMTDD.setTextColor(Color.WHITE); ctr.addView(labelCUMTDD); TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this); - labelCUMRATIO.setId(1000+i); - labelCUMRATIO.setText(Math.round(100*sum/i/magicNumber) + " %"); + labelCUMRATIO.setId(1000 + i); + labelCUMRATIO.setText(Math.round(100 * sum / i / magicNumber) + " %"); labelCUMRATIO.setTextColor(Color.WHITE); ctr.addView(labelCUMRATIO); @@ -462,7 +461,7 @@ public class DanaRStatsActivity extends Activity { TableLayout.LayoutParams.WRAP_CONTENT)); } - if (historyList.size()<3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000*60*60*24))))){ + if (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24))))) { statsMessage.setVisibility(View.VISIBLE); statsMessage.setText(getString(R.string.danar_stats_olddata_Message)); @@ -474,38 +473,38 @@ public class DanaRStatsActivity extends Activity { i = 0; - for (DanaRHistoryRecord record: historyList) { - double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); - if(i == 0 ) { + for (DanaRHistoryRecord record : historyList) { + double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal(); + if (i == 0) { weighted03 = tdd; weighted05 = tdd; weighted07 = tdd; } else { - weighted07 = (weighted07*0.3 + tdd*0.7); - weighted05 = (weighted05*0.5 + tdd*0.5); - weighted03 = (weighted03*0.7 + tdd*0.3); + weighted07 = (weighted07 * 0.3 + tdd * 0.7); + weighted05 = (weighted05 * 0.5 + tdd * 0.5); + weighted03 = (weighted03 * 0.7 + tdd * 0.3); } i++; } // Create the exptable row TableRow etr = new TableRow(DanaRStatsActivity.this); - if(i%2!=0) etr.setBackgroundColor(Color.DKGRAY); - etr.setId(1100+i); + if (i % 2 != 0) etr.setBackgroundColor(Color.DKGRAY); + etr.setId(1100 + i); etr.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); // Here create the TextView dynamically TextView labelWEIGHT = new TextView(DanaRStatsActivity.this); - labelWEIGHT.setId(1200+i); + labelWEIGHT.setId(1200 + i); labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7"); labelWEIGHT.setTextColor(Color.WHITE); etr.addView(labelWEIGHT); TextView labelEXPTDD = new TextView(DanaRStatsActivity.this); - labelEXPTDD.setId(1300+i); + labelEXPTDD.setId(1300 + i); labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03) + " U\n" + DecimalFormatter.to2Decimal(weighted05) + " U\n" + DecimalFormatter.to2Decimal(weighted07) + " U"); @@ -513,10 +512,10 @@ public class DanaRStatsActivity extends Activity { etr.addView(labelEXPTDD); TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this); - labelEXPRATIO.setId(1400+i); - labelEXPRATIO.setText(Math.round(100*weighted03/magicNumber) +" %\n" - + Math.round(100*weighted05/magicNumber) +" %\n" - + Math.round(100*weighted07/magicNumber) +" %"); + labelEXPRATIO.setId(1400 + i); + labelEXPRATIO.setText(Math.round(100 * weighted03 / magicNumber) + " %\n" + + Math.round(100 * weighted05 / magicNumber) + " %\n" + + Math.round(100 * weighted07 / magicNumber) + " %"); labelEXPRATIO.setTextColor(Color.WHITE); etr.addView(labelEXPRATIO); @@ -549,21 +548,12 @@ public class DanaRStatsActivity extends Activity { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged c) { runOnUiThread( new Runnable() { @Override public void run() { - if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { - statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed)); - log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s"); - } else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) { - statusView.setText(MainApp.sResources.getString(R.string.connected)); - log.debug("EventDanaRConnectionStatus: Connected"); - } else { - statusView.setText(MainApp.sResources.getString(R.string.disconnected)); - log.debug("EventDanaRConnectionStatus: Disconnected"); - } + statusView.setText(c.textStatus()); } } ); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Services/ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Services/ExecutionService.java index e7ecb4c742..323b139bda 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Services/ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/Services/ExecutionService.java @@ -33,8 +33,8 @@ import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaR.DanaRPump; import info.nightscout.androidaps.plugins.DanaR.SerialIOThread; @@ -78,18 +78,17 @@ import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusBolusExtended; import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusTempBasal; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; public class ExecutionService extends Service { private static Logger log = LoggerFactory.getLogger(ExecutionService.class); - private SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); private String devName; private SerialIOThread mSerialIOThread; @@ -118,7 +117,7 @@ public class ExecutionService extends Service { if (mSerialIOThread != null) { mSerialIOThread.disconnect("BT disconnection broadcast"); } - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); } } } @@ -188,7 +187,7 @@ public class ExecutionService extends Service { } public void connect(String from) { - if (danaRPump.password != -1 && danaRPump.password != SafeParse.stringToInt(SP.getString("danar_password", "-1"))) { + if (danaRPump.password != -1 && danaRPump.password != SP.getInt(R.string.key_danar_password, -1)) { ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error); return; } @@ -208,7 +207,7 @@ public class ExecutionService extends Service { long startTime = new Date().getTime(); while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) { long secondsElapsed = (new Date().getTime() - startTime) / 1000L; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTING, (int) secondsElapsed)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); if (Config.logDanaBTComm) log.debug("connect waiting " + secondsElapsed + "sec from: " + from); try { @@ -227,18 +226,19 @@ public class ExecutionService extends Service { mSerialIOThread.disconnect("Recreate SerialIOThread"); } mSerialIOThread = new SerialIOThread(mRfcommSocket); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTED, 0)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0)); if (!getPumpStatus()) { mSerialIOThread.disconnect("getPumpStatus failed"); waitMsec(3000); if (!MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginBase.PUMP)) return; getBTSocketForSelectedPump(); + startTime = new Date().getTime(); } } } if (!isConnected()) { - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); log.error("Pump connection timed out"); } connectionInProgress = false; @@ -247,7 +247,7 @@ public class ExecutionService extends Service { } private void getBTSocketForSelectedPump() { - devName = SP.getString("danar_bt_name", ""); + devName = SP.getString(MainApp.sResources.getString(R.string.key_danar_bt_name), ""); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { @@ -280,7 +280,7 @@ public class ExecutionService extends Service { private boolean getPumpStatus() { try { - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.gettingpumpstatus))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus))); MsgStatus statusMsg = new MsgStatus(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); @@ -341,7 +341,7 @@ public class ExecutionService extends Service { danaRPump.lastConnection = now; MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); - MainApp.getConfigBuilder().uploadDeviceStatus(60); + MainApp.getConfigBuilder().uploadDeviceStatus(15); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); @@ -357,46 +357,46 @@ public class ExecutionService extends Service { public boolean tempBasal(int percent, int durationInHours) { connect("tempBasal"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingtempbasal))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean tempBasalStop() { connect("tempBasalStop"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingtempbasal))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean extendedBolus(double insulin, int durationInHalfHours) { connect("extendedBolus"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingextendedbolus))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean extendedBolusStop() { connect("extendedBolusStop"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingextendedbolus))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean bolus(Double amount, int carbs, Treatment t) { bolusingTreatment = t; MsgBolusStart start = new MsgBolusStart(amount); - MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables MsgBolusStop stop = new MsgBolusStop(amount, t); connect("bolus"); @@ -406,6 +406,7 @@ public class ExecutionService extends Service { Calendar time = Calendar.getInstance(); mSerialIOThread.sendMessage(new MsgSetCarbsEntry(time, carbs)); } + MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables MainApp.bus().post(new EventDanaRBolusStart()); if (!stop.stopped) { @@ -416,7 +417,7 @@ public class ExecutionService extends Service { } while (!stop.stopped && !start.failed) { waitMsec(100); - if (progress.lastReceive != 0 && (new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm + if ((new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm stop.stopped = true; stop.forced = true; log.debug("Communication stopped"); @@ -501,7 +502,7 @@ public class ExecutionService extends Service { public boolean updateBasalsInPump(final NSProfile profile) { connect("updateBasalsInPump"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.updatingbasalrates))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates))); double[] basal = buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); mSerialIOThread.sendMessage(msgSet); @@ -509,7 +510,7 @@ public class ExecutionService extends Service { mSerialIOThread.sendMessage(msgActivate); danaRPump.lastSettingsRead = new Date(0); // force read full settings getPumpStatus(); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgBolusProgress.java index aa8a77f7bf..fe30fea1be 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgBolusProgress.java @@ -30,7 +30,7 @@ public class MsgBolusProgress extends MessageBase { this(); this.amount = amount; this.t = t; - lastReceive = 0; + lastReceive = new Date().getTime(); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSetCarbsEntry.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSetCarbsEntry.java index 667070c684..ed3e3ac455 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSetCarbsEntry.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSetCarbsEntry.java @@ -27,7 +27,7 @@ public class MsgSetCarbsEntry extends MessageBase { AddParamByte((byte) 0x43); //?? AddParamInt(amount); if (Config.logDanaMessageDetail) - log.debug("Set carb entry: " + amount + " date " + time.toString()); + log.debug("Set carb entry: " + amount + " date " + time.getTime().toString()); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/events/EventDanaRConnectionStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/events/EventDanaRConnectionStatus.java deleted file mode 100644 index fef8868d2b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/events/EventDanaRConnectionStatus.java +++ /dev/null @@ -1,23 +0,0 @@ -package info.nightscout.androidaps.plugins.DanaR.events; - -public class EventDanaRConnectionStatus { - public static final int CONNECTING = 0; - public static final int CONNECTED = 1; - public static final int DISCONNECTED = 2; - public static final int PERFORMING = 3; - - public int sStatus = DISCONNECTED; - public int sSecondsElapsed = 0; - public String sAction = ""; - - public EventDanaRConnectionStatus(int status, int secondsElapsed) { - sStatus = status; - sSecondsElapsed = secondsElapsed; - } - - public EventDanaRConnectionStatus(int status, int secondsElapsed, String action) { - sStatus = status; - sSecondsElapsed = secondsElapsed; - sAction = action; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanFragment.java index 4142b43ff6..af4d12e5ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanFragment.java @@ -24,11 +24,10 @@ import java.util.Date; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaRKorean.History.DanaRHistoryActivity; import info.nightscout.androidaps.plugins.DanaRKorean.History.DanaRStatsActivity; @@ -163,18 +162,18 @@ public class DanaRKoreanFragment extends Fragment implements FragmentBase { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged c) { Activity activity = getActivity(); if (activity != null) { activity.runOnUiThread( new Runnable() { @Override public void run() { - if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) + if (c.sStatus == EventPumpStatusChanged.CONNECTING) btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); - else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) + else if (c.sStatus == EventPumpStatusChanged.CONNECTED) btConnectionView.setText("{fa-bluetooth}"); - else + else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED) btConnectionView.setText("{fa-bluetooth-b}"); } } @@ -192,11 +191,6 @@ public class DanaRKoreanFragment extends Fragment implements FragmentBase { updateGUI(); } - @Subscribe - public void onStatusEvent(final EventPreferenceChange s) { - updateGUI(); - } - // GUI functions private void updateGUI() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPlugin.java index 1384be16e2..683e2d8f1b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPlugin.java @@ -40,7 +40,7 @@ import info.nightscout.androidaps.plugins.NSProfile.NSProfilePlugin; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.Round; @@ -72,6 +72,8 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints return sDanaRKoreanPump; } + String textStatus = ""; + public DanaRKoreanPlugin() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false); @@ -285,12 +287,12 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints } @Override - public Date lastStatusTime() { + public Date lastDataTime() { return getDanaRPump().lastConnection; } @Override - public void updateStatus(String reason) { + public void refreshDataFromPump(String reason) { if (!isConnected() && !isConnecting()) { doConnect(reason); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPump.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPump.java index b29d9a4347..b8a7016956 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPump.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPump.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.DanaRKorean; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -11,9 +8,9 @@ import java.text.DecimalFormat; import java.util.Date; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.client.data.NSProfile; -import info.nightscout.utils.SafeParse; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; /** * Created by mike on 04.07.2016. @@ -115,8 +112,7 @@ public class DanaRKoreanPump { // Evening / 17:00–21:59 // Night / 22:00–5:59 - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - double dia = SafeParse.stringToDouble(SP.getString("danarprofile_dia", "3")); + double dia = SP.getDouble(R.string.key_danarprofile_dia, 3d); try { json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRHistoryActivity.java index d23cff488b..158d0b43cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRHistoryActivity.java @@ -32,20 +32,19 @@ import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Date; import java.util.List; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DanaRHistoryRecord; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.DanaR.History.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.ToastUtils; @@ -306,7 +305,7 @@ public class DanaRHistoryActivity extends Activity { case RecordTypes.RECORD_TYPE_DAILY: holder.dailybasal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + "U"); holder.dailybolus.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + "U"); - holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()+ record.getRecordDailyBasal()) + "U"); + holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus() + record.getRecordDailyBasal()) + "U"); holder.time.setText(DateUtil.dateString(record.getRecordDate())); holder.time.setVisibility(View.VISIBLE); holder.value.setVisibility(View.GONE); @@ -434,21 +433,12 @@ public class DanaRHistoryActivity extends Activity { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged c) { runOnUiThread( new Runnable() { @Override public void run() { - if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { - statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed)); - log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s"); - } else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) { - statusView.setText(MainApp.sResources.getString(R.string.connected)); - log.debug("EventDanaRConnectionStatus: Connected"); - } else { - statusView.setText(MainApp.sResources.getString(R.string.disconnected)); - log.debug("EventDanaRConnectionStatus: Disconnected"); - } + statusView.setText(c.textStatus()); } } ); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRStatsActivity.java index d8b5390fbd..0c0e2f112b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/History/DanaRStatsActivity.java @@ -48,11 +48,11 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DanaRHistoryRecord; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService; import info.nightscout.utils.DecimalFormatter; @@ -68,11 +68,11 @@ public class DanaRStatsActivity extends Activity { private Handler mHandler; private static HandlerThread mHandlerThread; - TextView statusView, statsMessage,totalBaseBasal2; + TextView statusView, statsMessage, totalBaseBasal2; EditText totalBaseBasal; Button reloadButton; LinearLayoutManager llm; - TableLayout tl,ctl,etl; + TableLayout tl, ctl, etl; String TBB; double magicNumber; DecimalFormat decimalFormat; @@ -118,15 +118,15 @@ public class DanaRStatsActivity extends Activity { public boolean dispatchTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { View myView = getCurrentFocus(); - if ( myView instanceof EditText) { + if (myView instanceof EditText) { Rect rect = new Rect(); myView.getGlobalVisibleRect(rect); - if (!rect.contains((int)event.getRawX(), (int)event.getRawY())) { + if (!rect.contains((int) event.getRawX(), (int) event.getRawY())) { myView.clearFocus(); } } } - return super.dispatchTouchEvent( event ); + return super.dispatchTouchEvent(event); } ServiceConnection mConnection = new ServiceConnection() { @@ -172,11 +172,11 @@ public class DanaRStatsActivity extends Activity { totalBaseBasal.setText(TBB); ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile(); - if (pi != null && pi instanceof CircadianPercentageProfilePlugin){ - double cppTBB = ((CircadianPercentageProfilePlugin)pi).baseBasalSum(); + if (pi != null && pi instanceof CircadianPercentageProfilePlugin) { + double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum(); totalBaseBasal.setText(decimalFormat.format(cppTBB)); SharedPreferences.Editor edit = preferences.edit(); - edit.putString("TBB",totalBaseBasal.getText().toString()); + edit.putString("TBB", totalBaseBasal.getText().toString()); edit.commit(); TBB = preferences.getString("TBB", ""); } @@ -312,7 +312,7 @@ public class DanaRStatsActivity extends Activity { totalBaseBasal.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if(actionId== EditorInfo.IME_ACTION_DONE){ + if (actionId == EditorInfo.IME_ACTION_DONE) { totalBaseBasal.clearFocus(); return true; } @@ -323,11 +323,11 @@ public class DanaRStatsActivity extends Activity { totalBaseBasal.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { - if(hasFocus){ + if (hasFocus) { totalBaseBasal.getText().clear(); } else { SharedPreferences.Editor edit = preferences.edit(); - edit.putString("TBB",totalBaseBasal.getText().toString()); + edit.putString("TBB", totalBaseBasal.getText().toString()); edit.commit(); TBB = preferences.getString("TBB", ""); loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY); @@ -362,15 +362,14 @@ public class DanaRStatsActivity extends Activity { cleanTable(etl); DateFormat df = new SimpleDateFormat("dd.MM."); - if(TextUtils.isEmpty(TBB)) { + if (TextUtils.isEmpty(TBB)) { totalBaseBasal.setError("Please Enter Total Base Basal"); return; - } - else { + } else { magicNumber = SafeParse.stringToDouble(TBB); } - magicNumber *=2; + magicNumber *= 2; totalBaseBasal2.setText(decimalFormat.format(magicNumber)); int i = 0; @@ -379,45 +378,45 @@ public class DanaRStatsActivity extends Activity { double weighted05 = 0d; double weighted07 = 0d; - for (DanaRHistoryRecord record: historyList) { - double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); + for (DanaRHistoryRecord record : historyList) { + double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal(); // Create the table row TableRow tr = new TableRow(DanaRStatsActivity.this); - if(i%2!=0) tr.setBackgroundColor(Color.DKGRAY); - tr.setId(100+i); + if (i % 2 != 0) tr.setBackgroundColor(Color.DKGRAY); + tr.setId(100 + i); tr.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); // Here create the TextView dynamically TextView labelDATE = new TextView(DanaRStatsActivity.this); - labelDATE.setId(200+i); + labelDATE.setId(200 + i); labelDATE.setText(df.format(new Date(record.getRecordDate()))); labelDATE.setTextColor(Color.WHITE); tr.addView(labelDATE); TextView labelBASAL = new TextView(DanaRStatsActivity.this); - labelBASAL.setId(300+i); + labelBASAL.setId(300 + i); labelBASAL.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + " U"); labelBASAL.setTextColor(Color.WHITE); tr.addView(labelBASAL); TextView labelBOLUS = new TextView(DanaRStatsActivity.this); - labelBOLUS.setId(400+i); + labelBOLUS.setId(400 + i); labelBOLUS.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + " U"); labelBOLUS.setTextColor(Color.WHITE); tr.addView(labelBOLUS); TextView labelTDD = new TextView(DanaRStatsActivity.this); - labelTDD.setId(500+i); + labelTDD.setId(500 + i); labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U"); labelTDD.setTextColor(Color.WHITE); tr.addView(labelTDD); TextView labelRATIO = new TextView(DanaRStatsActivity.this); - labelRATIO.setId(600+i); - labelRATIO.setText(Math.round(100*tdd/magicNumber) +" %"); + labelRATIO.setId(600 + i); + labelRATIO.setText(Math.round(100 * tdd / magicNumber) + " %"); labelRATIO.setTextColor(Color.WHITE); tr.addView(labelRATIO); @@ -431,28 +430,28 @@ public class DanaRStatsActivity extends Activity { // Create the cumtable row TableRow ctr = new TableRow(DanaRStatsActivity.this); - if(i%2==0) ctr.setBackgroundColor(Color.DKGRAY); - ctr.setId(700+i); + if (i % 2 == 0) ctr.setBackgroundColor(Color.DKGRAY); + ctr.setId(700 + i); ctr.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); // Here create the TextView dynamically TextView labelDAYS = new TextView(DanaRStatsActivity.this); - labelDAYS.setId(800+i); + labelDAYS.setId(800 + i); labelDAYS.setText("" + i); labelDAYS.setTextColor(Color.WHITE); ctr.addView(labelDAYS); TextView labelCUMTDD = new TextView(DanaRStatsActivity.this); - labelCUMTDD.setId(900+i); - labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum/i) + " U"); + labelCUMTDD.setId(900 + i); + labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum / i) + " U"); labelCUMTDD.setTextColor(Color.WHITE); ctr.addView(labelCUMTDD); TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this); - labelCUMRATIO.setId(1000+i); - labelCUMRATIO.setText(Math.round(100*sum/i/magicNumber) + " %"); + labelCUMRATIO.setId(1000 + i); + labelCUMRATIO.setText(Math.round(100 * sum / i / magicNumber) + " %"); labelCUMRATIO.setTextColor(Color.WHITE); ctr.addView(labelCUMRATIO); @@ -462,7 +461,7 @@ public class DanaRStatsActivity extends Activity { TableLayout.LayoutParams.WRAP_CONTENT)); } - if (historyList.size()<3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000*60*60*24))))){ + if (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24))))) { statsMessage.setVisibility(View.VISIBLE); statsMessage.setText(getString(R.string.danar_stats_olddata_Message)); @@ -474,38 +473,38 @@ public class DanaRStatsActivity extends Activity { i = 0; - for (DanaRHistoryRecord record: historyList) { - double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); - if(i == 0 ) { + for (DanaRHistoryRecord record : historyList) { + double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal(); + if (i == 0) { weighted03 = tdd; weighted05 = tdd; weighted07 = tdd; } else { - weighted07 = (weighted07*0.3 + tdd*0.7); - weighted05 = (weighted05*0.5 + tdd*0.5); - weighted03 = (weighted03*0.7 + tdd*0.3); + weighted07 = (weighted07 * 0.3 + tdd * 0.7); + weighted05 = (weighted05 * 0.5 + tdd * 0.5); + weighted03 = (weighted03 * 0.7 + tdd * 0.3); } i++; } // Create the exptable row TableRow etr = new TableRow(DanaRStatsActivity.this); - if(i%2!=0) etr.setBackgroundColor(Color.DKGRAY); - etr.setId(1100+i); + if (i % 2 != 0) etr.setBackgroundColor(Color.DKGRAY); + etr.setId(1100 + i); etr.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); // Here create the TextView dynamically TextView labelWEIGHT = new TextView(DanaRStatsActivity.this); - labelWEIGHT.setId(1200+i); + labelWEIGHT.setId(1200 + i); labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7"); labelWEIGHT.setTextColor(Color.WHITE); etr.addView(labelWEIGHT); TextView labelEXPTDD = new TextView(DanaRStatsActivity.this); - labelEXPTDD.setId(1300+i); + labelEXPTDD.setId(1300 + i); labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03) + " U\n" + DecimalFormatter.to2Decimal(weighted05) + " U\n" + DecimalFormatter.to2Decimal(weighted07) + " U"); @@ -513,10 +512,10 @@ public class DanaRStatsActivity extends Activity { etr.addView(labelEXPTDD); TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this); - labelEXPRATIO.setId(1400+i); - labelEXPRATIO.setText(Math.round(100*weighted03/magicNumber) +" %\n" - + Math.round(100*weighted05/magicNumber) +" %\n" - + Math.round(100*weighted07/magicNumber) +" %"); + labelEXPRATIO.setId(1400 + i); + labelEXPRATIO.setText(Math.round(100 * weighted03 / magicNumber) + " %\n" + + Math.round(100 * weighted05 / magicNumber) + " %\n" + + Math.round(100 * weighted07 / magicNumber) + " %"); labelEXPRATIO.setTextColor(Color.WHITE); etr.addView(labelEXPRATIO); @@ -549,21 +548,12 @@ public class DanaRStatsActivity extends Activity { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged c) { runOnUiThread( new Runnable() { @Override public void run() { - if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { - statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed)); - log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s"); - } else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) { - statusView.setText(MainApp.sResources.getString(R.string.connected)); - log.debug("EventDanaRConnectionStatus: Connected"); - } else { - statusView.setText(MainApp.sResources.getString(R.string.disconnected)); - log.debug("EventDanaRConnectionStatus: Disconnected"); - } + statusView.setText(c.textStatus()); } } ); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/Services/ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/Services/ExecutionService.java index 0bad19b38e..1a0267dd67 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/Services/ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/Services/ExecutionService.java @@ -8,11 +8,9 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.content.SharedPreferences; import android.os.Binder; import android.os.IBinder; import android.os.PowerManager; -import android.preference.PreferenceManager; import com.squareup.otto.Subscribe; @@ -33,6 +31,7 @@ import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.DanaR.comm.MsgBolusProgress; @@ -59,7 +58,6 @@ import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTempBasalStop; import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTime; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump; @@ -75,16 +73,15 @@ import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgSettingShippingInf import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusBasic; import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusBolusExtended; import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusTempBasal; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.client.data.NSProfile; -import info.nightscout.utils.SafeParse; +import info.nightscout.utils.SP; import info.nightscout.utils.ToastUtils; public class ExecutionService extends Service { private static Logger log = LoggerFactory.getLogger(ExecutionService.class); - private SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); private String devName; private SerialIOThread mSerialIOThread; @@ -113,7 +110,7 @@ public class ExecutionService extends Service { if (mSerialIOThread != null) { mSerialIOThread.disconnect("BT disconnection broadcast"); } - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); } } } @@ -183,7 +180,7 @@ public class ExecutionService extends Service { } public void connect(String from) { - if (danaRKoreanPump.password != -1 && danaRKoreanPump.password != SafeParse.stringToInt(SP.getString("danar_password", "-1"))) { + if (danaRKoreanPump.password != -1 && danaRKoreanPump.password != SP.getInt(R.string.key_danar_password, -1)) { ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error); return; } @@ -203,7 +200,7 @@ public class ExecutionService extends Service { long startTime = new Date().getTime(); while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) { long secondsElapsed = (new Date().getTime() - startTime) / 1000L; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTING, (int) secondsElapsed)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); if (Config.logDanaBTComm) log.debug("connect waiting " + secondsElapsed + "sec from: " + from); try { @@ -222,18 +219,19 @@ public class ExecutionService extends Service { mSerialIOThread.disconnect("Recreate SerialIOThread"); } mSerialIOThread = new SerialIOThread(mRfcommSocket); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTED, 0)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED)); if (!getPumpStatus()) { mSerialIOThread.disconnect("getPumpStatus failed"); waitMsec(3000); if (!MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginBase.PUMP)) return; getBTSocketForSelectedPump(); + startTime = new Date().getTime(); } } } if (!isConnected()) { - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); log.error("Pump connection timed out"); } connectionInProgress = false; @@ -242,7 +240,7 @@ public class ExecutionService extends Service { } private void getBTSocketForSelectedPump() { - devName = SP.getString("danar_bt_name", ""); + devName = SP.getString(MainApp.sResources.getString(R.string.key_danar_bt_name), ""); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { @@ -275,7 +273,7 @@ public class ExecutionService extends Service { private boolean getPumpStatus() { try { - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.gettingpumpstatus))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus))); //MsgStatus statusMsg = new MsgStatus(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); @@ -334,7 +332,7 @@ public class ExecutionService extends Service { danaRKoreanPump.lastConnection = now; MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); - MainApp.getConfigBuilder().uploadDeviceStatus(60); + MainApp.getConfigBuilder().uploadDeviceStatus(15); if (danaRKoreanPump.dailyTotalUnits > danaRKoreanPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { log.debug("Approaching daily limit: " + danaRKoreanPump.dailyTotalUnits + "/" + danaRKoreanPump.maxDailyTotalUnits); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); @@ -350,47 +348,46 @@ public class ExecutionService extends Service { public boolean tempBasal(int percent, int durationInHours) { connect("tempBasal"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingtempbasal))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean tempBasalStop() { connect("tempBasalStop"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingtempbasal))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean extendedBolus(double insulin, int durationInHalfHours) { connect("extendedBolus"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingextendedbolus))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean extendedBolusStop() { connect("extendedBolusStop"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingextendedbolus))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } public boolean bolus(Double amount, int carbs, Treatment t) { bolusingTreatment = t; MsgBolusStart start = new MsgBolusStart(amount); - MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables MsgBolusStop stop = new MsgBolusStop(amount, t); connect("bolus"); @@ -400,6 +397,8 @@ public class ExecutionService extends Service { Calendar time = Calendar.getInstance(); mSerialIOThread.sendMessage(new MsgSetCarbsEntry(time, carbs)); } + + MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables MainApp.bus().post(new EventDanaRBolusStart()); if (!stop.stopped) { @@ -410,7 +409,7 @@ public class ExecutionService extends Service { } while (!stop.stopped && !start.failed) { waitMsec(100); - if (progress.lastReceive != 0 && (new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm + if ((new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm stop.stopped = true; stop.forced = true; log.debug("Communication stopped"); @@ -495,13 +494,13 @@ public class ExecutionService extends Service { public boolean updateBasalsInPump(final NSProfile profile) { connect("updateBasalsInPump"); if (!isConnected()) return false; - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.updatingbasalrates))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates))); double[] basal = buildDanaRProfileRecord(profile); MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal); mSerialIOThread.sendMessage(msgSet); danaRKoreanPump.lastSettingsRead = new Date(0); // force read full settings getPumpStatus(); - MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/LocalProfile/LocalProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/LocalProfile/LocalProfilePlugin.java index 91c994cdbb..a4c65e83dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/LocalProfile/LocalProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/LocalProfile/LocalProfilePlugin.java @@ -15,8 +15,8 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.androidaps.plugins.SimpleProfile.SimpleProfileFragment; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; /** @@ -63,7 +63,7 @@ public class LocalProfilePlugin implements PluginBase, ProfileInterface { @Override public String getNameShort() { String name = MainApp.sResources.getString(R.string.localprofile_shortname); - if (!name.trim().isEmpty()){ + if (!name.trim().isEmpty()) { //only if translation exists return name; } @@ -117,117 +117,48 @@ public class LocalProfilePlugin implements PluginBase, ProfileInterface { private void loadSettings() { if (Config.logPrefsChange) log.debug("Loading stored settings"); - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - if (settings.contains("LocalProfile" + "mgdl")) - try { - mgdl = settings.getBoolean("LocalProfile" + "mgdl", false); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else mgdl = false; - if (settings.contains("LocalProfile" + "mmol")) - try { - mmol = settings.getBoolean("LocalProfile" + "mmol", true); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else mmol = true; - if (settings.contains("LocalProfile" + "dia")) - try { - dia = SafeParse.stringToDouble(settings.getString("LocalProfile" + "dia", "3")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else dia = 3d; - if (settings.contains("LocalProfile" + "ic")) - try { - ic = new JSONArray(settings.getString("LocalProfile" + "ic", DEFAULTARRAY)); - } catch (Exception e) { - log.debug(e.getMessage()); - try { - ic = new JSONArray(DEFAULTARRAY); - } catch (JSONException e1) { - e1.printStackTrace(); - } - } - else { + mgdl = SP.getBoolean("LocalProfile" + "mgdl", false); + mmol = SP.getBoolean("LocalProfile" + "mmol", true); + dia = SP.getDouble("LocalProfile" + "dia", 3d); + try { + ic = new JSONArray(SP.getString("LocalProfile" + "ic", DEFAULTARRAY)); + } catch (JSONException e1) { try { ic = new JSONArray(DEFAULTARRAY); - } catch (JSONException e) { - e.printStackTrace(); + } catch (JSONException e2) { } } - if (settings.contains("LocalProfile" + "isf")) - try { - isf = new JSONArray(settings.getString("LocalProfile" + "isf", DEFAULTARRAY)); - } catch (Exception e) { - log.debug(e.getMessage()); - try { - isf = new JSONArray(DEFAULTARRAY); - } catch (JSONException e1) { - e1.printStackTrace(); - } - } - else { + try { + isf = new JSONArray(SP.getString("LocalProfile" + "isf", DEFAULTARRAY)); + } catch (JSONException e1) { try { isf = new JSONArray(DEFAULTARRAY); - } catch (JSONException e) { - e.printStackTrace(); + } catch (JSONException e2) { } } - if (settings.contains("LocalProfile" + "basal")) - try { - basal = new JSONArray(settings.getString("LocalProfile" + "basal", DEFAULTARRAY)); - } catch (Exception e) { - log.debug(e.getMessage()); - try { - basal = new JSONArray(DEFAULTARRAY); - } catch (JSONException e1) { - e1.printStackTrace(); - } - } - else { + try { + basal = new JSONArray(SP.getString("LocalProfile" + "basal", DEFAULTARRAY)); + } catch (JSONException e1) { try { basal = new JSONArray(DEFAULTARRAY); - } catch (JSONException e) { - e.printStackTrace(); + } catch (JSONException e2) { } } - if (settings.contains("LocalProfile" + "targetlow")) - try { - targetLow = new JSONArray(settings.getString("LocalProfile" + "targetlow", DEFAULTARRAY)); - } catch (Exception e) { - log.debug(e.getMessage()); - try { - targetLow = new JSONArray(DEFAULTARRAY); - } catch (JSONException e1) { - e1.printStackTrace(); - } - } - else { + try { + targetLow = new JSONArray(SP.getString("LocalProfile" + "targetlow", DEFAULTARRAY)); + } catch (JSONException e1) { try { targetLow = new JSONArray(DEFAULTARRAY); - } catch (JSONException e) { - e.printStackTrace(); + } catch (JSONException e2) { } } - if (settings.contains("LocalProfile" + "targethigh")) - try { - targetHigh = new JSONArray(settings.getString("LocalProfile" + "targethigh", DEFAULTARRAY)); - } catch (Exception e) { - log.debug(e.getMessage()); - try { - targetHigh = new JSONArray(DEFAULTARRAY); - } catch (JSONException e1) { - e1.printStackTrace(); - } - } - else { + try { + targetHigh = new JSONArray(SP.getString("LocalProfile" + "targethigh", DEFAULTARRAY)); + } catch (JSONException e1) { try { targetHigh = new JSONArray(DEFAULTARRAY); - } catch (JSONException e) { - e.printStackTrace(); + } catch (JSONException e2) { } } createConvertedProfile(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java index 85a9f39b09..0d4f5b423f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.Loop; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import org.json.JSONException; @@ -10,12 +9,9 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.Services.Intents; -import info.nightscout.client.data.DbLogger; +import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; /* { @@ -382,6 +378,7 @@ public class DeviceStatus { public JSONObject enacted = null; public JSONObject suggested = null; public JSONObject iob = null; + public JSONObject uploaderBattery = null; public String created_at = null; public JSONObject mongoRecord () { @@ -395,6 +392,7 @@ public class DeviceStatus { if (enacted != null) openaps.put("enacted", enacted); if (suggested != null) openaps.put("suggested", suggested); if (iob != null) openaps.put("iob", iob); + if (uploaderBattery != null) openaps.put("uploaderBattery", uploaderBattery); record.put("openaps", openaps); } if (created_at != null) record.put("created_at" , created_at); 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 76eb14eb1a..59ddcfc3b8 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 @@ -228,7 +228,7 @@ public class LoopPlugin implements PluginBase { } MainApp.bus().post(new EventLoopUpdateGui()); - MainApp.getConfigBuilder().uploadDeviceStatus(120); + MainApp.getConfigBuilder().uploadDeviceStatus(60); } finally { if (Config.logFunctionCalls) log.debug("invoke end"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIPlugin.java index ce48a966de..534a77b766 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIPlugin.java @@ -7,7 +7,6 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.SQLException; import java.util.Date; import info.nightscout.androidaps.BuildConfig; @@ -19,10 +18,7 @@ import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; -import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpFragment; -import info.nightscout.androidaps.plugins.VirtualPump.events.EventVirtualPumpUpdateGui; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; /** @@ -147,12 +143,12 @@ public class MDIPlugin implements PluginBase, PumpInterface { } @Override - public Date lastStatusTime() { + public Date lastDataTime() { return new Date(); } @Override - public void updateStatus(String reason) { + public void refreshDataFromPump(String reason) { // do nothing } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalFragment.java new file mode 100644 index 0000000000..42ddcc9ba8 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalFragment.java @@ -0,0 +1,171 @@ +package info.nightscout.androidaps.plugins.NSClientInternal; + + +import android.app.Activity; +import android.graphics.Paint; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.text.Html; +import android.text.Spanned; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.ScrollView; +import android.widget.TextView; + +import com.squareup.otto.Subscribe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.FragmentBase; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; +import info.nightscout.utils.SP; + +public class NSClientInternalFragment extends Fragment implements FragmentBase, View.OnClickListener, CompoundButton.OnCheckedChangeListener { + private static Logger log = LoggerFactory.getLogger(NSClientInternalFragment.class); + + static NSClientInternalPlugin nsClientInternalPlugin; + + static public NSClientInternalPlugin getPlugin() { + if (nsClientInternalPlugin == null) { + nsClientInternalPlugin = new NSClientInternalPlugin(); + } + return nsClientInternalPlugin; + } + + private TextView logTextView; + private TextView queueTextView; + private TextView urlTextView; + private TextView statusTextView; + private TextView clearlog; + private TextView restart; + private TextView delivernow; + private TextView clearqueue; + private TextView showqueue; + private ScrollView logScrollview; + private CheckBox autoscrollCheckbox; + private CheckBox pausedCheckbox; + + String status = ""; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false); + + logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview); + autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll); + autoscrollCheckbox.setChecked(getPlugin().autoscroll); + autoscrollCheckbox.setOnCheckedChangeListener(this); + pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused); + pausedCheckbox.setChecked(getPlugin().paused); + pausedCheckbox.setOnCheckedChangeListener(this); + logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log); + queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue); + urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url); + statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status); + + clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog); + clearlog.setOnClickListener(this); + clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + restart = (TextView) view.findViewById(R.id.nsclientinternal_restart); + restart.setOnClickListener(this); + restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow); + delivernow.setOnClickListener(this); + delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue); + clearqueue.setOnClickListener(this); + clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue); + showqueue.setOnClickListener(this); + showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + + updateGUI(); + return view; + } + + @Override + public void onClick(View view) { + switch (view.getId()) { + case R.id.nsclientinternal_restart: + MainApp.bus().post(new EventNSClientRestart()); + break; + case R.id.nsclientinternal_delivernow: + getPlugin().resend("GUI"); + break; + case R.id.nsclientinternal_clearlog: + getPlugin().clearLog(); + break; + case R.id.nsclientinternal_clearqueue: + getPlugin().queue().reset(); + break; + case R.id.nsclientinternal_showqueue: + MainApp.bus().post(new EventNSClientNewLog("QUEUE", getPlugin().queue().textList())); + break; + } + } + + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + switch (buttonView.getId()) { + case R.id.nsclientinternal_paused: + SP.putBoolean(R.string.key_nsclientinternal_paused, isChecked); + getPlugin().paused = isChecked; + MainApp.bus().post(new EventPreferenceChange(R.string.key_nsclientinternal_paused)); + updateGUI(); + break; + case R.id.nsclientinternal_autoscroll: + SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked); + getPlugin().autoscroll = isChecked; + updateGUI(); + break; + } + } + + @Override + public void onPause() { + super.onPause(); + MainApp.bus().unregister(this); + } + + @Override + public void onResume() { + super.onResume(); + MainApp.bus().register(this); + updateGUI(); + } + + @Subscribe + public void onStatusEvent(final EventNSClientUpdateGUI ev) { + updateGUI(); + } + + private void updateGUI() { + Activity activity = getActivity(); + if (activity != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + logTextView.setText(getPlugin().textLog); + if (getPlugin().autoscroll) { + logScrollview.fullScroll(ScrollView.FOCUS_DOWN); + } + urlTextView.setText(getPlugin().url()); + Spanned queuetext = Html.fromHtml(MainApp.sResources.getString(R.string.queue) + " " + getPlugin().queue().size() + ""); + queueTextView.setText(queuetext); + statusTextView.setText(getPlugin().status); + } + }); + } + + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalPlugin.java new file mode 100644 index 0000000000..46830deadc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalPlugin.java @@ -0,0 +1,217 @@ +package info.nightscout.androidaps.plugins.NSClientInternal; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.content.SharedPreferences; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.IBinder; +import android.preference.PreferenceManager; +import android.text.Html; +import android.text.Spanned; +import android.text.TextUtils; + +import com.squareup.otto.Subscribe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventAppExit; +import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.interfaces.PumpDescription; +import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; +import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; +import info.nightscout.utils.SP; + +public class NSClientInternalPlugin implements PluginBase { + private static Logger log = LoggerFactory.getLogger(NSClientInternalPlugin.class); + + boolean fragmentEnabled = false; + boolean fragmentVisible = false; + + static public Handler handler; + static private HandlerThread handlerThread; + + public List listLog = new ArrayList(); + public Spanned textLog = Html.fromHtml(""); + + public boolean paused = false; + public boolean autoscroll = true; + + public String status = ""; + + public NSClientService nsClientService = null; + + public NSClientInternalPlugin() { + MainApp.bus().register(this); + paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false); + autoscroll = SP.getBoolean(R.string.key_nsclientinternal_autoscroll, true); + + if (handler == null) { + handlerThread = new HandlerThread(NSClientInternalPlugin.class.getSimpleName() + "Handler"); + handlerThread.start(); + handler = new Handler(handlerThread.getLooper()); + } + + Context context = MainApp.instance().getApplicationContext(); + Intent intent = new Intent(context, NSClientService.class); + context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + } + + @Override + public int getType() { + return PluginBase.GENERAL; + } + + @Override + public String getFragmentClass() { + return NSClientInternalFragment.class.getName(); + } + + @Override + public String getName() { + return MainApp.sResources.getString(R.string.nsclientinternal); + } + + @Override + public String getNameShort() { + String name = MainApp.sResources.getString(R.string.nsclientinternal_shortname); + if (!name.trim().isEmpty()) { + //only if translation exists + return name; + } + // use long name as fallback + return getName(); + } + + @Override + public boolean isEnabled(int type) { + return type == GENERAL && fragmentEnabled; + } + + @Override + public boolean isVisibleInTabs(int type) { + return type == GENERAL && fragmentVisible; + } + + @Override + public boolean canBeHidden(int type) { + return true; + } + + @Override + public void setFragmentEnabled(int type, boolean fragmentEnabled) { + if (type == GENERAL) this.fragmentEnabled = fragmentEnabled; + } + + @Override + public void setFragmentVisible(int type, boolean fragmentVisible) { + if (type == GENERAL) this.fragmentVisible = fragmentVisible; + } + + ServiceConnection mConnection = new ServiceConnection() { + + public void onServiceDisconnected(ComponentName name) { + log.debug("Service is disconnected"); + nsClientService = null; + } + + public void onServiceConnected(ComponentName name, IBinder service) { + log.debug("Service is connected"); + NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service; + nsClientService = mLocalBinder.getServiceInstance(); + } + }; + + @SuppressWarnings("UnusedParameters") + @Subscribe + public void onStatusEvent(final EventAppExit e) { + if (nsClientService != null) + MainApp.instance().getApplicationContext().unbindService(mConnection); + } + + @Subscribe + public void onStatusEvent(final EventPreferenceChange s) { + //TODO + } + + @Subscribe + public void onStatusEvent(final EventNSClientNewLog ev) { + addToLog(ev); + log.debug(ev.action + " " + ev.logText); + } + + @Subscribe + public void onStatusEvent(final EventNSClientRestart ev) { + if (nsClientService != null) + nsClientService.restart(); + } + + @Subscribe + public void onStatusEvent(final EventNSClientStatus ev) { + status = ev.status; + MainApp.bus().post(new EventNSClientUpdateGUI()); + } + + public void clearLog() { + handler.post(new Runnable() { + @Override + public void run() { + listLog = new ArrayList(); + updateLog(); + } + }); + } + + private void addToLog(final EventNSClientNewLog ev) { + handler.post(new Runnable() { + @Override + public void run() { + SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); + listLog.add(ev); + // remove the first line if log is too large + if (listLog.size() >= Constants.MAX_LOG_LINES) { + listLog.remove(0); + } + updateLog(); + } + }); + } + + private void updateLog() { + Spanned newTextLog = Html.fromHtml(""); + for (EventNSClientNewLog log : listLog) { + newTextLog = (Spanned) TextUtils.concat(newTextLog, log.toHtml()); + } + textLog = newTextLog; + MainApp.bus().post(new EventNSClientUpdateGUI()); + } + + public void resend(String reason) { + if (nsClientService != null) + nsClientService.resend(reason); + } + + public UploadQueue queue() { + return NSClientService.uploadQueue; + } + + public String url() { + return NSClientService.nsURL; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java new file mode 100644 index 0000000000..ded00ffb85 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java @@ -0,0 +1,159 @@ +package info.nightscout.androidaps.plugins.NSClientInternal; + +import android.content.SharedPreferences; +import android.preference.PreferenceManager; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastQueueStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.data.DbRequest; +import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; +import info.nightscout.utils.SP; + +/** + * Created by mike on 21.02.2016. + */ +public class UploadQueue { + private static Logger log = LoggerFactory.getLogger(UploadQueue.class); + + public static HashMap queue = null; + + public UploadQueue() { + loadMap(); + } + + public static String status() { + return "QUEUE: " + queue.size(); + } + + public static int size() { + return queue.size(); + } + + public static void add(final DbRequest dbr) { + NSClientService.handler.post(new Runnable() { + @Override + public void run() { + log.debug("QUEUE adding: " + dbr.data.toString()); + queue.put(dbr.hash(), dbr); + saveMap(); + } + }); + } + + public static void reset() { + NSClientService.handler.post(new Runnable() { + @Override + public void run() { + log.debug("QUEUE Reset"); + queue.clear(); + log.debug(status()); + } + }); + } + + public static void removeID(final JSONObject record) { + NSClientService.handler.post(new Runnable() { + @Override + public void run() { + try { + long id = -1L; + if (record.has("NSCLIENT_ID")) { + id = record.getLong("NSCLIENT_ID"); + } else { + return; + } + Iterator> iter = queue.entrySet().iterator(); + while (iter.hasNext()) { + DbRequest dbr = iter.next().getValue(); + JSONObject data = dbr.data; + long nsclientId = -1; + if (data.has("NSCLIENT_ID")) { + nsclientId = data.getLong("NSCLIENT_ID"); + if (nsclientId == id) { + log.debug("Removing item from UploadQueue"); + iter.remove(); + log.debug(UploadQueue.status()); + return; + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + saveMap(); + } + }); + } + + public static void removeID(final String action, final String _id) { + NSClientService.handler.post(new Runnable() { + @Override + public void run() { + Iterator> iter = queue.entrySet().iterator(); + while (iter.hasNext()) { + DbRequest dbr = iter.next().getValue(); + if (dbr.action.equals(action) && dbr._id.equals(_id)) { + log.debug("Removing item from UploadQueue"); + iter.remove(); + return; + } else { + log.debug("Failed removing item from UploadQueue"); + } + } + saveMap(); + } + }); + } + + final static String KEY = "UploadQueue"; + + private static void saveMap() { + JSONArray jsonArray = new JSONArray(); + Iterator> iter = queue.entrySet().iterator(); + while (iter.hasNext()) { + DbRequest dbr = iter.next().getValue(); + jsonArray.put(dbr.toJSON()); + } + SP.putString(KEY, jsonArray.toString()); + } + + private void loadMap() { + queue = new HashMap(); + try { + String jsonString = SP.getString(KEY, (new JSONArray()).toString()); + JSONArray jsonArray = new JSONArray(jsonString); + for (int i=0; i < jsonArray.length(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + DbRequest dbr = DbRequest.fromJSON(jsonObject); + queue.put(dbr.hash(), dbr); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public String textList() { + Iterator> iter = queue.entrySet().iterator(); + String result = ""; + + while (iter.hasNext()) { + DbRequest dbr = iter.next().getValue(); + result += "
"; + result += dbr.action.toUpperCase() + " "; + result += dbr.collection + ": "; + result += dbr.data.toString(); + } + return result; + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java new file mode 100644 index 0000000000..b4ba0c3364 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java @@ -0,0 +1,55 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.acks; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; +import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; +import io.socket.client.Ack; + +/** + * Created by mike on 29.12.2015. + */ +public class NSAddAck implements Ack { + private static Logger log = LoggerFactory.getLogger(NSAddAck.class); + public String _id = null; + public String nsClientID = null; + public JSONObject json = null; + public void call(Object...args) { + // Regular response + try { + JSONArray responsearray = (JSONArray) (args[0]); + JSONObject response = null; + if (responsearray.length()>0) { + response = responsearray.getJSONObject(0); + _id = response.getString("_id"); + json = response; + if (response.has("NSCLIENT_ID")) { + nsClientID = response.getString("NSCLIENT_ID"); + } + } + MainApp.bus().post(this); + return; + } catch (Exception e) { + } + // Check for not authorized + try { + JSONObject response = (JSONObject) (args[0]); + if (response.has("result")) { + _id = null; + if (response.getString("result").contains("Not")) { + MainApp.bus().post(new EventNSClientRestart()); + return; + } + log.debug("DBACCESS " + response.getString("result")); + } + return; + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAuthAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAuthAck.java new file mode 100644 index 0000000000..3c3b173173 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAuthAck.java @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.acks; + +import org.json.JSONObject; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; +import io.socket.client.Ack; + +/** + * Created by mike on 02.01.2016. + */ +public class NSAuthAck implements Ack{ + public boolean read = false; + public boolean write = false; + public boolean write_treatment = false; + + public void call(Object...args) { + JSONObject response = (JSONObject)args[0]; + read = response.optBoolean("read"); + write = response.optBoolean("write"); + write_treatment = response.optBoolean("write_treatment"); + MainApp.bus().post(this); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSPingAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSPingAck.java new file mode 100644 index 0000000000..2824e922aa --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSPingAck.java @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.acks; + +import org.json.JSONException; +import org.json.JSONObject; + +import io.socket.client.Ack; + +/** + * Created by mike on 29.12.2015. + */ +public class NSPingAck implements Ack { + public long mills = 0; + public boolean received = false; + public boolean auth_received = false; + public boolean read = false; + public boolean write = false; + public boolean write_treatment = false; + + public void call(Object...args) { + JSONObject response = (JSONObject)args[0]; + mills = response.optLong("mills"); + if (response.has("authorization")) { + auth_received = true; + try { + JSONObject authorization = response.getJSONObject("authorization"); + read = authorization.optBoolean("read"); + write = authorization.optBoolean("write"); + write_treatment = authorization.optBoolean("write_treatment"); + } catch (JSONException e) { + e.printStackTrace(); + } + } + received = true; + synchronized(this) { + this.notify(); + } + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java new file mode 100644 index 0000000000..5aef754d8c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java @@ -0,0 +1,39 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.acks; + +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.MainApp; +import io.socket.client.Ack; + +/** + * Created by mike on 21.02.2016. + */ +public class NSUpdateAck implements Ack { + private static Logger log = LoggerFactory.getLogger(NSUpdateAck.class); + public boolean result = false; + public String _id = null; + public String action; + public void call(Object...args) { + JSONObject response = (JSONObject)args[0]; + if (response.has("result")) + try { + if (response.getString("result").equals("success")) + result = true; + else if (response.getString("result").equals("Missing _id")) { + result = true; + log.debug("Internal error: Missing _id returned on dbUpdate ack"); + } + MainApp.bus().post(this); + } catch (JSONException e) { + } + } + + public NSUpdateAck(String action, String _id) { + super(); + this.action = action; + this._id = _id; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java new file mode 100644 index 0000000000..58a24e825c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java @@ -0,0 +1,34 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.os.Bundle; + +import org.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.Services.Intents; + +/** + * Created by mike on 26.06.2016. + */ +public class BroadcastCals { + private static Logger log = LoggerFactory.getLogger(BroadcastCals.class); + + public void handleNewCal(JSONArray cals, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("cals", cals.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_CAL); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("CAL " + x.size() + " receivers"); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java new file mode 100644 index 0000000000..64fd72b36a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.Services.Intents; + + +public class BroadcastDeviceStatus { + private static Logger log = LoggerFactory.getLogger(BroadcastDeviceStatus.class); + + public void handleNewDeviceStatus(JSONObject status, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("devicestatus", status.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("DEVICESTATUS " + x.size() + " receivers"); + } + public void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("devicestatuses", statuses.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("DEVICESTATUS " + x.size() + " receivers"); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java new file mode 100644 index 0000000000..33669e1852 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java @@ -0,0 +1,34 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.os.Bundle; + +import org.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.Services.Intents; + +/** + * Created by mike on 26.06.2016. + */ +public class BroadcastMbgs { + private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class); + + public void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("mbgs", mbgs.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_MBG); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("MBG " + x.size() + " receivers"); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java new file mode 100644 index 0000000000..a1d44d0340 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; + + +/** + * Created by mike on 20.02.2016. + */ +public class BroadcastProfile { + private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class); + + public void handleNewTreatment(NSProfile profile, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("profile", profile.getData().toString()); + bundle.putString("activeprofile", profile.getActiveProfile()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_PROFILE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("PROFILE " + x.size() + " receivers"); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastQueueStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastQueueStatus.java new file mode 100644 index 0000000000..ed2b01a27c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastQueueStatus.java @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.PowerManager; + +import info.nightscout.androidaps.Services.Intents; + +/** + * Created by mike on 28.02.2016. + */ +public class BroadcastQueueStatus { + public void handleNewStatus(int size, Context context) { + PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); + PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + "sendQueue"); + wakeLock.acquire(); + try { + Bundle bundle = new Bundle(); + bundle.putInt("size", size); + Intent intent = new Intent(Intents.ACTION_QUEUE_STATUS); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + } finally { + wakeLock.release(); + } + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java new file mode 100644 index 0000000000..81a2621a77 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.Services.Intents; + +/** + * Created by mike on 22.02.2016. + */ +public class BroadcastSgvs { + private static Logger log = LoggerFactory.getLogger(BroadcastSgvs.class); + + public void handleNewSgv(JSONObject sgv, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("sgv", sgv.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_SGV); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("SGV " + x.size() + " receivers"); + } + + public void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("sgvs", sgvs.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_SGV); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("SGV " + x.size() + " receivers"); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java new file mode 100644 index 0000000000..b99950c89b --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; + +/** + * Created by mike on 24.02.2016. + */ +public class BroadcastStatus { + private static Logger log = LoggerFactory.getLogger(BroadcastStatus.class); + + public void handleNewStatus(NSStatus status, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + try { + bundle.putString("nsclientversionname", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionName); + bundle.putInt("nsclientversioncode", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode); + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + }; + bundle.putString("nightscoutversionname", NSClientService.nightscoutVersionName); + bundle.putInt("nightscoutversioncode", NSClientService.nightscoutVersionCode); + bundle.putString("status", status.getData().toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_STATUS); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("STATUS: " + x.size() + " receivers"); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java new file mode 100644 index 0000000000..9d1abe43e3 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java @@ -0,0 +1,107 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +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.List; + +import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; + +/** + * Created by mike on 20.02.2016. + */ +public class BroadcastTreatment { + private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class); + + public void handleNewTreatment(NSTreatment treatment, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("treatment", treatment.getData().toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("TREAT_ADD " + treatment.getEventType() + " " + x.size() + " receivers"); + } + + public void handleNewTreatment(JSONArray treatments, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("treatments", treatments.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("TREAT_ADD " + treatments.length() + " " + x.size() + " receivers"); + } + + public void handleChangedTreatment(JSONObject treatment, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("treatment", treatment.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + try { + log.debug("TREAT_CHANGE " + treatment.getString("_id") + " " + x.size() + " receivers"); + } catch (JSONException e) {} + } + + public void handleChangedTreatment(JSONArray treatments, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("treatments", treatments.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("TREAT_CHANGE " + treatments.length() + " " + x.size() + " receivers"); + } + + public void handleRemovedTreatment(JSONObject treatment, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("treatment", treatment.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + try { + log.debug("TREAT_REMOVE " + treatment.getString("_id") + " " + x.size() + " receivers"); + } catch (JSONException e) {} + } + + public void handleRemovedTreatment(JSONArray treatments, Context context, boolean isDelta) { + Bundle bundle = new Bundle(); + bundle.putString("treatments", treatments.toString()); + bundle.putBoolean("delta", isDelta); + Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List x = context.getPackageManager().queryBroadcastReceivers(intent, 0); + + log.debug("TREAT_REMOVE " + treatments.length() + " treatments " + x.size() + " receivers"); + } + +} diff --git a/app/src/main/java/info/nightscout/client/data/DbLogger.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java similarity index 96% rename from app/src/main/java/info/nightscout/client/data/DbLogger.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java index 3695d5e735..70d8e9e336 100644 --- a/app/src/main/java/info/nightscout/client/data/DbLogger.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java @@ -1,4 +1,4 @@ -package info.nightscout.client.data; +package info.nightscout.androidaps.plugins.NSClientInternal.data; import android.content.Intent; import android.content.pm.ResolveInfo; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbRequest.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbRequest.java new file mode 100644 index 0000000000..ed7de35f49 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbRequest.java @@ -0,0 +1,87 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.data; + +import com.google.common.base.Charsets; +import com.google.common.hash.Hashing; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Created by mike on 27.02.2016. + *

+ * Allowed actions "dbAdd" || "dbUpdate" || "dbUpdateUnset" || "dbRemove" + */ +public class DbRequest { + public String action = null; + public String collection = null; + public JSONObject data = null; + public String _id = null; + public String nsClientID = null; + + public DbRequest() { + } + + // dbAdd + public DbRequest(String action, String collection, String nsClientID, JSONObject data) { + this.action = action; + this.collection = collection; + this.data = data; + this.nsClientID = nsClientID; + this._id = ""; + } + + // dbUpdate, dbUpdateUnset + public DbRequest(String action, String collection, String nsClientID, String _id, JSONObject data) { + this.action = action; + this.collection = collection; + this.data = data; + this.nsClientID = nsClientID; + this._id = _id; + } + + // dbRemove + public DbRequest(String action, String collection, String nsClientID, String _id) { + this.action = action; + this.collection = collection; + this.data = new JSONObject(); + this.nsClientID = nsClientID; + this._id = _id; + } + + public String hash() { + return Hashing.sha1().hashString(action + collection + _id + data.toString(), Charsets.UTF_8).toString(); + } + + public JSONObject toJSON() { + JSONObject object = new JSONObject(); + try { + object.put("action", action); + object.put("collection", collection); + object.put("data", data); + if (_id != null) object.put("_id", _id); + if (nsClientID != null) object.put("nsClientID", nsClientID); + } catch (JSONException e) { + e.printStackTrace(); + } + return object; + } + + public static DbRequest fromJSON(JSONObject jsonObject) { + DbRequest result = new DbRequest(); + try { + if (jsonObject.has("action")) + result.action = jsonObject.getString("action"); + if (jsonObject.has("collection")) + result.collection = jsonObject.getString("collection"); + if (jsonObject.has("data")) + result.data = jsonObject.getJSONObject("data"); + if (jsonObject.has("_id")) + result._id = jsonObject.getString("_id"); + if (jsonObject.has("nsClientID")) + result.nsClientID = jsonObject.getString("nsClientID"); + } catch (JSONException e) { + e.printStackTrace(); + } + return result; + } +} diff --git a/app/src/main/java/info/nightscout/client/data/NSCal.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java similarity index 67% rename from app/src/main/java/info/nightscout/client/data/NSCal.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java index 5a78dbaa02..74b5f688d9 100644 --- a/app/src/main/java/info/nightscout/client/data/NSCal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java @@ -1,9 +1,12 @@ -package info.nightscout.client.data; +package info.nightscout.androidaps.plugins.NSClientInternal.data; import org.json.JSONException; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NSCal { + private static Logger log = LoggerFactory.getLogger(NSCal.class); public long date; public double slope; public double intercept; @@ -17,6 +20,7 @@ public class NSCal { scale = json.getDouble("scale"); } catch (JSONException e) { e.printStackTrace(); + log.debug("Data: " + json.toString()); } } } diff --git a/app/src/main/java/info/nightscout/client/data/NSProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java similarity index 99% rename from app/src/main/java/info/nightscout/client/data/NSProfile.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java index 2e732c8c9f..4d3df3068c 100644 --- a/app/src/main/java/info/nightscout/client/data/NSProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java @@ -1,4 +1,4 @@ -package info.nightscout.client.data; +package info.nightscout.androidaps.plugins.NSClientInternal.data; import com.crashlytics.android.Crashlytics; diff --git a/app/src/main/java/info/nightscout/client/data/NSSgv.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java similarity index 96% rename from app/src/main/java/info/nightscout/client/data/NSSgv.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java index 5ce9b35caa..c8666f4306 100644 --- a/app/src/main/java/info/nightscout/client/data/NSSgv.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java @@ -1,4 +1,4 @@ -package info.nightscout.client.data; +package info.nightscout.androidaps.plugins.NSClientInternal.data; import org.json.JSONException; import org.json.JSONObject; diff --git a/app/src/main/java/info/nightscout/client/data/NSStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSStatus.java similarity index 97% rename from app/src/main/java/info/nightscout/client/data/NSStatus.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSStatus.java index f247907296..fe20e90b1d 100644 --- a/app/src/main/java/info/nightscout/client/data/NSStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSStatus.java @@ -1,4 +1,4 @@ -package info.nightscout.client.data; +package info.nightscout.androidaps.plugins.NSClientInternal.data; import org.json.JSONException; import org.json.JSONObject; diff --git a/app/src/main/java/info/nightscout/client/data/NSTreatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java similarity index 97% rename from app/src/main/java/info/nightscout/client/data/NSTreatment.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java index f358b4e74d..7430caf600 100644 --- a/app/src/main/java/info/nightscout/client/data/NSTreatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java @@ -1,4 +1,4 @@ -package info.nightscout.client.data; +package info.nightscout.androidaps.plugins.NSClientInternal.data; import org.json.JSONException; import org.json.JSONObject; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientNewLog.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientNewLog.java new file mode 100644 index 0000000000..7f576fde7e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientNewLog.java @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.events; + +import android.text.Html; +import android.text.Spanned; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Created by mike on 15.02.2017. + */ + +public class EventNSClientNewLog { + public Date date = new Date(); + public String action; + public String logText; + public EventNSClientNewLog(String action, String logText) { + this.action = action; + this.logText = logText; + } + + public Spanned toHtml() { + SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); + Spanned line = Html.fromHtml(timeFormat.format(date) + " " + action + " " + logText + "
"); + return line; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientRestart.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientRestart.java new file mode 100644 index 0000000000..9bf90be31b --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientRestart.java @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.events; + +/** + * Created by mike on 15.02.2017. + */ + +public class EventNSClientRestart { +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientStatus.java new file mode 100644 index 0000000000..6a1c721535 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientStatus.java @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.events; + +/** + * Created by mike on 02.01.2016. + */ +public class EventNSClientStatus { + public String status = ""; + + public EventNSClientStatus(String status) { + this.status = status; + } + + public EventNSClientStatus() { + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientUpdateGUI.java new file mode 100644 index 0000000000..8f00bd3424 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientUpdateGUI.java @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.events; + +/** + * Created by mike on 17.02.2017. + */ + +public class EventNSClientUpdateGUI { +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AutoStartReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AutoStartReceiver.java new file mode 100644 index 0000000000..dd5d3330ab --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AutoStartReceiver.java @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.receivers; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; + +public class AutoStartReceiver extends BroadcastReceiver { + public AutoStartReceiver() { + } + + @Override + public void onReceive(Context context, Intent intent) { + context.startService(new Intent(context, NSClientService.class)); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java new file mode 100644 index 0000000000..5f715ad78e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java @@ -0,0 +1,93 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.receivers; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.PowerManager; + +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; +import info.nightscout.androidaps.plugins.NSClientInternal.data.DbRequest; + +public class DBAccessReceiver extends BroadcastReceiver { + private static Logger log = LoggerFactory.getLogger(DBAccessReceiver.class); + + + @Override + public void onReceive(Context context, Intent intent) { + PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); + PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + "sendQueue"); + NSClientInternalPlugin nsClientInternalPlugin = (NSClientInternalPlugin) MainApp.getSpecificPlugin(NSClientInternalPlugin.class); + if (!nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) { + return; + } + wakeLock.acquire(); + try { + Bundle bundles = intent.getExtras(); + if (bundles == null) return; + if (!bundles.containsKey("action")) return; + + String collection = null; + String _id = null; + JSONObject data = null; + String action = bundles.getString("action"); + try { collection = bundles.getString("collection"); } catch (Exception e) {} + try { _id = bundles.getString("_id"); } catch (Exception e) {} + try { data = new JSONObject(bundles.getString("data")); } catch (Exception e) {} + + if (data == null && !action.equals("dbRemove") || _id == null && action.equals("dbRemove")) { + log.debug("DBACCESS no data inside record"); + return; + } + + if (action.equals("dbRemove")) { + data = new JSONObject(); + } + // mark by id + Long nsclientid = new Date().getTime(); + try { + data.put("NSCLIENT_ID", nsclientid); + } catch (JSONException e) { + e.printStackTrace(); + } + + if (!isAllowedCollection(collection)) { + log.debug("DBACCESS wrong collection specified"); + return; + } + + if (action.equals("dbRemove")) { + DbRequest dbr = new DbRequest(action, collection, nsclientid.toString(), _id); + UploadQueue.add(dbr); + } else { + DbRequest dbr = new DbRequest(action, collection, nsclientid.toString(), data); + UploadQueue.add(dbr); + } + + } finally { + wakeLock.release(); + } + + } + + private boolean isAllowedCollection(String collection) { + // "treatments" || "entries" || "devicestatus" || "profile" || "food" + if (collection.equals("treatments")) return true; + if (collection.equals("entries")) return true; + if (collection.equals("devicestatus")) return true; + if (collection.equals("profile")) return true; + if (collection.equals("food")) return true; + return false; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/RestartReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/RestartReceiver.java new file mode 100644 index 0000000000..a38ca842f9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/RestartReceiver.java @@ -0,0 +1,25 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.receivers; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.support.v4.content.WakefulBroadcastReceiver; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; +import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; + +public class RestartReceiver extends WakefulBroadcastReceiver { + public RestartReceiver() { + } + + @Override + public void onReceive(Context context, Intent intent) { + startWakefulService(context, new Intent(context, NSClientService.class) + .setAction(intent.getAction()) + .putExtras(intent)); + + MainApp.bus().post(new EventNSClientRestart()); + completeWakefulIntent(intent); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java new file mode 100644 index 0000000000..272959b21c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java @@ -0,0 +1,674 @@ +package info.nightscout.androidaps.plugins.NSClientInternal.services; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Binder; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.IBinder; +import android.os.PowerManager; +import android.preference.PreferenceManager; + +import com.google.common.base.Charsets; +import com.google.common.hash.Hashing; +import com.squareup.otto.Subscribe; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.URISyntaxException; +import java.util.Date; +import java.util.Iterator; +import java.util.Map; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventAppExit; +import info.nightscout.androidaps.events.EventConfigBuilderChange; +import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; +import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; +import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck; +import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAuthAck; +import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSPingAck; +import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSUpdateAck; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastCals; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastDeviceStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastMbgs; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastSgvs; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; +import info.nightscout.androidaps.plugins.NSClientInternal.data.DbRequest; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSCal; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; +import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; +import info.nightscout.androidaps.plugins.Overview.Notification; +import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; +import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.utils.DateUtil; +import info.nightscout.utils.SP; +import io.socket.client.IO; +import io.socket.client.Socket; +import io.socket.emitter.Emitter; + +public class NSClientService extends Service { + private static Logger log = LoggerFactory.getLogger(ExecutionService.class); + + static public PowerManager.WakeLock mWakeLock; + private IBinder mBinder = new NSClientService.LocalBinder(); + + static NSProfile nsProfile; + + static public Handler handler; + static private HandlerThread handlerThread; + + public static Socket mSocket; + public static boolean isConnected = false; + public static boolean hasWriteAuth = false; + private static Integer dataCounter = 0; + + + public static String nightscoutVersionName = ""; + public static Integer nightscoutVersionCode = 0; + + private boolean nsEnabled = false; + static public String nsURL = ""; + private String nsAPISecret = ""; + private String nsDevice = ""; + private Integer nsHours = 24; + + private final Integer timeToWaitForResponseInMs = 30000; + private boolean uploading = false; + public Date lastReception = new Date(); + + public long latestDateInReceivedData = 0; + + private String nsAPIhashCode = ""; + + public static UploadQueue uploadQueue = new UploadQueue(); + + public NSClientService() { + registerBus(); + if (handler == null) { + handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler"); + handlerThread.start(); + handler = new Handler(handlerThread.getLooper()); + } + + PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NSClientService"); + initialize(); + } + + public class LocalBinder extends Binder { + public NSClientService getServiceInstance() { + return NSClientService.this; + } + } + + @Override + public IBinder onBind(Intent intent) { + return mBinder; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + + return START_STICKY; + } + + private void registerBus() { + try { + MainApp.bus().unregister(this); + } catch (RuntimeException x) { + // Ignore + } + MainApp.bus().register(this); + } + + @Subscribe + public void onStatusEvent(EventAppExit event) { + if (Config.logFunctionCalls) + log.debug("EventAppExit received"); + + destroy(); + + stopSelf(); + if (Config.logFunctionCalls) + log.debug("EventAppExit finished"); + } + + @Subscribe + public void onStatusEvent(EventPreferenceChange ev) { + if (ev.isChanged(R.string.key_nsclientinternal_url) || + ev.isChanged(R.string.key_nsclientinternal_api_secret) || + ev.isChanged(R.string.key_nsclientinternal_paused) + ) { + destroy(); + initialize(); + } + } + + @Subscribe + public void onStatusEvent(EventConfigBuilderChange ev) { + if (nsEnabled != MainApp.getSpecificPlugin(NSClientInternalPlugin.class).isEnabled(PluginBase.GENERAL)) { + destroy(); + initialize(); + } + } + + public static void setNsProfile(NSProfile profile) { + nsProfile = profile; + } + + public static NSProfile getNsProfile() { + return nsProfile; + } + + public void initialize() { + dataCounter = 0; + + NSClientService.mWakeLock.acquire(); + + readPreferences(); + + if (!nsAPISecret.equals("")) + nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); + + MainApp.bus().post(new EventNSClientStatus("Initializing")); + if (((NSClientInternalPlugin)MainApp.getSpecificPlugin(NSClientInternalPlugin.class)).paused) { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused")); + MainApp.bus().post(new EventNSClientStatus("Paused")); + } else if (!nsEnabled) { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled")); + MainApp.bus().post(new EventNSClientStatus("Disabled")); + } else if (!nsURL.equals("")) { + try { + MainApp.bus().post(new EventNSClientStatus("Connecting ...")); + IO.Options opt = new IO.Options(); + opt.forceNew = true; + opt.reconnection = true; + mSocket = IO.socket(nsURL, opt); + mSocket.on(Socket.EVENT_CONNECT, onConnect); + mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect); + mSocket.on(Socket.EVENT_PING, onPing); + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect")); + mSocket.connect(); + mSocket.on("dataUpdate", onDataUpdate); + } catch (URISyntaxException | RuntimeException e) { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax")); + MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax")); + } + } else { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified")); + MainApp.bus().post(new EventNSClientStatus("Not configured")); + } + NSClientService.mWakeLock.release(); + } + + private Emitter.Listener onConnect = new Emitter.Listener() { + @Override + public void call(Object... args) { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "connect event. ID: " + mSocket.id())); + sendAuthMessage(new NSAuthAck()); + } + }; + + private Emitter.Listener onDisconnect = new Emitter.Listener() { + @Override + public void call(Object... args) { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event")); + } + }; + + public void destroy() { + if (mSocket != null) { + MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "destroy")); + isConnected = false; + hasWriteAuth = false; + mSocket.disconnect(); + mSocket = null; + } + } + + + public void sendAuthMessage(NSAuthAck ack) { + JSONObject authMessage = new JSONObject(); + try { + authMessage.put("client", "Android_" + nsDevice); + authMessage.put("history", nsHours); + authMessage.put("status", true); // receive status + authMessage.put("pingme", true); // send mi pings to keep alive + authMessage.put("from", latestDateInReceivedData); // send data newer than + authMessage.put("secret", nsAPIhashCode); + } catch (JSONException e) { + e.printStackTrace(); + return; + } + MainApp.bus().post(new EventNSClientNewLog("AUTH", "requesting auth")); + mSocket.emit("authorize", authMessage, ack); + } + + @Subscribe + public void onStatusEvent(NSAuthAck ack) { + String connectionStatus = "Authenticated ("; + if (ack.read) connectionStatus += "R"; + if (ack.write) connectionStatus += "W"; + if (ack.write_treatment) connectionStatus += "T"; + connectionStatus += ')'; + isConnected = true; + hasWriteAuth = ack.write && ack.write_treatment; + MainApp.bus().post(new EventNSClientStatus(connectionStatus)); + MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus)); + if (!ack.write) { + MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); + } + if (!ack.write_treatment) { + MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!")); + } + if (!hasWriteAuth) { + Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.sResources.getString(R.string.nowritepermission), Notification.URGENT); + MainApp.bus().post(new EventNewNotification(noperm)); + } else { + MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)); + } + lastReception = new Date(); + } + + public void readPreferences() { + nsEnabled = MainApp.getSpecificPlugin(NSClientInternalPlugin.class).isEnabled(PluginBase.GENERAL); + nsURL = SP.getString(R.string.key_nsclientinternal_url, ""); + nsAPISecret = SP.getString(R.string.key_nsclientinternal_api_secret, ""); + nsDevice = SP.getString("careportal_enteredby", ""); + } + + private Emitter.Listener onPing = new Emitter.Listener() { + @Override + public void call(final Object... args) { + if (Config.detailedLog) + MainApp.bus().post(new EventNSClientNewLog("PING", "received")); + // send data if there is something waiting + resend("Ping received"); + } + }; + + private Emitter.Listener onDataUpdate = new Emitter.Listener() { + @Override + public void call(final Object... args) { + lastReception = new Date(); + NSClientService.handler.post(new Runnable() { + @Override + public void run() { + PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + "onDataUpdate"); + wakeLock.acquire(); + try { + SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + + JSONObject data = (JSONObject) args[0]; + NSCal actualCal = new NSCal(); + boolean broadcastProfile = false; + try { + // delta means only increment/changes are comming + boolean isDelta = data.has("delta"); + boolean isFull = !isDelta; + MainApp.bus().post(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full"))); + + if (data.has("profiles")) { + JSONArray profiles = (JSONArray) data.getJSONArray("profiles"); + if (profiles.length() > 0) { + JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1); + String activeProfile = NSClientService.getNsProfile() == null ? null : NSClientService.getNsProfile().getActiveProfile(); + NSProfile nsProfile = new NSProfile(profile, activeProfile); + NSClientService.setNsProfile(nsProfile); + broadcastProfile = true; + MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received")); + } + } + + if (data.has("status")) { + JSONObject status = data.getJSONObject("status"); + NSStatus nsStatus = new NSStatus(status); + + if (!status.has("versionNum")) { + if (status.getInt("versionNum") < 900) { + MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); + } + } else { + nightscoutVersionName = status.getString("version"); + nightscoutVersionCode = status.getInt("versionNum"); + } + + BroadcastStatus bs = new BroadcastStatus(); + bs.handleNewStatus(nsStatus, MainApp.instance().getApplicationContext(), isDelta); + + if (NSClientService.getNsProfile() != null) { + String oldActiveProfile = NSClientService.getNsProfile().getActiveProfile(); + String receivedActiveProfile = nsStatus.getActiveProfile(); + NSClientService.getNsProfile().setActiveProfile(receivedActiveProfile); + if (receivedActiveProfile != null) { + MainApp.bus().post(new EventNSClientNewLog("PROFILE", "status activeProfile received: " + receivedActiveProfile)); + } + // Change possible nulls to "" + String oldP = oldActiveProfile == null ? "" : oldActiveProfile; + String newP = receivedActiveProfile == null ? "" : receivedActiveProfile; + if (!newP.equals(oldP)) { + broadcastProfile = true; + } + } + /* Other received data to 2016/02/10 + { + status: 'ok' + , name: env.name + , version: env.version + , versionNum: versionNum (for ver 1.2.3 contains 10203) + , serverTime: new Date().toISOString() + , apiEnabled: apiEnabled + , careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1 + , boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1 + , head: env.head + , settings: env.settings + , extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {} + , activeProfile ..... calculated from treatments or missing + } + */ + } else if (!isDelta) { + MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); + } + + // If new profile received or change detected broadcast it + if (broadcastProfile && nsProfile != null) { + BroadcastProfile bp = new BroadcastProfile(); + bp.handleNewTreatment(nsProfile, MainApp.instance().getApplicationContext(), isDelta); + MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting")); + } + + if (data.has("treatments")) { + JSONArray treatments = (JSONArray) data.getJSONArray("treatments"); + JSONArray removedTreatments = new JSONArray(); + JSONArray updatedTreatments = new JSONArray(); + JSONArray addedTreatments = new JSONArray(); + BroadcastTreatment bt = new BroadcastTreatment(); + if (treatments.length() > 0) + MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments")); + for (Integer index = 0; index < treatments.length(); index++) { + JSONObject jsonTreatment = treatments.getJSONObject(index); + NSTreatment treatment = new NSTreatment(jsonTreatment); + + // remove from upload queue if Ack is failing + UploadQueue.removeID(jsonTreatment); + //Find latest date in treatment + if (treatment.getMills() != null && treatment.getMills() < new Date().getTime()) + if (treatment.getMills() > latestDateInReceivedData) + latestDateInReceivedData = treatment.getMills(); + + if (treatment.getAction() == null) { + if (!isCurrent(treatment)) continue; + addedTreatments.put(jsonTreatment); + } else if (treatment.getAction().equals("update")) { + if (!isCurrent(treatment)) continue; + updatedTreatments.put(jsonTreatment); + } else if (treatment.getAction().equals("remove")) { + removedTreatments.put(jsonTreatment); + } + } + if (removedTreatments.length() > 0) { + bt.handleRemovedTreatment(removedTreatments, MainApp.instance().getApplicationContext(), isDelta); + } + if (updatedTreatments.length() > 0) { + bt.handleChangedTreatment(updatedTreatments, MainApp.instance().getApplicationContext(), isDelta); + } + if (addedTreatments.length() > 0) { + bt.handleNewTreatment(addedTreatments, MainApp.instance().getApplicationContext(), isDelta); + } + } + if (data.has("devicestatus")) { + BroadcastDeviceStatus bds = new BroadcastDeviceStatus(); + JSONArray devicestatuses = (JSONArray) data.getJSONArray("devicestatus"); + if (devicestatuses.length() > 0) { + MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses")); + for (Integer index = 0; index < devicestatuses.length(); index++) { + JSONObject jsonStatus = devicestatuses.getJSONObject(index); + // remove from upload queue if Ack is failing + UploadQueue.removeID(jsonStatus); + } + // send only last record + bds.handleNewDeviceStatus(devicestatuses.getJSONObject(devicestatuses.length() - 1), MainApp.instance().getApplicationContext(), isDelta); + } + } + if (data.has("mbgs")) { + BroadcastMbgs bmbg = new BroadcastMbgs(); + JSONArray mbgs = (JSONArray) data.getJSONArray("mbgs"); + if (mbgs.length() > 0) + MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs")); + for (Integer index = 0; index < mbgs.length(); index++) { + JSONObject jsonMbg = mbgs.getJSONObject(index); + // remove from upload queue if Ack is failing + UploadQueue.removeID(jsonMbg); + } + bmbg.handleNewMbg(mbgs, MainApp.instance().getApplicationContext(), isDelta); + } + if (data.has("cals")) { + BroadcastCals bc = new BroadcastCals(); + JSONArray cals = (JSONArray) data.getJSONArray("cals"); + if (cals.length() > 0) + MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals")); + // Retreive actual calibration + for (Integer index = 0; index < cals.length(); index++) { + if (index == 0) { + actualCal.set(cals.optJSONObject(index)); + } + // remove from upload queue if Ack is failing + UploadQueue.removeID(cals.optJSONObject(index)); + } + bc.handleNewCal(cals, MainApp.instance().getApplicationContext(), isDelta); + } + if (data.has("sgvs")) { + BroadcastSgvs bs = new BroadcastSgvs(); + String units = nsProfile != null ? nsProfile.getUnits() : "mg/dl"; + JSONArray sgvs = (JSONArray) data.getJSONArray("sgvs"); + if (sgvs.length() > 0) + MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs")); + for (Integer index = 0; index < sgvs.length(); index++) { + JSONObject jsonSgv = sgvs.getJSONObject(index); + // MainApp.bus().post(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString()); + NSSgv sgv = new NSSgv(jsonSgv); + // Handle new sgv here + // remove from upload queue if Ack is failing + UploadQueue.removeID(jsonSgv); + //Find latest date in sgv + if (sgv.getMills() != null && sgv.getMills() < new Date().getTime()) + if (sgv.getMills() > latestDateInReceivedData) + latestDateInReceivedData = sgv.getMills(); + } + bs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta); + } + MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); + } catch (JSONException e) { + e.printStackTrace(); + } + //MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); + } finally { + wakeLock.release(); + } + } + + }); + } + }; + + public void dbUpdate(DbRequest dbr, NSUpdateAck ack) { + try { + if (!isConnected || !hasWriteAuth) return; + JSONObject message = new JSONObject(); + message.put("collection", dbr.collection); + message.put("_id", dbr._id); + message.put("data", dbr.data); + mSocket.emit("dbUpdate", message, ack); + MainApp.bus().post(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public void dbUpdateUnset(DbRequest dbr, NSUpdateAck ack) { + try { + if (!isConnected || !hasWriteAuth) return; + JSONObject message = new JSONObject(); + message.put("collection", dbr.collection); + message.put("_id", dbr._id); + message.put("data", dbr.data); + mSocket.emit("dbUpdateUnset", message, ack); + MainApp.bus().post(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public void dbRemove(DbRequest dbr, NSUpdateAck ack) { + try { + if (!isConnected || !hasWriteAuth) return; + JSONObject message = new JSONObject(); + message.put("collection", dbr.collection); + message.put("_id", dbr._id); + mSocket.emit("dbRemove", message, ack); + MainApp.bus().post(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Subscribe + public void onStatusEvent(NSUpdateAck ack) { + if (ack.result) { + uploadQueue.removeID(ack.action, ack._id); + MainApp.bus().post(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); + } else { + MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); + } + } + + public void dbAdd(DbRequest dbr, NSAddAck ack) { + try { + if (!isConnected || !hasWriteAuth) return; + JSONObject message = new JSONObject(); + message.put("collection", dbr.collection); + message.put("data", dbr.data); + mSocket.emit("dbAdd", message, ack); + MainApp.bus().post(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Subscribe + public void onStatusEvent(NSAddAck ack) { + if (ack.nsClientID != null) { + uploadQueue.removeID(ack.json); + MainApp.bus().post(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); + } else { + MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); + } + } + + public void doPing() { + if (!isConnected || !hasWriteAuth) return; + MainApp.bus().post(new EventNSClientNewLog("PING", "Sending")); + uploading = true; + JSONObject message = new JSONObject(); + try { + message.put("mills", new Date().getTime()); + } catch (JSONException e) { + e.printStackTrace(); + } + NSPingAck ack = new NSPingAck(); + mSocket.emit("nsping", message, ack); + synchronized (ack) { + try { + ack.wait(timeToWaitForResponseInMs); + } catch (InterruptedException e) { + } + } + if (ack.received) { + String connectionStatus = "Pong received"; + if (ack.auth_received) { + connectionStatus += ": "; + if (ack.read) connectionStatus += "R"; + if (ack.write) connectionStatus += "W"; + if (ack.write_treatment) connectionStatus += "T"; + } + if (!ack.read) sendAuthMessage(new NSAuthAck()); + MainApp.bus().post(new EventNSClientNewLog("AUTH ", connectionStatus)); + } else { + MainApp.bus().post(new EventNSClientNewLog("PING", "Ping lost")); + } + uploading = false; + } + + private boolean isCurrent(NSTreatment treatment) { + long now = (new Date()).getTime(); + long minPast = now - nsHours * 60L * 60 * 1000; + if (treatment.getMills() == null) { + log.debug("treatment.getMills() == null " + treatment.getData().toString()); + return false; + } + if (treatment.getMills() > minPast) return true; + return false; + } + + public void resend(final String reason) { + if (UploadQueue.queue.size() == 0) + return; + + if (!isConnected || !hasWriteAuth) return; + + MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason)); + + handler.post(new Runnable() { + @Override + public void run() { + Logger log = LoggerFactory.getLogger(UploadQueue.class); + Iterator> iter = UploadQueue.queue.entrySet().iterator(); + + if (mSocket == null || !mSocket.connected()) return; + + while (iter.hasNext()) { + DbRequest dbr = iter.next().getValue(); + if (dbr.action.equals("dbAdd")) { + NSAddAck addAck = new NSAddAck(); + dbAdd(dbr, addAck); + } else if (dbr.action.equals("dbRemove")) { + NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id); + dbRemove(dbr, removeAck); + } else if (dbr.action.equals("dbUpdate")) { + NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id); + dbUpdate(dbr, updateAck); + } else if (dbr.action.equals("dbUpdateUnset")) { + NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id); + dbUpdateUnset(dbr, updateUnsetAck); + } + } + MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); + } + }); + } + + public void restart() { + destroy(); + initialize(); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSProfile/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSProfile/NSProfilePlugin.java index 5f5ed9ca1d..3c19b5a5c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSProfile/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSProfile/NSProfilePlugin.java @@ -19,8 +19,9 @@ import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.ProfileInterface; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.NSProfile.events.EventNSProfileUpdateGUI; -import info.nightscout.client.data.NSProfile; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. @@ -110,9 +111,8 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface { private void loadNSProfile() { if (Config.logPrefsChange) log.debug("Loading stored profile"); - SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - String activeProfile = store.getString("activeProfile", null); - String profileString = store.getString("profile", null); + String activeProfile = SP.getString("activeProfile", null); + String profileString = SP.getString("profile", null); if (profileString != null) { if (Config.logPrefsChange) { log.debug("Loaded profile: " + profileString); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java index 030878b6e9..5d33fdae5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java @@ -16,6 +16,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; /** @@ -211,20 +212,19 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface { } void loadProgress() { - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); for (int num = 0; num < objectives.size(); num++) { Objective o = objectives.get(num); try { - o.started = new Date(SafeParse.stringToLong(settings.getString("Objectives" + num + "started", "0"))); - o.accomplished = new Date(SafeParse.stringToLong(settings.getString("Objectives" + num + "accomplished", "0"))); + o.started = new Date(SP.getLong("Objectives" + num + "started", 0L)); + o.accomplished = new Date(SP.getLong("Objectives" + num + "accomplished", 0L)); } catch (Exception e) { e.printStackTrace(); } } - bgIsAvailableInNS = settings.getBoolean("Objectives" + "bgIsAvailableInNS", false); - pumpStatusIsAvailableInNS = settings.getBoolean("Objectives" + "pumpStatusIsAvailableInNS", false); + bgIsAvailableInNS = SP.getBoolean("Objectives" + "bgIsAvailableInNS", false); + pumpStatusIsAvailableInNS = SP.getBoolean("Objectives" + "pumpStatusIsAvailableInNS", false); try { - manualEnacts = SafeParse.stringToInt(settings.getString("Objectives" + "manualEnacts", "0")); + manualEnacts = SP.getInt("Objectives" + "manualEnacts", 0); } catch (Exception e) { e.printStackTrace(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/Autosens.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/Autosens.java index eb449b96c8..44c3970ac5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/Autosens.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/Autosens.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.OpenAPSAMA; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,12 +8,12 @@ import java.util.Arrays; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.Round; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; @@ -24,7 +21,6 @@ public class Autosens { private static Logger log = LoggerFactory.getLogger(Autosens.class); public static AutosensResult detectSensitivityandCarbAbsorption(List glucose_data, Long mealTime) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); //console.error(mealTime); @@ -132,7 +128,7 @@ public class Autosens { if (mealTime != null && bgTime > mealTime) { // figure out how many carbs that represents // but always assume at least 3mg/dL/5m (default) absorption - double ci = Math.max(deviation, SafeParse.stringToDouble(SP.getString("openapsama_min_5m_carbimpact", "3.0"))); + double ci = Math.max(deviation, SP.getDouble("openapsama_min_5m_carbimpact", 3.0)); double absorbed = ci * profile.getIc(secondsFromMidnight) / sens; // and add that to the running total carbsAbsorbed carbsAbsorbed += absorbed; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java index aa6c0ae36d..f03a892cae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java @@ -16,17 +16,15 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; public class DetermineBasalAdapterAMAJS { @@ -209,7 +207,6 @@ public class DetermineBasalAdapterAMAJS { double min_5m_carbimpact) { String units = profile.getUnits(); - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); mProfile = new V8Object(mV8rt); mProfile.add("max_iob", maxIob); @@ -222,13 +219,13 @@ public class DetermineBasalAdapterAMAJS { mProfile.add("target_bg", targetBg); mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight())); mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units)); - mProfile.add("max_daily_safety_multiplier", SafeParse.stringToInt(preferences.getString("openapsama_max_daily_safety_multiplier", "3"))); - mProfile.add("current_basal_safety_multiplier", SafeParse.stringToInt(preferences.getString("openapsama_current_basal_safety_multiplier", "4"))); + mProfile.add("max_daily_safety_multiplier", SP.getInt("openapsama_max_daily_safety_multiplier", 3)); + mProfile.add("current_basal_safety_multiplier", SP.getInt("openapsama_current_basal_safety_multiplier", 4)); mProfile.add("skip_neutral_temps", true); mProfile.add("current_basal", pump.getBaseBasalRate()); mProfile.add("temptargetSet", tempTargetSet); - mProfile.add("autosens_adjust_targets", preferences.getBoolean("openapsama_autosens_adjusttargets", true)); - mProfile.add("min_5m_carbimpact", SafeParse.stringToDouble(preferences.getString("openapsama_min_5m_carbimpact", "3.0"))); + mProfile.add("autosens_adjust_targets", SP.getBoolean("openapsama_autosens_adjusttargets", true)); + mProfile.add("min_5m_carbimpact", SP.getDouble("openapsama_min_5m_carbimpact", 3d)); mV8rt.add(PARAM_profile, mProfile); mCurrentTemp = new V8Object(mV8rt); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java index 49d5b760b9..2cbffae52a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java @@ -22,17 +22,17 @@ import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.interfaces.TempBasalsInterface; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.Profiler; import info.nightscout.utils.Round; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; @@ -156,12 +156,11 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface { return; } - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String units = profile.getUnits(); - String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; - String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; - String targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; + Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; + Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; + Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; if (!units.equals(Constants.MGDL)) { maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; @@ -170,11 +169,11 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface { Date now = new Date(); - double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5")); - double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); - double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units); - double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", maxBgDefault)), units); - double targetBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_target_bg", targetBgDefault)), units); + double maxIob = SP.getDouble("openapsma_max_iob", 1.5d); + double maxBasal = SP.getDouble("openapsma_max_basal", 1d); + double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units); + double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units); + double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units); minBg = Round.roundTo(minBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java index 75c68cd5cc..75f87021c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java @@ -18,7 +18,7 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Loop.ScriptReader; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; public class DetermineBasalAdapterMAJS { private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterMAJS.class); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java index a3d5c3c508..c4b8f3e34a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.OpenAPSMA; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,15 +22,15 @@ import info.nightscout.androidaps.interfaces.TempBasalsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.ScriptReader; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; -import info.nightscout.client.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.Profiler; import info.nightscout.utils.Round; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; -import info.nightscout.utils.ToastUtils; import static info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin.checkOnlyHardLimits; import static info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin.verifyHardLimits; @@ -157,12 +154,11 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface { return; } - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String units = profile.getUnits(); - String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; - String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; - String targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; + Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; + Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; + Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; if (!units.equals(Constants.MGDL)) { maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; @@ -171,11 +167,11 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface { Date now = new Date(); - double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5")); + double maxIob = SP.getDouble("openapsma_max_iob", 1.5d); double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); - double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units); - double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", maxBgDefault)), units); - double targetBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_target_bg", targetBgDefault)), units); + double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units); + double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units); + double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units); minBg = Round.roundTo(minBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressDialog.java index dfedda106e..a5d45128be 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressDialog.java @@ -18,10 +18,10 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; public class BolusProgressDialog extends DialogFragment implements View.OnClickListener { private static Logger log = LoggerFactory.getLogger(BolusProgressDialog.class); @@ -46,7 +46,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL bolusEnded = false; } - public void setHelperActivity(BolusProgressHelperActivity activity){ + public void setHelperActivity(BolusProgressHelperActivity activity) { this.helperActivity = activity; } @@ -77,9 +77,9 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL } @Override - public void dismiss(){ + public void dismiss() { super.dismiss(); - if (helperActivity!= null){ + if (helperActivity != null) { helperActivity.finish(); } } @@ -128,7 +128,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus c) { + public void onStatusEvent(final EventPumpStatusChanged c) { Activity activity = getActivity(); if (activity != null) { @@ -136,14 +136,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL new Runnable() { @Override public void run() { - if (c.sStatus == c.CONNECTING) { - statusView.setText(String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), c.sSecondsElapsed)); - } else if (c.sStatus == c.CONNECTED) { - statusView.setText(MainApp.sResources.getString(R.string.connected)); - } else { - statusView.setText(MainApp.sResources.getString(R.string.disconnected)); - if (started) scheduleDismiss(); - } + statusView.setText(c.textStatus()); } } ); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java index 9e06bbb600..0c2b9068bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java @@ -21,7 +21,7 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.GlucoseStatus; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.XdripCalibrations; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index 890c393edc..2fc8764a9d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -43,7 +43,7 @@ import info.nightscout.androidaps.interfaces.TempBasalsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.BolusWizard; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java index 5d83a76cc7..0508917312 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Notification.java @@ -23,6 +23,7 @@ public class Notification { public static final int OLD_NSCLIENT = 8; public static final int INVALID_PHONE_NUMBER = 9; public static final int APPROACHING_DAILY_LIMIT = 10; + public static final int NSCLIENT_NO_WRITE_PERMISSION = 10; public int id; public Date date; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 61f4279a51..ac9035b7fd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -63,6 +63,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTreatmentChange; @@ -71,7 +72,6 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Objectives.ObjectivesPlugin; @@ -87,19 +87,18 @@ import info.nightscout.androidaps.plugins.Overview.graphExtensions.TimeAsXAxisLa import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.BolusWizard; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.Round; -import info.nightscout.utils.SafeParse; +import info.nightscout.utils.SP; public class OverviewFragment extends Fragment { private static Logger log = LoggerFactory.getLogger(OverviewFragment.class); private static OverviewPlugin overviewPlugin = new OverviewPlugin(); - private SharedPreferences prefs; public static OverviewPlugin getPlugin() { return overviewPlugin; @@ -118,6 +117,8 @@ public class OverviewFragment extends Fragment { TextView apsModeView; TextView tempTargetView; TextView pumpStatusView; + LinearLayout loopStatusLayout; + LinearLayout pumpStatusLayout; GraphView bgGraph; CheckBox showPredictionView; @@ -151,7 +152,6 @@ public class OverviewFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); View view = inflater.inflate(R.layout.overview_fragment, container, false); bgView = (TextView) view.findViewById(R.id.overview_bg); @@ -163,7 +163,9 @@ public class OverviewFragment extends Fragment { baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal); basalLayout = (LinearLayout) view.findViewById(R.id.overview_basallayout); activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile); - pumpStatusView = (TextView) view.findViewById(R.id.overview_initializing); + pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus); + loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout); + pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout); iobView = (TextView) view.findViewById(R.id.overview_iob); apsModeView = (TextView) view.findViewById(R.id.overview_apsmode); @@ -185,12 +187,13 @@ public class OverviewFragment extends Fragment { llm = new LinearLayoutManager(view.getContext()); notificationsView.setLayoutManager(llm); - showPredictionView.setChecked(prefs.getBoolean("showprediction", false)); + showPredictionView.setChecked(SP.getBoolean("showprediction", false)); showPredictionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - SharedPreferences.Editor editor = prefs.edit(); + SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("showprediction", showPredictionView.isChecked()); editor.apply(); updateGUI(); @@ -295,7 +298,7 @@ public class OverviewFragment extends Fragment { sHandler.post(new Runnable() { @Override public void run() { - MainApp.getConfigBuilder().updateStatus("RefreshClicked"); + MainApp.getConfigBuilder().refreshDataFromPump("RefreshClicked"); } }); } @@ -320,7 +323,7 @@ public class OverviewFragment extends Fragment { final JSONObject boluscalcJSON = new JSONObject(); try { - boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date())); + boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date())); boluscalcJSON.put("targetBGLow", wizard.targetBGLow); boluscalcJSON.put("targetBGHigh", wizard.targetBGHigh); boluscalcJSON.put("isf", wizard.sens); @@ -477,18 +480,13 @@ public class OverviewFragment extends Fragment { } @Subscribe - public void onStatusEvent(final EventDanaRConnectionStatus s) { + public void onStatusEvent(final EventPumpStatusChanged s) { Activity activity = getActivity(); if (activity != null) activity.runOnUiThread(new Runnable() { @Override public void run() { - if (s.sStatus == EventDanaRConnectionStatus.CONNECTING) - updatePumpStatus(String.format(getString(R.string.danar_history_connectingfor), s.sSecondsElapsed)); - else if (s.sStatus == EventDanaRConnectionStatus.PERFORMING) - updatePumpStatus(s.sAction); - else if (s.sStatus == EventDanaRConnectionStatus.DISCONNECTED) - updatePumpStatus(null); + updatePumpStatus(s.textStatus()); } }); } @@ -517,30 +515,15 @@ public class OverviewFragment extends Fragment { private void updatePumpStatus(String status) { PumpInterface pump = MainApp.getConfigBuilder(); - if (status != null) { + if (!status.equals("")) { pumpStatusView.setText(status); - pumpStatusView.setVisibility(View.VISIBLE); - } else if (pump.isBusy()) { - pumpStatusView.setText(R.string.pumpbusy); - pumpStatusView.setVisibility(View.VISIBLE); - } else if (pump.isSuspended()) { - // disable all treatment buttons because we are not able to check constraints without profile - wizardButton.setVisibility(View.INVISIBLE); - treatmentButton.setVisibility(View.INVISIBLE); - quickWizardButton.setVisibility(View.INVISIBLE); - pumpStatusView.setText(R.string.pumpsuspendedclicktorefresh); - pumpStatusView.setVisibility(View.VISIBLE); - } else if (!pump.isInitialized()) { - // disable all treatment buttons because we are not able to check constraints without profile - wizardButton.setVisibility(View.INVISIBLE); - treatmentButton.setVisibility(View.INVISIBLE); - quickWizardButton.setVisibility(View.INVISIBLE); - pumpStatusView.setText(R.string.waitingforpumpclicktorefresh); - pumpStatusView.setVisibility(View.VISIBLE); + pumpStatusLayout.setVisibility(View.VISIBLE); + loopStatusLayout.setVisibility(View.GONE); } else { wizardButton.setVisibility(View.VISIBLE); treatmentButton.setVisibility(View.VISIBLE); - pumpStatusView.setVisibility(View.GONE); + pumpStatusLayout.setVisibility(View.GONE); + loopStatusLayout.setVisibility(View.VISIBLE); } } @@ -552,10 +535,12 @@ public class OverviewFragment extends Fragment { if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null || MainApp.getConfigBuilder().getActiveProfile().getProfile() == null) {// app not initialized yet pumpStatusView.setText(R.string.noprofileset); - pumpStatusView.setVisibility(View.VISIBLE); + pumpStatusLayout.setVisibility(View.VISIBLE); + loopStatusLayout.setVisibility(View.GONE); return; } else { - pumpStatusView.setVisibility(View.GONE); + pumpStatusLayout.setVisibility(View.GONE); + loopStatusLayout.setVisibility(View.VISIBLE); } // Skip if not initialized yet @@ -623,15 +608,15 @@ public class OverviewFragment extends Fragment { tempTargetView.setText(NSProfile.toUnitsString(tempTarget.low, NSProfile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + NSProfile.toUnitsString(tempTarget.high, NSProfile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits())); } else { - String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; - String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; + Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; + Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; if (!profile.getUnits().equals(Constants.MGDL)) { maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; } tempTargetView.setTextColor(Color.WHITE); tempTargetView.setBackgroundResource(R.drawable.temptargetborderdisabled); - tempTargetView.setText(prefs.getString("openapsma_min_bg", minBgDefault) + " - " + prefs.getString("openapsma_max_bg", maxBgDefault)); + tempTargetView.setText(SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault)); tempTargetView.setVisibility(View.VISIBLE); } } else { @@ -799,8 +784,8 @@ public class OverviewFragment extends Fragment { endTime = toTime; } - Double lowLine = SafeParse.stringToDouble(prefs.getString("low_mark", "0")); - Double highLine = SafeParse.stringToDouble(prefs.getString("high_mark", "0")); + Double lowLine = SP.getDouble("low_mark", 0d); + Double highLine = SP.getDouble("high_mark", 0d); if (lowLine < 1) { lowLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units); @@ -1003,7 +988,7 @@ public class OverviewFragment extends Fragment { bgGraph.getGridLabelRenderer().setVerticalLabelsSecondScaleColor(ContextCompat.getColor(MainApp.instance(), R.color.background_material_dark)); // same color as backround = hide } - updatePumpStatus(null); + //updatePumpStatus(null); } //Notifications diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java index 9caa2fde10..a8f0083afc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.Overview; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - import com.squareup.otto.Subscribe; import org.json.JSONArray; @@ -13,6 +10,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. @@ -27,8 +25,7 @@ public class OverviewPlugin implements PluginBase { public NotificationStore notificationStore = new NotificationStore(); public OverviewPlugin() { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - String storedData = preferences.getString("QuickWizard", "[]"); + String storedData = SP.getString("QuickWizard", "[]"); try { quickWizard.setData(new JSONArray(storedData)); } catch (JSONException e) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java index ac7dbaa101..4f3e2a255c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/QuickWizard.java @@ -7,12 +7,10 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.util.Calendar; import java.util.Date; -import java.util.GregorianCalendar; import info.nightscout.androidaps.MainApp; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java index d9bff5a4cd..9cbda6bf06 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.SafetyFragment; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,9 +10,9 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.Round; -import info.nightscout.utils.SafeParse; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. @@ -78,7 +75,6 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface { **/ @Override public boolean isClosedModeEnabled() { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String mode = SP.getString("aps_mode", "open"); return mode.equals("closed") && BuildConfig.CLOSEDLOOP; } @@ -96,15 +92,14 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface { @Override public Double applyBasalConstraints(Double absoluteRate) { Double origAbsoluteRate = absoluteRate; - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); + Double maxBasal = SP.getDouble("openapsma_max_basal", 1d); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return absoluteRate; if (absoluteRate < 0) absoluteRate = 0d; - Integer maxBasalMult = SafeParse.stringToInt(SP.getString("openapsama_current_basal_safety_multiplier", "4")); - Integer maxBasalFromDaily = SafeParse.stringToInt(SP.getString("openapsama_max_daily_safety_multiplier", "3")); + Integer maxBasalMult = SP.getInt("openapsama_current_basal_safety_multiplier", 4); + Integer maxBasalFromDaily = SP.getInt("openapsama_max_daily_safety_multiplier", 3); // Check percentRate but absolute rate too, because we know real current basal in pump Double origRate = absoluteRate; if (absoluteRate > maxBasal) { @@ -128,8 +123,7 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface { @Override public Integer applyBasalConstraints(Integer percentRate) { Integer origPercentRate = percentRate; - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); + Double maxBasal = SP.getDouble("openapsma_max_basal", 1d); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return percentRate; @@ -142,8 +136,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface { if (absoluteRate < 0) absoluteRate = 0d; - Integer maxBasalMult = SafeParse.stringToInt(SP.getString("openapsama_current_basal_safety_multiplier", "4")); - Integer maxBasalFromDaily = SafeParse.stringToInt(SP.getString("openapsama_max_daily_safety_multiplier", "3")); + Integer maxBasalMult = SP.getInt("openapsama_current_basal_safety_multiplier", 4); + Integer maxBasalFromDaily = SP.getInt("openapsama_max_daily_safety_multiplier", 3); // Check percentRate but absolute rate too, because we know real current basal in pump Double origRate = absoluteRate; if (absoluteRate > maxBasal) { @@ -174,9 +168,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface { @Override public Double applyBolusConstraints(Double insulin) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); try { - Double maxBolus = SafeParse.stringToDouble(SP.getString("treatmentssafety_maxbolus", "3")); + Double maxBolus = SP.getDouble("treatmentssafety_maxbolus", 3d); if (insulin < 0) insulin = 0d; if (insulin > maxBolus) insulin = maxBolus; @@ -189,9 +182,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface { @Override public Integer applyCarbsConstraints(Integer carbs) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); try { - Integer maxCarbs = SafeParse.stringToInt(SP.getString("treatmentssafety_maxcarbs", "48")); + Integer maxCarbs = SP.getInt("treatmentssafety_maxcarbs", 48); if (carbs < 0) carbs = 0; if (carbs > maxCarbs) carbs = maxCarbs; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfilePlugin.java index 3264696feb..f40d85371e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfilePlugin.java @@ -15,7 +15,8 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; /** @@ -60,7 +61,7 @@ public class SimpleProfilePlugin implements PluginBase, ProfileInterface { @Override public String getNameShort() { String name = MainApp.sResources.getString(R.string.simpleprofile_shortname); - if (!name.trim().isEmpty()){ + if (!name.trim().isEmpty()) { //only if translation exists return name; } @@ -114,64 +115,15 @@ public class SimpleProfilePlugin implements PluginBase, ProfileInterface { private void loadSettings() { if (Config.logPrefsChange) log.debug("Loading stored settings"); - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - if (settings.contains("SimpleProfile" + "mgdl")) - try { - mgdl = settings.getBoolean("SimpleProfile" + "mgdl", true); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else mgdl = true; - if (settings.contains("SimpleProfile" + "mmol")) - try { - mmol = settings.getBoolean("SimpleProfile" + "mmol", false); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else mmol = false; - if (settings.contains("SimpleProfile" + "dia")) - try { - dia = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "dia", "3")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else dia = 3d; - if (settings.contains("SimpleProfile" + "ic")) - try { - ic = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "ic", "20")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else ic = 20d; - if (settings.contains("SimpleProfile" + "isf")) - try { - isf = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "isf", "200")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else isf = 200d; - if (settings.contains("SimpleProfile" + "basal")) - try { - basal = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "basal", "1")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else basal = 1d; - if (settings.contains("SimpleProfile" + "targetlow")) - try { - targetLow = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "targetlow", "80")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else targetLow = 80d; - if (settings.contains("SimpleProfile" + "targethigh")) - try { - targetHigh = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "targethigh", "120")); - } catch (Exception e) { - log.debug(e.getMessage()); - } - else targetHigh = 120d; + mgdl = SP.getBoolean("SimpleProfile" + "mgdl", true); + mmol = SP.getBoolean("SimpleProfile" + "mmol", false); + dia = SP.getDouble("SimpleProfile" + "dia", 3d); + ic = SP.getDouble("SimpleProfile" + "ic", 20d); + isf = SP.getDouble("SimpleProfile" + "isf", 200d); + basal = SP.getDouble("SimpleProfile" + "basal", 1d); + targetLow = SP.getDouble("SimpleProfile" + "targetlow", 80d); + targetHigh = SP.getDouble("SimpleProfile" + "targethigh", 120d); createConvertedProfile(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java index 4097efcdf9..e216764a3d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.GlucoseStatus; +import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.events.EventPreferenceChange; @@ -30,13 +31,13 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; -import info.nightscout.androidaps.data.IobTotal; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; -import info.nightscout.client.data.NSProfile; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.XdripCalibrations; @@ -159,8 +160,7 @@ public class SmsCommunicatorPlugin implements PluginBase { @Subscribe public void processSettings(final EventPreferenceChange ev) { - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - String settings = sharedPreferences.getString("smscommunicator_allowednumbers", ""); + String settings = SP.getString("smscommunicator_allowednumbers", ""); String pattern = ";"; @@ -191,8 +191,6 @@ public class SmsCommunicatorPlugin implements PluginBase { } private void processSms(Sms receivedSms) { - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - if (!isEnabled(PluginBase.GENERAL)) { log.debug("Ignoring SMS. Plugin disabled."); return; @@ -319,7 +317,7 @@ public class SmsCommunicatorPlugin implements PluginBase { break; case "BASAL": if (splited.length > 1) { - boolean remoteCommandsAllowed = sharedPreferences.getBoolean("smscommunicator_remotecommandsallowed", false); + boolean remoteCommandsAllowed = SP.getBoolean("smscommunicator_remotecommandsallowed", false); if (splited[1].toUpperCase().equals("CANCEL") || splited[1].toUpperCase().equals("STOP")) { if (remoteCommandsAllowed) { passCode = generatePasscode(); @@ -355,7 +353,7 @@ public class SmsCommunicatorPlugin implements PluginBase { } else if (splited.length > 1) { amount = SafeParse.stringToDouble(splited[1]); amount = MainApp.getConfigBuilder().applyBolusConstraints(amount); - boolean remoteCommandsAllowed = sharedPreferences.getBoolean("smscommunicator_remotecommandsallowed", false); + boolean remoteCommandsAllowed = SP.getBoolean("smscommunicator_remotecommandsallowed", false); if (amount > 0d && remoteCommandsAllowed) { passCode = generatePasscode(); reply = String.format(MainApp.sResources.getString(R.string.smscommunicator_bolusreplywithcode), amount, passCode); @@ -372,7 +370,7 @@ public class SmsCommunicatorPlugin implements PluginBase { case "CAL": if (splited.length > 1) { amount = SafeParse.stringToDouble(splited[1]); - boolean remoteCommandsAllowed = sharedPreferences.getBoolean("smscommunicator_remotecommandsallowed", false); + boolean remoteCommandsAllowed = SP.getBoolean("smscommunicator_remotecommandsallowed", false); if (amount > 0d && remoteCommandsAllowed) { passCode = generatePasscode(); reply = String.format(MainApp.sResources.getString(R.string.smscommunicator_calibrationreplywithcode), amount, passCode); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/TempTargetRange/TempTargetRangeFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/TempTargetRange/TempTargetRangeFragment.java index 4bfe4ca74e..f9e979ae45 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/TempTargetRange/TempTargetRangeFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/TempTargetRange/TempTargetRangeFragment.java @@ -34,7 +34,7 @@ import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.ToastUtils; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java index 38a4904b56..4e1b41906e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java @@ -36,7 +36,7 @@ import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.FragmentBase; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.ToastUtils; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java index 966a5e7578..c49e26553e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java @@ -1,35 +1,25 @@ package info.nightscout.androidaps.plugins.Treatments; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.stmt.PreparedQuery; -import com.j256.ormlite.stmt.QueryBuilder; -import com.j256.ormlite.stmt.Where; import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.SQLException; -import java.util.ArrayList; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; +import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.TreatmentsInterface; -import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.client.data.NSProfile; -import info.nightscout.utils.SafeParse; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. @@ -125,7 +115,6 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { @Override public IobTotal getCalculationToTime(long time) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); IobTotal total = new IobTotal(time); if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet @@ -143,7 +132,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { Iob tIOB = t.iobCalc(now, dia); total.iob += tIOB.iobContrib; total.activity += tIOB.activityContrib; - Iob bIOB = t.iobCalc(now, dia / SafeParse.stringToInt(SP.getString("openapsama_bolussnooze_dia_divisor", "2"))); + Iob bIOB = t.iobCalc(now, dia / SP.getInt("openapsama_bolussnooze_dia_divisor", 2)); total.bolussnooze += bIOB.iobContrib; } return total; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpPlugin.java index e90916122f..0e46b6a219 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpPlugin.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.VirtualPump.events.EventVirtualPumpUpdateGui; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; /** @@ -158,12 +158,12 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { } @Override - public Date lastStatusTime() { + public Date lastDataTime() { return new Date(); } @Override - public void updateStatus(String reason) { + public void refreshDataFromPump(String reason) { // do nothing } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java index 8b24be7979..6afb51c5c6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java @@ -1,21 +1,11 @@ package info.nightscout.androidaps.plugins.Wear; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.graphics.Color; import android.os.Handler; import android.os.HandlerThread; -import android.preference.PreferenceManager; -import android.support.annotation.BoolRes; import android.support.annotation.NonNull; -import android.support.v7.app.AlertDialog; -import android.view.View; import com.j256.ormlite.dao.Dao; -import org.json.JSONException; -import org.json.JSONObject; - import java.sql.SQLException; import java.text.DecimalFormat; import java.util.Date; @@ -32,15 +22,14 @@ import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; -import info.nightscout.androidaps.plugins.Overview.QuickWizard; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; -import info.nightscout.client.data.NSProfile; import info.nightscout.utils.BolusWizard; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; @@ -56,9 +45,6 @@ public class ActionStringHandler { private static String lastConfirmActionString = null; private static BolusWizard lastBolusWizard = null; - private static SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - - private static HandlerThread handlerThread = new HandlerThread(FillDialog.class.getSimpleName()); static { handlerThread.start(); @@ -83,11 +69,11 @@ public class ActionStringHandler { ///////////////////////////////////// PRIME/FILL double amount = 0d; if ("1".equals(act[1])) { - amount = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button1", "0.3")))); + amount = SP.getDouble("fill_button1", 0.3); } else if ("2".equals(act[1])) { - amount = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button2", "0")))); + amount = SP.getDouble("fill_button2", 0d); } else if ("3".equals(act[1])) { - amount = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button3", "0")))); + amount = SP.getDouble("fill_button3", 0d); } else { return; } @@ -305,17 +291,17 @@ public class ActionStringHandler { } //Default Range/Target - String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; - String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; - String targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; + Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; + Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; + Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; if (!profile.getUnits().equals(Constants.MGDL)) { maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; targetBgDefault = Constants.TARGET_BG_DEFAULT_MMOL; } ret += "DEFAULT RANGE: "; - ret += sp.getString("openapsma_min_bg", minBgDefault) + " - " + sp.getString("openapsma_max_bg", maxBgDefault); - ret += " target: " + sp.getString("openapsma_target_bg", targetBgDefault); + ret += SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault); + ret += " target: " + SP.getDouble("openapsma_target_bg", targetBgDefault); return ret; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java index 9e1f9709dd..5df62fd4dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java @@ -35,7 +35,7 @@ import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Wear.ActionStringHandler; import info.nightscout.androidaps.plugins.Wear.WearPlugin; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/persistentnotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/persistentnotification/PersistentNotificationPlugin.java index 532959d926..37b2d5b99d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/persistentnotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/persistentnotification/PersistentNotificationPlugin.java @@ -28,7 +28,7 @@ import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DecimalFormatter; /** diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index a7f3f02f36..434d488086 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -18,14 +18,10 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; -import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; public class KeepAliveReceiver extends BroadcastReceiver { private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class); @@ -43,7 +39,7 @@ public class KeepAliveReceiver extends BroadcastReceiver { boolean isBasalOutdated = false; boolean isStatusOutdated = false; - Date lastConnection = pump.lastStatusTime(); + Date lastConnection = pump.lastDataTime(); if (lastConnection.getTime() + 30 * 60 * 1000L < new Date().getTime()) isStatusOutdated = true; if (Math.abs(profile.getBasal(NSProfile.secondsFromMidnight()) - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep) @@ -62,7 +58,7 @@ public class KeepAliveReceiver extends BroadcastReceiver { Thread t = new Thread(new Runnable() { @Override public void run() { - pump.updateStatus("KeepAlive. Status outdated."); + pump.refreshDataFromPump("KeepAlive. Status outdated."); } }); t.start(); @@ -70,7 +66,7 @@ public class KeepAliveReceiver extends BroadcastReceiver { Thread t = new Thread(new Runnable() { @Override public void run() { - pump.updateStatus("KeepAlive. Basal outdated."); + pump.refreshDataFromPump("KeepAlive. Basal outdated."); } }); t.start(); diff --git a/app/src/main/java/info/nightscout/utils/BatteryLevel.java b/app/src/main/java/info/nightscout/utils/BatteryLevel.java new file mode 100644 index 0000000000..44f6b6e0e5 --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/BatteryLevel.java @@ -0,0 +1,28 @@ +package info.nightscout.utils; + +import android.content.Intent; +import android.content.IntentFilter; +import android.os.BatteryManager; + +import info.nightscout.androidaps.MainApp; + +/** + * Created by mike on 20.02.2017. + */ + +public class BatteryLevel { + static public int lastUploadedLevel = 0; + + static public int getBatteryLevel() { + Intent batteryIntent = MainApp.instance().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + if (batteryIntent != null) { + int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); + int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); + if (level == -1 || scale == -1) { + return 50; + } + return (int) (((float) level / (float) scale) * 100.0f); + } else return 50; + } + +} diff --git a/app/src/main/java/info/nightscout/utils/BolusWizard.java b/app/src/main/java/info/nightscout/utils/BolusWizard.java index 80e907bb6f..c3607cc89a 100644 --- a/app/src/main/java/info/nightscout/utils/BolusWizard.java +++ b/app/src/main/java/info/nightscout/utils/BolusWizard.java @@ -6,7 +6,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.TempBasalsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; /** * Created by mike on 11.10.2016. diff --git a/app/src/main/java/info/nightscout/utils/LocaleHelper.java b/app/src/main/java/info/nightscout/utils/LocaleHelper.java index 1d89c7d689..c8faa83b9d 100644 --- a/app/src/main/java/info/nightscout/utils/LocaleHelper.java +++ b/app/src/main/java/info/nightscout/utils/LocaleHelper.java @@ -40,8 +40,7 @@ public class LocaleHelper { } private static String getPersistedData(Context context, String defaultLanguage) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); + return SP.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { diff --git a/app/src/main/java/info/nightscout/utils/PasswordProtection.java b/app/src/main/java/info/nightscout/utils/PasswordProtection.java index 2b8d7a59c1..1af10eb2d2 100644 --- a/app/src/main/java/info/nightscout/utils/PasswordProtection.java +++ b/app/src/main/java/info/nightscout/utils/PasswordProtection.java @@ -3,8 +3,6 @@ package info.nightscout.utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; @@ -19,7 +17,6 @@ import info.nightscout.androidaps.R; public class PasswordProtection { static public boolean isLocked(String preference) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); final String password = SP.getString(preference, ""); if (password.equals("")) { return false; @@ -28,7 +25,6 @@ public class PasswordProtection { } static public void QueryPassword(final Context context, int stringID, String preference, final Runnable ok, final Runnable fail) { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); final String password = SP.getString(preference, ""); if (password.equals("")) { if (ok != null) ok.run(); diff --git a/app/src/main/java/info/nightscout/utils/SP.java b/app/src/main/java/info/nightscout/utils/SP.java new file mode 100644 index 0000000000..3626d7c69e --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/SP.java @@ -0,0 +1,90 @@ +package info.nightscout.utils; + +import android.content.SharedPreferences; +import android.preference.PreferenceManager; + +import info.nightscout.androidaps.MainApp; + +/** + * Created by mike on 17.02.2017. + */ + +public class SP { + static SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + + static public boolean contains(String key) { + return sharedPreferences.contains(key); + } + + static public String getString(int resourceID, String defaultValue) { + return sharedPreferences.getString(MainApp.sResources.getString(resourceID), defaultValue); + } + + static public String getString(String key, String defaultValue) { + return sharedPreferences.getString(key, defaultValue); + } + + static public boolean getBoolean(int resourceID, boolean defaultValue) { + try { + return sharedPreferences.getBoolean(MainApp.sResources.getString(resourceID), defaultValue); + } catch (Exception e) { + return defaultValue; + } + } + + static public boolean getBoolean(String key, boolean defaultValue) { + try { + return sharedPreferences.getBoolean(key, defaultValue); + } catch (Exception e) { + return defaultValue; + } + } + + static public Double getDouble(int resourceID, Double defaultValue) { + return SafeParse.stringToDouble(sharedPreferences.getString(MainApp.sResources.getString(resourceID), defaultValue.toString())); + } + + static public Double getDouble(String key, Double defaultValue) { + return SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())); + } + + static public int getInt(int resourceID, Integer defaultValue) { + return SafeParse.stringToInt(sharedPreferences.getString(MainApp.sResources.getString(resourceID), defaultValue.toString())); + } + + static public int getInt(String key, Integer defaultValue) { + return SafeParse.stringToInt(sharedPreferences.getString(key, defaultValue.toString())); + } + + static public long getLong(int resourceID, Long defaultValue) { + return SafeParse.stringToLong(sharedPreferences.getString(MainApp.sResources.getString(resourceID), defaultValue.toString())); + } + + static public long getLong(String key, Long defaultValue) { + return SafeParse.stringToLong(sharedPreferences.getString(key, defaultValue.toString())); + } + + static public void putBoolean(String key, boolean value) { + SharedPreferences.Editor editor = sharedPreferences.edit(); + editor.putBoolean(key, value); + editor.apply(); + } + + static public void putBoolean(int resourceID, boolean value) { + SharedPreferences.Editor editor = sharedPreferences.edit(); + editor.putBoolean(MainApp.sResources.getString(resourceID), value); + editor.apply(); + } + + static public void putString(String key, String value) { + SharedPreferences.Editor editor = sharedPreferences.edit(); + editor.putString(key, value); + editor.apply(); + } + + static public void putString(int resourceID, String value) { + SharedPreferences.Editor editor = sharedPreferences.edit(); + editor.putString(MainApp.sResources.getString(resourceID), value); + editor.apply(); + } +} diff --git a/app/src/main/java/info/nightscout/utils/XdripCalibrations.java b/app/src/main/java/info/nightscout/utils/XdripCalibrations.java index 338304d790..53c3bf45ec 100644 --- a/app/src/main/java/info/nightscout/utils/XdripCalibrations.java +++ b/app/src/main/java/info/nightscout/utils/XdripCalibrations.java @@ -17,7 +17,7 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.Services.Intents; -import info.nightscout.client.data.NSProfile; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; /** * Created by mike on 10.02.2017. diff --git a/app/src/main/res/layout/nsclientinternal_fragment.xml b/app/src/main/res/layout/nsclientinternal_fragment.xml new file mode 100644 index 0000000000..580df825ca --- /dev/null +++ b/app/src/main/res/layout/nsclientinternal_fragment.xml @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/overview_fragment.xml b/app/src/main/res/layout/overview_fragment.xml index 939f506890..26d53c7e9a 100644 --- a/app/src/main/res/layout/overview_fragment.xml +++ b/app/src/main/res/layout/overview_fragment.xml @@ -21,6 +21,7 @@ + android:textAppearance="?android:attr/textAppearanceSmall" /> + android:textColor="@color/mdtp_white" /> + android:textAppearance="?android:attr/textAppearanceMedium" /> + android:gravity="center_horizontal" + android:orientation="horizontal"> Прекъсване Презареждане IOB на помпата - Парола за помпа + Парола за помпа пълнене Общо %d записа са изпратени Приложено diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 835421fbb0..001d624c96 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -265,7 +265,7 @@ Nahrávám Pumpa je zaneprázdněna Špatné heslo k pumpě - Heslo k pumpě + Heslo k pumpě Okluze Podáno Stop diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index abf9b60b58..77af750cf3 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -259,7 +259,7 @@ Glukose Füllmenge Unterbrechungen - Pumpen-Passwort + Pumpen-Passwort Essensbolus Kein Profil gewählt Stop diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index bd95743215..7d28d6ef7f 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -275,7 +275,7 @@ Rellenar Suspender Conexión de %d s - Contraseña de la bomba + Contraseña de la bomba Contraseña de la bomba incorrecta! Bomba ocupada Entregado diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index b45c7393b0..9c947244c0 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -278,7 +278,7 @@ 교체 중지 %d 초 동안 연결중 - 펌프 비밀번호 + 펌프 비밀번호 펌프 비밀번호가 잘못되었습니다! 펌프가 바쁩니다 주입됨 diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 91658da020..04dc1e3798 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -3,7 +3,7 @@ #3F51B5 #303F9F #FF4081 - #ff2630 + #00695c #121212 #779ECB diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 23fddfed1f..58e2375142 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -294,7 +294,7 @@ Refill Suspend Connecting for %d s - Pump password + Pump password Wrong pump password! Pump is busy Delivered @@ -507,6 +507,36 @@ Password for settings Unlock settings Approaching insulin daily limit + NSClient internal + NSCI + URL: + Autoscroll + Restart + Internal NSClient + Nightscout URL + Enter Nightscout URL + NS API secret + NS API secret + Enter NS API secret (min 12 chars) + Device name + Enter device name + It will be used for enteredBy field + Deliver now + Clear queue + Show queue + Queue: + Status: + Paused + nsclientinternal_url + nsclientinternal_api_secret + danar_bt_name + danar_password + danar_useextended + danarprofile_dia + Clear log + nsclientinternal_autoscroll + nsclientinternal_paused + NSCLIENT has no write permission Wear settings Show detailed IOB Break down IOB into bolus and basal IOB on the watchface diff --git a/app/src/main/res/xml/pref_danar.xml b/app/src/main/res/xml/pref_danar.xml index d0ca8a997a..9d5c86a535 100644 --- a/app/src/main/res/xml/pref_danar.xml +++ b/app/src/main/res/xml/pref_danar.xml @@ -6,16 +6,16 @@ diff --git a/app/src/main/res/xml/pref_danarprofile.xml b/app/src/main/res/xml/pref_danarprofile.xml index 5e864d7561..68be80566a 100644 --- a/app/src/main/res/xml/pref_danarprofile.xml +++ b/app/src/main/res/xml/pref_danarprofile.xml @@ -5,7 +5,7 @@ android:title="@string/danarprofile"> diff --git a/app/src/main/res/xml/pref_nsclientinternal.xml b/app/src/main/res/xml/pref_nsclientinternal.xml new file mode 100644 index 0000000000..f6ea0cb48e --- /dev/null +++ b/app/src/main/res/xml/pref_nsclientinternal.xml @@ -0,0 +1,26 @@ + + + + + + + + + + \ No newline at end of file