diff --git a/app/build.gradle b/app/build.gradle
index 31de31b970..d656fa97d9 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -43,8 +43,8 @@ android {
applicationId "info.nightscout.androidaps"
minSdkVersion 21
targetSdkVersion 23
- versionCode 1100
- version "1.33"
+ versionCode 1500
+ version "1.5"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild()
}
@@ -168,8 +168,8 @@ dependencies {
compile 'com.google.android.gms:play-services-wearable:7.5.0'
compile 'junit:junit:4.12'
testCompile 'org.json:json:20140107'
- testCompile 'org.mockito:mockito-core:2.+'
- androidTestCompile 'org.mockito:mockito-core:2.+'
+ testCompile 'org.mockito:mockito-core:2.7.22'
+ androidTestCompile 'org.mockito:mockito-core:2.7.22'
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')
@@ -177,11 +177,7 @@ dependencies {
// 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'
+ compile 'com.google.code.gson:gson:2.7'
+ compile 'com.google.guava:guava:20.0'
- compile ('com.jakewharton:butterknife:8.5.1') {
- exclude module: 'support-compat'
- }
- annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}
\ No newline at end of file
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index e01ed53f34..c4f9bcfe04 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -41,10 +41,10 @@
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
-
-
-
-
+
+
+
+
@@ -116,11 +116,16 @@
android:name=".Services.DataService"
android:exported="false" />
+
Build.VERSION_CODES.LOLLIPOP_MR1) {
askForPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
@@ -69,23 +77,7 @@ public class MainActivity extends AppCompatActivity {
if (Config.logFunctionCalls)
log.debug("onCreate");
- // show version in toolbar
- setTitle(getString(R.string.app_name) + " " + BuildConfig.VERSION);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
registerBus();
-
- try {
- getSupportActionBar().setDisplayShowHomeEnabled(true);
- if (BuildConfig.NSCLIENTOLNY)
- getSupportActionBar().setIcon(R.mipmap.yellowowl);
- else
- getSupportActionBar().setIcon(R.mipmap.blueowl);
- } catch (NullPointerException e) {
- // no action
- }
-
-
setUpTabs(false);
}
@@ -119,79 +111,6 @@ public class MainActivity extends AppCompatActivity {
mPager.setCurrentItem(pageAdapter.getCount() - 1, false);
}
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- int id = item.getItemId();
- switch (id) {
- case R.id.nav_preferences:
- PasswordProtection.QueryPassword(this, R.string.settings_password, "settings_password", new Runnable() {
- @Override
- public void run() {
- Intent i = new Intent(getApplicationContext(), PreferencesActivity.class);
- startActivity(i);
- }
- }, null);
- break;
- case R.id.nav_resetdb:
- new AlertDialog.Builder(this)
- .setTitle(R.string.nav_resetdb)
- .setMessage(R.string.reset_db_confirm)
- .setNegativeButton(android.R.string.cancel, null)
- .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- MainApp.getDbHelper().resetDatabases();
- }
- })
- .create()
- .show();
- break;
- case R.id.nav_export:
- ImportExportPrefs.verifyStoragePermissions(this);
- ImportExportPrefs.exportSharedPreferences(this);
- break;
- case R.id.nav_import:
- ImportExportPrefs.verifyStoragePermissions(this);
- ImportExportPrefs.importSharedPreferences(this);
- break;
- case R.id.nav_show_logcat:
- LogDialog.showLogcat(this);
- break;
-// case R.id.nav_test_alarm:
-// final int REQUEST_CODE_ASK_PERMISSIONS = 2355;
-// int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW);
-// if (permission != PackageManager.PERMISSION_GRANTED) {
-// // We don't have permission so prompt the user
-// // On Android 6 give permission for alarming in Settings -> Apps -> Draw over other apps
-// ActivityCompat.requestPermissions(
-// this,
-// new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW},
-// REQUEST_CODE_ASK_PERMISSIONS
-// );
-// }
-// Intent alertServiceIntent = new Intent(getApplicationContext(), AlertService.class);
-// alertServiceIntent.putExtra("alertText", getString(R.string.nav_test_alert));
-// getApplicationContext().startService(alertServiceIntent);
-// break;
- case R.id.nav_exit:
- log.debug("Exiting");
- MainApp.instance().stopKeepAliveService();
- MainApp.bus().post(new EventAppExit());
- MainApp.closeDbHelper();
- finish();
- System.runFinalization();
- System.exit(0);
- break;
- }
- return super.onOptionsItemSelected(item);
- }
-
private void registerBus() {
try {
MainApp.bus().unregister(this);
@@ -243,7 +162,7 @@ public class MainActivity extends AppCompatActivity {
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
log.debug("Requesting ignore battery optimization");
- OKDialog.show(this, getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() {
+ OKDialog.show(getParent(), getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() {
@Override
public void run() {
@@ -325,4 +244,81 @@ public class MainActivity extends AppCompatActivity {
}
return super.dispatchTouchEvent(event);
}
+
+ @Override
+ public void onClick(final View v) {
+ final Activity activity = this;
+ switch (v.getId()) {
+ case R.id.overview_menuButton:
+ PopupMenu popup = new PopupMenu(v.getContext(), v);
+ MenuInflater inflater = popup.getMenuInflater();
+ inflater.inflate(R.menu.menu_main, popup.getMenu());
+ popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
+ @Override
+ public boolean onMenuItemClick(MenuItem item) {
+ int id = item.getItemId();
+ switch (id) {
+ case R.id.nav_preferences:
+ PasswordProtection.QueryPassword(v.getContext(), R.string.settings_password, "settings_password", new Runnable() {
+ @Override
+ public void run() {
+ Intent i = new Intent(v.getContext(), PreferencesActivity.class);
+ startActivity(i);
+ }
+ }, null);
+ break;
+ case R.id.nav_resetdb:
+ new AlertDialog.Builder(v.getContext())
+ .setTitle(R.string.nav_resetdb)
+ .setMessage(R.string.reset_db_confirm)
+ .setNegativeButton(android.R.string.cancel, null)
+ .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog, int which) {
+ MainApp.getDbHelper().resetDatabases();
+ }
+ })
+ .create()
+ .show();
+ break;
+ case R.id.nav_export:
+ ImportExportPrefs.verifyStoragePermissions(activity);
+ ImportExportPrefs.exportSharedPreferences(activity);
+ break;
+ case R.id.nav_import:
+ ImportExportPrefs.verifyStoragePermissions(activity);
+ ImportExportPrefs.importSharedPreferences(activity);
+ break;
+ case R.id.nav_show_logcat:
+ LogDialog.showLogcat(v.getContext());
+ break;
+ case R.id.nav_about:
+ AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
+ builder.setTitle(getString(R.string.app_name) + " " + BuildConfig.VERSION);
+ if (Config.NSCLIENT)
+ builder.setIcon(R.mipmap.yellowowl);
+ else
+ builder.setIcon(R.mipmap.blueowl);
+ builder.setMessage("Build: " + BuildConfig.BUILDVERSION);
+ builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
+ AlertDialog alertDialog = builder.create();
+ alertDialog.show();
+ break;
+ case R.id.nav_exit:
+ log.debug("Exiting");
+ MainApp.instance().stopKeepAliveService();
+ MainApp.bus().post(new EventAppExit());
+ MainApp.closeDbHelper();
+ finish();
+ System.runFinalization();
+ System.exit(0);
+ break;
+ }
+ return false;
+ }
+ });
+ popup.show();
+ break;
+ }
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java
index 6568e03a53..1e49b03d73 100644
--- a/app/src/main/java/info/nightscout/androidaps/MainApp.java
+++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java
@@ -18,38 +18,47 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import info.nightscout.androidaps.db.DatabaseHelper;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
-import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfileFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanFragment;
-import info.nightscout.androidaps.plugins.LocalProfile.LocalProfileFragment;
+import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesFragment;
+import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyFragment;
+import info.nightscout.androidaps.plugins.InsulinFastacting.InsulinFastactingFragment;
+import info.nightscout.androidaps.plugins.InsulinFastactingProlonged.InsulinFastactingProlongedFragment;
+import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorFragment;
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;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
-import info.nightscout.androidaps.plugins.SafetyFragment.SafetyFragment;
-import info.nightscout.androidaps.plugins.SimpleProfile.SimpleProfileFragment;
+import info.nightscout.androidaps.plugins.Persistentnotification.PersistentNotificationPlugin;
+import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfileFragment;
+import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfileFragment;
+import info.nightscout.androidaps.plugins.ProfileNS.NSProfileFragment;
+import info.nightscout.androidaps.plugins.ProfileSimple.SimpleProfileFragment;
+import info.nightscout.androidaps.plugins.PumpDanaR.DanaRFragment;
+import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
+import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanFragment;
+import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
+import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Fragment;
+import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService;
+import info.nightscout.androidaps.plugins.PumpMDI.MDIFragment;
+import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpFragment;
+import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorFragment;
import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpFragment;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gFragment;
import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientFragment;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripFragment;
-import info.nightscout.androidaps.plugins.TempBasals.TempBasalsFragment;
-import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangeFragment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment;
-import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpFragment;
import info.nightscout.androidaps.plugins.Wear.WearFragment;
-import info.nightscout.androidaps.plugins.persistentnotification.PersistentNotificationPlugin;
+import info.nightscout.androidaps.plugins.XDripStatusline.StatuslineFragment;
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
+import info.nightscout.utils.NSUpload;
import io.fabric.sdk.android.Fabric;
@@ -85,31 +94,38 @@ public class MainApp extends Application {
pluginsList = new ArrayList<>();
// Register all tabs in app here
pluginsList.add(OverviewFragment.getPlugin());
+ pluginsList.add(IobCobCalculatorFragment.getPlugin());
if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
+ pluginsList.add(InsulinFastactingFragment.getPlugin());
+ pluginsList.add(InsulinFastactingProlongedFragment.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRFragment.getPlugin());
- if (Config.DANARKOREAN) pluginsList.add(DanaRKoreanFragment.getPlugin());
+ if (Config.DANAR) pluginsList.add(DanaRKoreanFragment.getPlugin());
+ if (Config.DANARv2) pluginsList.add(DanaRv2Fragment.getPlugin());
pluginsList.add(CareportalFragment.getPlugin());
if (Config.MDI) pluginsList.add(MDIFragment.getPlugin());
- if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpFragment.getPlugin());
+ if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getInstance());
if (Config.LOOPENABLED) pluginsList.add(LoopFragment.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSMAFragment.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSAMAFragment.getPlugin());
pluginsList.add(NSProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(SimpleProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(LocalProfileFragment.getPlugin());
- if (Config.OTHERPROFILES) pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
- if (Config.APS) pluginsList.add(TempTargetRangeFragment.getPlugin());
+ if (Config.OTHERPROFILES)
+ pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
pluginsList.add(TreatmentsFragment.getPlugin());
- if (Config.TEMPBASALS) pluginsList.add(TempBasalsFragment.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyFragment.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin());
- pluginsList.add(SourceXdripFragment.getPlugin());
+ if (!Config.NSCLIENT)
+ pluginsList.add(SourceXdripFragment.getPlugin());
pluginsList.add(SourceNSClientFragment.getPlugin());
- pluginsList.add(SourceMM640gFragment.getPlugin());
- pluginsList.add(SourceGlimpFragment.getPlugin());
+ if (!Config.NSCLIENT)
+ pluginsList.add(SourceMM640gFragment.getPlugin());
+ if (!Config.NSCLIENT)
+ pluginsList.add(SourceGlimpFragment.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorFragment.getPlugin());
if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this));
+ pluginsList.add(StatuslineFragment.getPlugin(this));
pluginsList.add(new PersistentNotificationPlugin(this));
pluginsList.add(NSClientInternalFragment.getPlugin());
@@ -117,7 +133,7 @@ public class MainApp extends Application {
MainApp.getConfigBuilder().initialize();
}
- MainApp.getConfigBuilder().uploadAppStart();
+ NSUpload.uploadAppStart();
startKeepAliveService();
@@ -140,18 +156,18 @@ public class MainApp extends Application {
if (keepAliveReceiver == null) {
keepAliveReceiver = new KeepAliveReceiver();
if (Config.DANAR) {
- startService(new Intent(this, info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService.class));
- startService(new Intent(this, info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService.class));
+ startService(new Intent(this, DanaRExecutionService.class));
+ startService(new Intent(this, DanaRKoreanExecutionService.class));
+ startService(new Intent(this, DanaRv2ExecutionService.class));
}
keepAliveReceiver.setAlarm(this);
}
}
-
- public void stopKeepAliveService(){
- if(keepAliveReceiver!=null)
- keepAliveReceiver.cancelAlarm(this);
+ public void stopKeepAliveService() {
+ if (keepAliveReceiver != null)
+ keepAliveReceiver.cancelAlarm(this);
}
public static Bus bus() {
@@ -198,6 +214,36 @@ public class MainApp extends Application {
return newList;
}
+ @Nullable
+ public static InsulinInterface getInsulinIterfaceById(int id) {
+ ArrayList newList = new ArrayList<>();
+
+ if (pluginsList != null) {
+ for (PluginBase p : pluginsList) {
+ if (p.getType() == PluginBase.INSULIN && ((InsulinInterface) p).getId() == id)
+ return (InsulinInterface) p;
+ }
+ } else {
+ log.error("InsulinInterface not found");
+ }
+ return null;
+ }
+
+ public static ArrayList getSpecificPluginsVisibleInList(int type) {
+ ArrayList newList = new ArrayList<>();
+
+ if (pluginsList != null) {
+ for (PluginBase p : pluginsList) {
+ if (p.getType() == type)
+ if (p.showInList(type))
+ newList.add(p);
+ }
+ } else {
+ log.error("pluginsList=null");
+ }
+ return newList;
+ }
+
public static ArrayList getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList newList = new ArrayList<>();
@@ -212,6 +258,21 @@ public class MainApp extends Application {
return newList;
}
+ public static ArrayList getSpecificPluginsVisibleInListByInterface(Class interfaceClass, int type) {
+ ArrayList newList = new ArrayList<>();
+
+ if (pluginsList != null) {
+ for (PluginBase p : pluginsList) {
+ if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
+ if (p.showInList(type))
+ newList.add(p);
+ }
+ } else {
+ log.error("pluginsList=null");
+ }
+ return newList;
+ }
+
@Nullable
public static PluginBase getSpecificPlugin(Class pluginClass) {
if (pluginsList != null) {
diff --git a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java
index 29a4913bc3..d3d52298aa 100644
--- a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java
@@ -14,13 +14,15 @@ import android.preference.PreferenceManager;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui;
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.PumpDanaR.BluetoothDevicePreference;
+import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
+import info.nightscout.androidaps.plugins.PumpDanaRKorean.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.PumpDanaRv2.DanaRv2Plugin;
+import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
+import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.utils.LocaleHelper;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@@ -109,10 +111,14 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
if (Config.DANAR) {
DanaRPlugin danaRPlugin = (DanaRPlugin) MainApp.getSpecificPlugin(DanaRPlugin.class);
DanaRKoreanPlugin danaRKoreanPlugin = (DanaRKoreanPlugin) MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
+ DanaRv2Plugin danaRv2Plugin = (DanaRv2Plugin) MainApp.getSpecificPlugin(DanaRv2Plugin.class);
if (danaRPlugin.isEnabled(PluginBase.PUMP) || danaRKoreanPlugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_danar);
}
- if (danaRPlugin.isEnabled(PluginBase.PROFILE) || danaRKoreanPlugin.isEnabled(PluginBase.PROFILE)) {
+ if (danaRv2Plugin != null && danaRv2Plugin.isEnabled(PluginBase.PUMP)) {
+ addPreferencesFromResource(R.xml.pref_danarv2);
+ }
+ if (danaRPlugin.isEnabled(PluginBase.PROFILE) || danaRKoreanPlugin.isEnabled(PluginBase.PROFILE) || danaRv2Plugin != null && danaRv2Plugin.isEnabled(PluginBase.PROFILE)) {
addPreferencesFromResource(R.xml.pref_danarprofile);
}
}
@@ -138,6 +144,11 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
}
}
+ StatuslinePlugin statuslinePlugin = (StatuslinePlugin) MainApp.getSpecificPlugin(StatuslinePlugin.class);
+ if (statuslinePlugin != null && statuslinePlugin.isEnabled(PluginBase.GENERAL)) {
+ addPreferencesFromResource(R.xml.pref_xdripstatus);
+ }
+
initSummary(getPreferenceScreen());
}
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 f45e59f4c1..def268bd35 100644
--- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java
+++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java
@@ -2,56 +2,42 @@ package info.nightscout.androidaps.Services;
import android.app.IntentService;
import android.content.Intent;
-import android.content.SharedPreferences;
import android.os.Bundle;
-import android.preference.PreferenceManager;
import android.provider.Telephony;
-import com.j256.ormlite.dao.Dao;
-import com.j256.ormlite.stmt.PreparedQuery;
-import com.j256.ormlite.stmt.QueryBuilder;
-import com.j256.ormlite.stmt.Where;
-
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.sql.SQLException;
import java.util.Date;
-import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.DanaRHistoryRecord;
-import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.db.Treatment;
-import info.nightscout.androidaps.events.EventNewBG;
+import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventNewBasalProfile;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.DanaR.History.DanaRNSHistorySync;
-import info.nightscout.androidaps.plugins.NSProfile.NSProfilePlugin;
-import info.nightscout.androidaps.plugins.Objectives.ObjectivesPlugin;
+import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
+import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
+import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
+import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
+import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
+import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin;
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.androidaps.plugins.NSClientInternal.data.NSProfile;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
+import info.nightscout.utils.SP;
public class DataService extends IntentService {
@@ -94,10 +80,9 @@ public class DataService extends IntentService {
glimpEnabled = true;
}
- boolean isNSProfile = ConfigBuilderPlugin.getActiveProfile().getClass().equals(NSProfilePlugin.class);
+ boolean isNSProfile = ConfigBuilderPlugin.getActiveProfileInterface().getClass().equals(NSProfilePlugin.class);
- SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
- boolean nsUploadOnly = SP.getBoolean("ns_upload_only", false);
+ boolean nsUploadOnly = SP.getBoolean(R.string.key_ns_upload_only, false);
if (intent != null) {
final String action = intent.getAction();
@@ -121,7 +106,7 @@ public class DataService extends IntentService {
// Objectives 0
ObjectivesPlugin.bgIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
- } else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action)) {
+ } else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) {
// always handle Profile if NSProfile is enabled without looking at nsUploadOnly
handleNewDataFromNSClient(intent);
} else if (!nsUploadOnly &&
@@ -178,25 +163,10 @@ public class DataService extends IntentService {
bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE);
bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME);
- bgReading.battery_level = bundle.getInt(Intents.EXTRA_SENSOR_BATTERY);
- bgReading.timeIndex = bundle.getLong(Intents.EXTRA_TIMESTAMP);
+ bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP);
bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW);
- if (bgReading.timeIndex < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) {
- if (Config.logIncommingBG)
- log.debug("Ignoring old XDRIPREC BG " + bgReading.toString());
- return;
- }
-
- if (Config.logIncommingBG)
- log.debug("XDRIPREC BG " + bgReading.toString());
-
- try {
- MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- MainApp.bus().post(new EventNewBG());
+ MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP");
}
private void handleNewDataFromGlimp(Intent intent) {
@@ -207,20 +177,10 @@ public class DataService extends IntentService {
bgReading.value = bundle.getDouble("mySGV");
bgReading.direction = bundle.getString("myTrend");
- bgReading.battery_level = bundle.getInt("myBatLvl");
- bgReading.timeIndex = bundle.getLong("myTimestamp");
+ bgReading.date = bundle.getLong("myTimestamp");
bgReading.raw = 0;
- if (Config.logIncommingBG)
- log.debug(bundle.toString());
- log.debug("GLIMP BG " + bgReading.toString());
-
- try {
- MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- MainApp.bus().post(new EventNewBG());
+ MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP");
}
private void handleNewDataFromMM640g(Intent intent) {
@@ -245,23 +205,10 @@ public class DataService extends IntentService {
bgReading.value = json_object.getDouble("sgv");
bgReading.direction = json_object.getString("direction");
- bgReading.timeIndex = json_object.getLong("date");
+ bgReading.date = json_object.getLong("date");
bgReading.raw = json_object.getDouble("sgv");
- if (bgReading.timeIndex < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) {
- if (Config.logIncommingBG)
- log.debug("Ignoring old MM640g BG " + bgReading.toString());
- return;
- }
-
- if (Config.logIncommingBG)
- log.debug("MM640g BG " + bgReading.toString());
-
- try {
- MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading);
- } catch (SQLException e) {
- e.printStackTrace();
- }
+ MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g");
break;
default:
log.debug("Unknown entries type: " + type);
@@ -272,7 +219,6 @@ public class DataService extends IntentService {
}
}
}
- MainApp.bus().post(new EventNewBG());
}
private void handleNewDataFromNSClient(Intent intent) {
@@ -353,25 +299,12 @@ public class DataService extends IntentService {
try {
String activeProfile = bundles.getString("activeprofile");
String profile = bundles.getString("profile");
- NSProfile nsProfile = new NSProfile(new JSONObject(profile), activeProfile);
- MainApp.bus().post(new EventNewBasalProfile(nsProfile));
+ ProfileStore profileStore = new ProfileStore(new JSONObject(profile));
+ NSProfilePlugin.storeNewProfile(profileStore);
+ MainApp.bus().post(new EventNewBasalProfile());
- PumpInterface pump = MainApp.getConfigBuilder();
- if (pump != null) {
- SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
- if (SP.getBoolean("syncprofiletopump", false)) {
- if (pump.setNewBasalProfile(nsProfile) == PumpInterface.SUCCESS) {
- SmsCommunicatorPlugin smsCommunicatorPlugin = (SmsCommunicatorPlugin) MainApp.getSpecificPlugin(SmsCommunicatorPlugin.class);
- if (smsCommunicatorPlugin != null && smsCommunicatorPlugin.isEnabled(PluginBase.GENERAL)) {
- smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.sResources.getString(R.string.profile_set_ok));
- }
- }
- }
- } else {
- log.error("No active pump selected");
- }
if (Config.logIncommingData)
- log.debug("Received profile: " + activeProfile + " " + profile);
+ log.debug("Received profileStore: " + activeProfile + " " + profile);
} catch (JSONException e) {
e.printStackTrace();
}
@@ -380,7 +313,7 @@ public class DataService extends IntentService {
try {
if (bundles.containsKey("treatment")) {
String trstring = bundles.getString("treatment");
- handleAddedTreatment(trstring);
+ handleAddChangeDataFromNS(trstring);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
@@ -388,7 +321,7 @@ public class DataService extends IntentService {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject trJson = jsonArray.getJSONObject(i);
String trstr = trJson.toString();
- handleAddedTreatment(trstr);
+ handleAddChangeDataFromNS(trstr);
}
}
} catch (Exception e) {
@@ -401,7 +334,7 @@ public class DataService extends IntentService {
try {
if (bundles.containsKey("treatment")) {
String trstring = bundles.getString("treatment");
- handleChangedTreatment(trstring);
+ handleAddChangeDataFromNS(trstring);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
@@ -409,7 +342,7 @@ public class DataService extends IntentService {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject trJson = jsonArray.getJSONObject(i);
String trstr = trJson.toString();
- handleChangedTreatment(trstr);
+ handleAddChangeDataFromNS(trstr);
}
}
} catch (Exception e) {
@@ -423,8 +356,7 @@ public class DataService extends IntentService {
String trstring = bundles.getString("treatment");
JSONObject trJson = new JSONObject(trstring);
String _id = trJson.getString("_id");
- MainApp.getDbHelper().delete(_id);
- handleRemoveTempTargetRecord(trJson);
+ handleRemovedRecordFromNS(_id);
}
if (bundles.containsKey("treatments")) {
@@ -433,8 +365,7 @@ public class DataService extends IntentService {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject trJson = jsonArray.getJSONObject(i);
String _id = trJson.getString("_id");
- MainApp.getDbHelper().delete(_id);
- handleRemoveTempTargetRecord(trJson);
+ handleRemovedRecordFromNS(_id);
}
}
} catch (Exception e) {
@@ -449,14 +380,7 @@ public class DataService extends IntentService {
JSONObject sgvJson = new JSONObject(sgvstring);
NSSgv nsSgv = new NSSgv(sgvJson);
BgReading bgReading = new BgReading(nsSgv);
- if (bgReading.timeIndex < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) {
- if (Config.logIncommingData)
- log.debug("Ignoring old BG: " + bgReading.toString());
- return;
- }
- MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading);
- if (Config.logIncommingData)
- log.debug("ADD: Stored new BG: " + bgReading.toString());
+ MainApp.getDbHelper().createIfNotExists(bgReading, "NS");
}
if (bundles.containsKey("sgvs")) {
@@ -466,244 +390,129 @@ public class DataService extends IntentService {
JSONObject sgvJson = jsonArray.getJSONObject(i);
NSSgv nsSgv = new NSSgv(sgvJson);
BgReading bgReading = new BgReading(nsSgv);
- if (bgReading.timeIndex < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) {
- if (Config.logIncommingData)
- log.debug("Ignoring old BG: " + bgReading.toString());
- } else {
- MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading);
- if (Config.logIncommingData)
- log.debug("ADD: Stored new BG: " + bgReading.toString());
- }
+ MainApp.getDbHelper().createIfNotExists(bgReading, "NS");
}
}
} catch (Exception e) {
e.printStackTrace();
}
- MainApp.bus().post(new EventNewBG());
}
if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) {
- log.error("Not implemented yet"); // TODO implemeng MBGS
- }
- }
+ try {
+ if (bundles.containsKey("mbg")) {
+ String mbgstring = bundles.getString("mbg");
+ JSONObject mbgJson = new JSONObject(mbgstring);
+ NSMbg nsMbg = new NSMbg(mbgJson);
+ CareportalEvent careportalEvent = new CareportalEvent(nsMbg);
+ MainApp.getDbHelper().createOrUpdate(careportalEvent);
+ if (Config.logIncommingData)
+ log.debug("Adding/Updating new MBG: " + careportalEvent.log());
+ }
- private void handleAddedTreatment(String trstring) throws JSONException, SQLException {
- JSONObject trJson = new JSONObject(trstring);
- handleDanaRHistoryRecords(trJson); // update record _id in history
- handleAddChangeTempTargetRecord(trJson);
- if (!trJson.has("insulin") && !trJson.has("carbs")) {
- if (Config.logIncommingData)
- log.debug("ADD: Uninterested treatment: " + trstring);
- return;
- }
-
- Treatment stored = null;
- String _id = trJson.getString("_id");
-
- if (trJson.has("timeIndex")) {
- if (Config.logIncommingData)
- log.debug("ADD: timeIndex found: " + trstring);
- stored = MainApp.getDbHelper().findTreatmentByTimeIndex(trJson.getLong("timeIndex"));
- } else {
- stored = MainApp.getDbHelper().findTreatmentById(_id);
- }
-
- if (stored != null) {
- if (Config.logIncommingData)
- log.debug("ADD: Existing treatment: " + trstring);
- if (trJson.has("timeIndex")) {
- stored._id = _id;
- int updated = MainApp.getDbHelper().update(stored);
- if (Config.logIncommingData)
- log.debug("Records updated: " + updated);
- }
- } else {
- if (Config.logIncommingData)
- log.debug("ADD: New treatment: " + trstring);
- Treatment treatment = new Treatment();
- treatment._id = _id;
- treatment.carbs = trJson.has("carbs") ? trJson.getDouble("carbs") : 0;
- treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d;
- treatment.created_at = new Date(trJson.getLong("mills"));
- if (trJson.has("eventType")) {
- treatment.mealBolus = true;
- if (trJson.get("eventType").equals("Correction Bolus"))
- treatment.mealBolus = false;
- double carbs = treatment.carbs;
- if (trJson.has("boluscalc")) {
- JSONObject boluscalc = trJson.getJSONObject("boluscalc");
- if (boluscalc.has("carbs")) {
- carbs = Math.max(boluscalc.getDouble("carbs"), carbs);
+ if (bundles.containsKey("mbgs")) {
+ String sgvstring = bundles.getString("mbgs");
+ JSONArray jsonArray = new JSONArray(sgvstring);
+ for (int i = 0; i < jsonArray.length(); i++) {
+ JSONObject mbgJson = jsonArray.getJSONObject(i);
+ NSMbg nsMbg = new NSMbg(mbgJson);
+ CareportalEvent careportalEvent = new CareportalEvent(nsMbg);
+ MainApp.getDbHelper().createOrUpdate(careportalEvent);
+ if (Config.logIncommingData)
+ log.debug("Adding/Updating new MBG: " + careportalEvent.log());
}
}
- if (carbs <= 0)
- treatment.mealBolus = false;
+ } catch (Exception e) {
+ e.printStackTrace();
}
- treatment.setTimeIndex(treatment.getTimeIndex());
- MainApp.getDbHelper().createOrUpdate(treatment);
- if (Config.logIncommingData)
- log.debug("ADD: Stored treatment: " + treatment.log());
}
}
- private void handleChangedTreatment(String trstring) throws JSONException, SQLException {
+ private void handleRemovedRecordFromNS(String _id) {
+ MainApp.getDbHelper().deleteTreatmentById(_id);
+ MainApp.getDbHelper().deleteTempTargetById(_id);
+ MainApp.getDbHelper().deleteTempBasalById(_id);
+ MainApp.getDbHelper().deleteExtendedBolusById(_id);
+ MainApp.getDbHelper().deleteCareportalEventById(_id);
+ MainApp.getDbHelper().deleteProfileSwitchById(_id);
+ }
+
+ private void handleAddChangeDataFromNS(String trstring) throws JSONException {
JSONObject trJson = new JSONObject(trstring);
handleDanaRHistoryRecords(trJson); // update record _id in history
handleAddChangeTempTargetRecord(trJson);
- if (!trJson.has("insulin") && !trJson.has("carbs")) {
- if (Config.logIncommingData)
- log.debug("CHANGE: Uninterested treatment: " + trstring);
+ handleAddChangeTempBasalRecord(trJson);
+ handleAddChangeExtendedBolusRecord(trJson);
+ handleAddChangeCareportalEventRecord(trJson);
+ handleAddChangeTreatmentRecord(trJson);
+ handleAddChangeProfileSwitchRecord(trJson);
+ }
+
+ public void handleDanaRHistoryRecords(JSONObject trJson) {
+ if (trJson.has(DanaRNSHistorySync.DANARSIGNATURE)) {
+ MainApp.getDbHelper().updateDanaRHistoryRecordId(trJson);
+ }
+ }
+
+ public void handleAddChangeTreatmentRecord(JSONObject trJson) throws JSONException {
+ if (trJson.has("insulin") || trJson.has("carbs")) {
+ MainApp.getDbHelper().createTreatmentFromJsonIfNotExists(trJson);
return;
}
- String _id = trJson.getString("_id");
-
- Treatment stored;
-
- if (trJson.has("timeIndex")) {
- if (Config.logIncommingData)
- log.debug("ADD: timeIndex found: " + trstring);
- stored = MainApp.getDbHelper().findTreatmentByTimeIndex(trJson.getLong("timeIndex"));
- } else {
- stored = MainApp.getDbHelper().findTreatmentById(_id);
- }
-
- if (stored != null) {
- if (Config.logIncommingData)
- log.debug("CHANGE: Removing old: " + trstring);
- MainApp.getDbHelper().delete(_id);
- }
-
- if (Config.logIncommingData)
- log.debug("CHANGE: Adding new treatment: " + trstring);
- Treatment treatment = new Treatment();
- treatment._id = _id;
- treatment.carbs = trJson.has("carbs") ? trJson.getDouble("carbs") : 0;
- treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d;
- //treatment.created_at = DateUtil.fromISODateString(trJson.getString("created_at"));
- treatment.created_at = new Date(trJson.getLong("mills"));
- if (trJson.has("eventType")) {
- treatment.mealBolus = true;
- if (trJson.get("eventType").equals("Correction Bolus"))
- treatment.mealBolus = false;
- double carbs = treatment.carbs;
- if (trJson.has("boluscalc")) {
- JSONObject boluscalc = trJson.getJSONObject("boluscalc");
- if (boluscalc.has("carbs")) {
- carbs = Math.max(boluscalc.getDouble("carbs"), carbs);
- }
- }
- if (carbs <= 0)
- treatment.mealBolus = false;
- }
- treatment.setTimeIndex(treatment.getTimeIndex());
- Dao.CreateOrUpdateStatus status = MainApp.getDbHelper().createOrUpdate(treatment);
- if (Config.logIncommingData)
- log.debug("Records updated: " + status.getNumLinesChanged());
- if (Config.logIncommingData)
- log.debug("CHANGE: Stored treatment: " + treatment.log());
}
- public void handleDanaRHistoryRecords(JSONObject trJson) throws JSONException, SQLException {
- if (trJson.has(DanaRNSHistorySync.DANARSIGNATURE)) {
- Dao daoHistoryRecords = MainApp.getDbHelper().getDaoDanaRHistory();
- QueryBuilder queryBuilder = daoHistoryRecords.queryBuilder();
- Where where = queryBuilder.where();
- where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = daoHistoryRecords.query(preparedQuery);
- if (list.size() == 0) {
- // Record does not exists. Ignore
- } else if (list.size() == 1) {
- DanaRHistoryRecord record = list.get(0);
- if (record.get_id() == null || record.get_id() != trJson.getString("_id")) {
- if (Config.logIncommingData)
- log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
- record.set_id(trJson.getString("_id"));
- daoHistoryRecords.update(record);
- } else {
- // already set
- }
+ public void handleAddChangeTempTargetRecord(JSONObject trJson) throws JSONException {
+ if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.TEMPORARYTARGET)) {
+ MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(trJson);
+ }
+ }
+
+ public void handleAddChangeTempBasalRecord(JSONObject trJson) throws JSONException {
+ if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.TEMPBASAL)) {
+ MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(trJson);
+ }
+ }
+
+ public void handleAddChangeExtendedBolusRecord(JSONObject trJson) throws JSONException {
+ if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.COMBOBOLUS)) {
+ MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(trJson);
+ }
+ }
+
+ public void handleAddChangeCareportalEventRecord(JSONObject trJson) throws JSONException {
+ if (trJson.has("insulin") && trJson.getDouble("insulin") > 0)
+ return;
+ if (trJson.has("carbs") && trJson.getDouble("carbs") > 0)
+ return;
+ if (trJson.has("eventType") && (
+ trJson.getString("eventType").equals(CareportalEvent.SITECHANGE) ||
+ trJson.getString("eventType").equals(CareportalEvent.INSULINCHANGE) ||
+ trJson.getString("eventType").equals(CareportalEvent.SENSORCHANGE) ||
+ trJson.getString("eventType").equals(CareportalEvent.BGCHECK) ||
+ trJson.getString("eventType").equals(CareportalEvent.NOTE) ||
+ trJson.getString("eventType").equals(CareportalEvent.NONE) ||
+ trJson.getString("eventType").equals(CareportalEvent.ANNOUNCEMENT) ||
+ trJson.getString("eventType").equals(CareportalEvent.QUESTION) ||
+ trJson.getString("eventType").equals(CareportalEvent.EXERCISE) ||
+ trJson.getString("eventType").equals(CareportalEvent.OPENAPSOFFLINE) ||
+ trJson.getString("eventType").equals(CareportalEvent.PUMPBATTERYCHANGE)
+ )) {
+ MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(trJson);
+ }
+
+ if (trJson.getString("eventType").equals(CareportalEvent.ANNOUNCEMENT)) {
+ long date = trJson.getLong("mills");
+ long now = new Date().getTime();
+ if (date > now - 15 * 60 * 1000L && trJson.has("notes")) {
+ Notification announcement = new Notification(Notification.ANNOUNCEMENT, trJson.getString("notes"), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(announcement));
}
}
}
- /*
- {
- "_id": "58795998aa86647ba4d68ce7",
- "enteredBy": "",
- "eventType": "Temporary Target",
- "reason": "Eating Soon",
- "targetTop": 80,
- "targetBottom": 80,
- "duration": 120,
- "created_at": "2017-01-13T22:50:00.782Z",
- "carbs": null,
- "insulin": null
-}
- */
-
- public void handleAddChangeTempTargetRecord(JSONObject trJson) throws JSONException, SQLException {
- if (trJson.has("eventType") && trJson.getString("eventType").equals("Temporary Target")) {
- if (Config.logIncommingData)
- log.debug("Processing TempTarget record: " + trJson.toString());
- Dao daoTempTargets = MainApp.getDbHelper().getDaoTempTargets();
- QueryBuilder queryBuilder = daoTempTargets.queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", trJson.getString("_id")).or().eq("timeIndex", trJson.getLong("mills"));
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = daoTempTargets.query(preparedQuery);
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- if (profile == null) return; // no profile data, better ignore than do something wrong
- String units = profile.getUnits();
- if (list.size() == 0) {
- // Record does not exists. add
- TempTarget newRecord = new TempTarget();
- newRecord.timeStart = new Date(trJson.getLong("mills"));
- newRecord.duration = trJson.getInt("duration");
- newRecord.low = NSProfile.toMgdl(trJson.getDouble("targetBottom"), units);
- newRecord.high = NSProfile.toMgdl(trJson.getDouble("targetTop"), units);
- newRecord.reason = trJson.getString("reason");
- newRecord._id = trJson.getString("_id");
- newRecord.setTimeIndex(newRecord.getTimeIndex());
- daoTempTargets.createIfNotExists(newRecord);
- if (Config.logIncommingData)
- log.debug("Adding TempTarget record to database: " + newRecord.log());
- MainApp.bus().post(new EventTempTargetRangeChange());
- } else if (list.size() == 1) {
- if (Config.logIncommingData)
- log.debug("Updating TempTarget record in database: " + trJson.getString("_id"));
- TempTarget record = list.get(0);
- record.timeStart = new Date(trJson.getLong("mills"));
- record.duration = trJson.getInt("duration");
- record.low = NSProfile.toMgdl(trJson.getDouble("targetBottom"), units);
- record.high = NSProfile.toMgdl(trJson.getDouble("targetTop"), units);
- record.reason = trJson.getString("reason");
- record._id = trJson.getString("_id");
- daoTempTargets.update(record);
- MainApp.bus().post(new EventTempTargetRangeChange());
- }
- }
- }
-
- public void handleRemoveTempTargetRecord(JSONObject trJson) throws JSONException, SQLException {
- if (trJson.has("_id")) {
- Dao daoTempTargets = MainApp.getDbHelper().getDaoTempTargets();
- QueryBuilder queryBuilder = daoTempTargets.queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", trJson.getString("_id"));
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = daoTempTargets.query(preparedQuery);
-
- if (list.size() == 1) {
- TempTarget record = list.get(0);
- if (Config.logIncommingData)
- log.debug("Removing TempTarget record from database: " + record.log());
- daoTempTargets.delete(record);
- MainApp.bus().post(new EventTempTargetRangeChange());
- } else {
- if (Config.logIncommingData)
- log.debug("TempTarget not found database: " + trJson.toString());
- }
+ public void handleAddChangeProfileSwitchRecord(JSONObject trJson) throws JSONException {
+ if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.PROFILESWITCH)) {
+ MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java b/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java
new file mode 100644
index 0000000000..f560ad0282
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java
@@ -0,0 +1,32 @@
+package info.nightscout.androidaps.data;
+
+import android.content.Context;
+
+import org.json.JSONObject;
+
+import java.util.Date;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.db.CareportalEvent;
+import info.nightscout.androidaps.db.Source;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
+
+/**
+ * Created by mike on 29.05.2017.
+ */
+
+public class DetailedBolusInfo {
+ public long date = new Date().getTime();
+ public InsulinInterface insulinInterface = MainApp.getConfigBuilder().getActiveInsulin();
+ public String eventType = CareportalEvent.MEALBOLUS;
+ public double insulin = 0;
+ public double carbs = 0;
+ public int source = Source.NONE;
+ public double glucose = 0; // Bg value in current units
+ public String glucoseType = ""; // NS values: Manual, Finger, Sensor
+ public int carbTime = 0; // time shift of carbs in minutes
+ public JSONObject boluscalc = null; // additional bolus wizard info
+ public Context context = null; // context for progress dialog
+ public boolean addToTreatments = true;
+ public long pumpId = 0; // id of record if comming from pump history (not a newly created treatment)
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java b/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java
index ad9b0acecf..68d4936460 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java
@@ -66,19 +66,17 @@ public class GlucoseStatus {
@Nullable
public static GlucoseStatus getGlucoseStatusData() {
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainApp.instance());
-
// load 45min
long fromtime = (long) (new Date().getTime() - 60 * 1000L * 45);
List data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false);
int sizeRecords = data.size();
- if (sizeRecords < 1 || data.get(0).timeIndex < new Date().getTime() - 7 * 60 * 1000L) {
+ if (sizeRecords < 1 || data.get(0).date < new Date().getTime() - 7 * 60 * 1000L) {
return null;
}
BgReading now = data.get(0);
- long now_date = now.timeIndex;
+ long now_date = now.date;
double change;
if (sizeRecords < 2) {
@@ -98,7 +96,7 @@ public class GlucoseStatus {
for (int i = 1; i < data.size(); i++) {
if (data.get(i).value > 38) {
BgReading then = data.get(i);
- long then_date = then.timeIndex;
+ long then_date = then.date;
double avgdelta = 0;
long minutesago;
@@ -131,7 +129,7 @@ public class GlucoseStatus {
status.short_avgdelta = average(short_deltas);
- if (prefs.getBoolean("always_use_shortavg", false) || last_deltas.isEmpty()) {
+ if (last_deltas.isEmpty()) {
status.delta = status.short_avgdelta;
} else {
status.delta = average(last_deltas);
@@ -143,48 +141,6 @@ public class GlucoseStatus {
return status.round();
}
- /*
- * Return last BgReading from database or null if db is empty
- */
- @Nullable
- public static BgReading lastBg() {
- List bgList = null;
-
- try {
- Dao daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
- QueryBuilder queryBuilder = daoBgReadings.queryBuilder();
- queryBuilder.orderBy("timeIndex", false);
- queryBuilder.limit(1L);
- queryBuilder.where().gt("value", 38);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- bgList = daoBgReadings.query(preparedQuery);
-
- } catch (SQLException e) {
- log.debug(e.getMessage(), e);
- }
- if (bgList != null && bgList.size() > 0)
- return bgList.get(0);
- else
- return null;
- }
-
- /*
- * Return bg reading if not old ( <9 min )
- * or null if older
- */
- @Nullable
- public static BgReading actualBg() {
- BgReading lastBg = lastBg();
-
- if (lastBg == null)
- return null;
-
- if (lastBg.timeIndex > new Date().getTime() - 9 * 60 * 1000)
- return lastBg;
-
- return null;
- }
-
public static double average(ArrayList array) {
double sum = 0d;
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 ce0a94ef5a..5c89a7bec7 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java
@@ -1,13 +1,10 @@
package info.nightscout.androidaps.data;
-import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round;
@@ -20,7 +17,9 @@ public class IobTotal {
public Double hightempinsulin;
public Double netInsulin = 0d; // for calculations from temp basals only
- public Double netRatio = 0d; // for calculations from temp basals only
+ public Double netRatio = 0d; // net ratio at start of temp basal
+
+ public Double extendedBolusInsulin = 0d; // total insulin for extended bolus
long time;
@@ -42,7 +41,7 @@ public class IobTotal {
netbasalinsulin += other.netbasalinsulin;
hightempinsulin += other.hightempinsulin;
netInsulin += other.netInsulin;
- netRatio += other.netRatio;
+ extendedBolusInsulin += other.extendedBolusInsulin;
return this;
}
@@ -94,43 +93,4 @@ public class IobTotal {
return json;
}
- public static IobTotal calulateFromTreatmentsAndTemps() {
- ConfigBuilderPlugin.getActiveTreatments().updateTotalIOB();
- IobTotal bolusIob = ConfigBuilderPlugin.getActiveTreatments().getLastCalculation().round();
- ConfigBuilderPlugin.getActiveTempBasals().updateTotalIOB();
- IobTotal basalIob = ConfigBuilderPlugin.getActiveTempBasals().getLastCalculation().round();
- IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
- return iobTotal;
- }
-
- public static IobTotal calulateFromTreatmentsAndTemps(long time) {
- IobTotal bolusIob = ConfigBuilderPlugin.getActiveTreatments().getCalculationToTime(time).round();
- IobTotal basalIob = ConfigBuilderPlugin.getActiveTempBasals().getCalculationToTime(time).round();
- IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
- return iobTotal;
- }
-
- public static IobTotal[] calculateIobArrayInDia() {
- NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
- // predict IOB out to DIA plus 30m
- long time = new Date().getTime();
- int len = (int) ((profile.getDia() *60 + 30) / 5);
- IobTotal[] array = new IobTotal[len];
- int pos = 0;
- for (int i = 0; i < len; i++){
- long t = time + i * 5 * 60000;
- IobTotal iob = calulateFromTreatmentsAndTemps(t);
- array[pos] = iob;
- pos++;
- }
- return array;
- }
-
- public static JSONArray convertToJSONArray(IobTotal[] iobArray) {
- JSONArray array = new JSONArray();
- for (int i = 0; i < iobArray.length; i ++) {
- array.put(iobArray[i].determineBasalJson());
- }
- return array;
- }
}
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 18919c3c8a..292d2272d5 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/MealData.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/MealData.java
@@ -1,17 +1,5 @@
package info.nightscout.androidaps.data;
-import java.util.Date;
-import java.util.List;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.Treatment;
-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.androidaps.plugins.NSClientInternal.data.NSProfile;
-
/**
* Created by mike on 04.01.2017.
*/
@@ -19,30 +7,4 @@ public class MealData {
public double boluses = 0d;
public double carbs = 0d;
public double mealCOB = 0.0d;
-
-
- public void addTreatment(Treatment treatment) {
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- if (profile == null) return;
-
- List bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (new Date().getTime() - 60 * 60 * 1000L * profile.getDia() * 2), false);
-
- long now = new Date().getTime();
- long dia_ago = now - (new Double(1.5d * profile.getDia() * 60 * 60 * 1000l)).longValue();
- long t = treatment.created_at.getTime();
- if (t > dia_ago && t <= now) {
- if (treatment.carbs >= 1) {
- carbs += treatment.carbs;
- if (MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class).isEnabled(PluginBase.APS)) {
- AutosensResult result = Autosens.detectSensitivityandCarbAbsorption(bgReadings, t);
- double myCarbsAbsorbed = result.carbsAbsorbed;
- double myMealCOB = Math.max(0, carbs - myCarbsAbsorbed);
- mealCOB = Math.max(mealCOB, myMealCOB);
- }
- }
- if (treatment.insulin > 0 && treatment.mealBolus) {
- boluses += treatment.insulin;
- }
- }
- }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java
new file mode 100644
index 0000000000..cc03936766
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java
@@ -0,0 +1,99 @@
+package info.nightscout.androidaps.data;
+
+import android.support.annotation.Nullable;
+import android.support.v4.util.LongSparseArray;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import info.nightscout.androidaps.interfaces.Interval;
+
+/**
+ * Created by mike on 09.05.2017.
+ */
+
+// Zero duration means end of interval
+
+public class OverlappingIntervals {
+
+ private LongSparseArray rawData = new LongSparseArray<>(); // oldest at index 0
+
+ public OverlappingIntervals reset() {
+ rawData = new LongSparseArray<>();
+ return this;
+ }
+
+ public void add(T newInterval) {
+ rawData.put(newInterval.start(), newInterval);
+ merge();
+ }
+
+ public void add(List list) {
+ for (T interval : list) {
+ rawData.put(interval.start(), interval);
+ }
+ merge();
+ }
+
+ private void merge() {
+ for (int index = 0; index < rawData.size() - 1; index++) {
+ Interval i = rawData.valueAt(index);
+ long startOfNewer = rawData.valueAt(index + 1).start();
+ if (i.originalEnd() > startOfNewer) {
+ i.cutEndTo(startOfNewer);
+ }
+ }
+ }
+
+ @Nullable
+ public Interval getValueByInterval(long time) {
+ int index = binarySearch(time);
+ if (index >= 0) return rawData.valueAt(index);
+ return null;
+ }
+
+ public List getList() {
+ List list = new ArrayList<>();
+ for (int i = 0; i < rawData.size(); i++)
+ list.add(rawData.valueAt(i));
+ return list;
+ }
+
+ public List getReversedList() {
+ List list = new ArrayList<>();
+ for (int i = rawData.size() -1; i>=0; i--)
+ list.add(rawData.valueAt(i));
+ return list;
+ }
+
+ private int binarySearch(long value) {
+ int lo = 0;
+ int hi = rawData.size() - 1;
+
+ while (lo <= hi) {
+ final int mid = (lo + hi) >>> 1;
+ final Interval midVal = rawData.valueAt(mid);
+
+ if (midVal.before(value)) {
+ lo = mid + 1;
+ } else if (midVal.after(value)) {
+ hi = mid - 1;
+ } else if (midVal.match(value)) {
+ return mid; // value found
+ }
+ }
+ return ~lo; // value not present
+ }
+
+ public int size() {
+ return rawData.size();
+ }
+
+ public T get(int index) {
+ return rawData.valueAt(index);
+ }
+
+ public T getReversed(int index) {
+ return rawData.valueAt(size() - 1 - index);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java
new file mode 100644
index 0000000000..dd68eff35f
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java
@@ -0,0 +1,347 @@
+package info.nightscout.androidaps.data;
+
+import com.crashlytics.android.Crashlytics;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.text.DecimalFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+
+import info.nightscout.androidaps.Constants;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.plugins.Overview.Notification;
+import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
+import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
+import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.utils.ToastUtils;
+
+public class Profile {
+ private static Logger log = LoggerFactory.getLogger(Profile.class);
+
+ private JSONObject json;
+ private String units = null;
+ double dia = Constants.defaultDIA;
+ TimeZone timeZone = TimeZone.getDefault();
+ JSONArray isf;
+ JSONArray ic;
+ JSONArray basal;
+ JSONArray targetLow;
+ JSONArray targetHigh;
+
+ public Profile(JSONObject json, String units) {
+ this(json);
+ if (this.units == null) {
+ if (units != null)
+ this.units = units;
+ else {
+ Crashlytics.log("Profile failover failed too");
+ this.units = Constants.MGDL;
+ }
+ }
+ }
+
+ public Profile(JSONObject json) {
+ this.json = json;
+ try {
+ if (json.has("units"))
+ units = json.getString("units").toLowerCase();
+ if (json.has("dia"))
+ dia = json.getDouble("dia");
+ if (json.has("dia"))
+ dia = json.getDouble("dia");
+ if (json.has("timezone"))
+ timeZone = TimeZone.getTimeZone(json.getString("timezone"));
+ isf = json.getJSONArray("sens");
+ if (getIsf(0) == null) {
+ int defaultISF = units.equals(Constants.MGDL) ? 400 : 20;
+ isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultISF + "\",\"timeAsSeconds\":\"0\"}]");
+ Notification noisf = new Notification(Notification.ISF_MISSING, MainApp.sResources.getString(R.string.isfmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(noisf));
+ } else {
+ MainApp.bus().post(new EventDismissNotification(Notification.ISF_MISSING));
+ }
+ ic = json.getJSONArray("carbratio");
+ if (getIc(0) == null) {
+ int defaultIC = 25;
+ isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultIC + "\",\"timeAsSeconds\":\"0\"}]");
+ Notification noic = new Notification(Notification.IC_MISSING, MainApp.sResources.getString(R.string.icmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(noic));
+ } else {
+ MainApp.bus().post(new EventDismissNotification(Notification.IC_MISSING));
+ }
+ basal = json.getJSONArray("basal");
+ if (getBasal(0) == null) {
+ double defaultBasal = 0.1d;
+ isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultBasal + "\",\"timeAsSeconds\":\"0\"}]");
+ Notification nobasal = new Notification(Notification.BASAL_MISSING, MainApp.sResources.getString(R.string.basalmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(nobasal));
+ } else {
+ MainApp.bus().post(new EventDismissNotification(Notification.BASAL_MISSING));
+ }
+ targetLow = json.getJSONArray("target_low");
+ if (getTargetLow(0) == null) {
+ double defaultLow = units.equals(Constants.MGDL) ? 120 : 6;
+ isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultLow + "\",\"timeAsSeconds\":\"0\"}]");
+ Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(notarget));
+ } else {
+ MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING));
+ }
+ targetHigh = json.getJSONArray("target_high");
+ if (getTargetHigh(0) == null) {
+ double defaultHigh = units.equals(Constants.MGDL) ? 160 : 8;
+ isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultHigh + "\",\"timeAsSeconds\":\"0\"}]");
+ Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(notarget));
+ } else {
+ MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING));
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.invalidprofile));
+ }
+ }
+
+ public String log() {
+ String ret = "\n";
+ for (Integer hour = 0; hour < 24; hour++) {
+ double value = getBasal(hour * 60 * 60);
+ ret += "NS basal value for " + hour + ":00 is " + value + "\n";
+ }
+ ret += "NS units: " + getUnits();
+ return ret;
+ }
+
+ public JSONObject getData() {
+ return json;
+ }
+
+ public Double getDia() {
+ return dia;
+ }
+
+ // mmol or mg/dl
+ public String getUnits() {
+ return units;
+ }
+
+ public TimeZone getTimeZone() {
+ return timeZone;
+ }
+
+ private Double getValueToTime(JSONArray array, Integer timeAsSeconds) {
+ Double lastValue = null;
+
+ for (Integer index = 0; index < array.length(); index++) {
+ try {
+ JSONObject o = array.getJSONObject(index);
+ Integer tas = o.getInt("timeAsSeconds");
+ Double value = o.getDouble("value");
+ if (lastValue == null) lastValue = value;
+ if (timeAsSeconds < tas) {
+ break;
+ }
+ lastValue = value;
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+ return lastValue;
+ }
+
+ private String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) {
+ String retValue = "";
+
+ for (Integer index = 0; index < array.length(); index++) {
+ try {
+ JSONObject o = array.getJSONObject(index);
+ retValue += o.getString("time");
+ retValue += " ";
+ retValue += format.format(o.getDouble("value"));
+ if (array2 != null) {
+ JSONObject o2 = array2.getJSONObject(index);
+ retValue += " - ";
+ retValue += format.format(o2.getDouble("value"));
+ }
+ retValue += " " + units;
+ retValue += "\n";
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+ return retValue;
+ }
+
+ public Double getIsf() {
+ return getIsf(secondsFromMidnight(new Date().getTime()));
+ }
+
+ public Double getIsf(long time) {
+ return getIsf(secondsFromMidnight(time));
+ }
+
+ public Double getIsf(Integer timeAsSeconds) {
+ return getValueToTime(isf, timeAsSeconds);
+ }
+
+ public String getIsfList() {
+ return getValuesList(isf, null, new DecimalFormat("0.0"), getUnits() + "/U");
+ }
+
+ public Double getIc() {
+ return getIc(secondsFromMidnight(new Date().getTime()));
+ }
+
+ public Double getIc(long time) {
+ return getIc(secondsFromMidnight(time));
+ }
+
+ public Double getIc(Integer timeAsSeconds) {
+ return getValueToTime(ic, timeAsSeconds);
+ }
+
+ public String getIcList() {
+ return getValuesList(ic, null, new DecimalFormat("0.0"), getUnits() + "/U");
+ }
+
+ public Double getBasal() {
+ return getBasal(secondsFromMidnight(new Date().getTime()));
+ }
+
+ public Double getBasal(long time) {
+ return getBasal(secondsFromMidnight(time));
+ }
+
+ public Double getBasal(Integer timeAsSeconds) {
+ return getValueToTime(basal, timeAsSeconds);
+ }
+
+ public String getBasalList() {
+ return getValuesList(basal, null, new DecimalFormat("0.00"), "U");
+ }
+
+ public class BasalValue {
+ public BasalValue(Integer timeAsSeconds, Double value) {
+ this.timeAsSeconds = timeAsSeconds;
+ this.value = value;
+ }
+
+ public Integer timeAsSeconds;
+ public Double value;
+ }
+
+ public BasalValue[] getBasalValues() {
+ try {
+ BasalValue[] ret = new BasalValue[basal.length()];
+
+ for (Integer index = 0; index < basal.length(); index++) {
+ JSONObject o = basal.getJSONObject(index);
+ Integer tas = o.getInt("timeAsSeconds");
+ Double value = o.getDouble("value");
+ ret[index] = new BasalValue(tas, value);
+ }
+ return ret;
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ return new BasalValue[0];
+ }
+
+ public Double getTargetLow() {
+ return getTargetLow(secondsFromMidnight(new Date().getTime()));
+ }
+
+ public Double getTargetLow(long time) {
+ return getTargetLow(secondsFromMidnight(time));
+ }
+
+ public Double getTargetLow(Integer timeAsSeconds) {
+ return getValueToTime(targetLow, timeAsSeconds);
+ }
+
+ public Double getTargetHigh() {
+ return getTargetHigh(secondsFromMidnight(new Date().getTime()));
+ }
+
+ public Double getTargetHigh(long time) {
+ return getTargetHigh(secondsFromMidnight(time));
+ }
+
+ public Double getTargetHigh(Integer timeAsSeconds) {
+ return getValueToTime(targetHigh, timeAsSeconds);
+ }
+
+ public String getTargetList() {
+ return getValuesList(targetLow, targetHigh, new DecimalFormat("0.0"), getUnits());
+ }
+
+ public double getMaxDailyBasal() {
+ Double max = 0d;
+ for (Integer hour = 0; hour < 24; hour++) {
+ double value = getBasal(hour * 60 * 60);
+ if (value > max) max = value;
+ }
+ return max;
+ }
+
+ public static Integer secondsFromMidnight() {
+ Calendar c = Calendar.getInstance();
+ long now = c.getTimeInMillis();
+ c.set(Calendar.HOUR_OF_DAY, 0);
+ c.set(Calendar.MINUTE, 0);
+ c.set(Calendar.SECOND, 0);
+ c.set(Calendar.MILLISECOND, 0);
+ long passed = now - c.getTimeInMillis();
+ return (int) (passed / 1000);
+ }
+
+ public static Integer secondsFromMidnight(Date date) {
+ Calendar c = Calendar.getInstance();
+ long now = date.getTime();
+ c.setTime(date);
+ c.set(Calendar.HOUR_OF_DAY, 0);
+ c.set(Calendar.MINUTE, 0);
+ c.set(Calendar.SECOND, 0);
+ c.set(Calendar.MILLISECOND, 0);
+ long passed = now - c.getTimeInMillis();
+ return (int) (passed / 1000);
+ }
+
+ public static Integer secondsFromMidnight(long date) {
+ Calendar c = Calendar.getInstance();
+ c.setTimeInMillis(date);
+ c.set(Calendar.HOUR_OF_DAY, 0);
+ c.set(Calendar.MINUTE, 0);
+ c.set(Calendar.SECOND, 0);
+ c.set(Calendar.MILLISECOND, 0);
+ long passed = date - c.getTimeInMillis();
+ return (int) (passed / 1000);
+ }
+
+ public static Double toMgdl(Double value, String units) {
+ if (units.equals(Constants.MGDL)) return value;
+ else return value * Constants.MMOLL_TO_MGDL;
+ }
+
+ public static Double fromMgdlToUnits(Double value, String units) {
+ if (units.equals(Constants.MGDL)) return value;
+ else return value * Constants.MGDL_TO_MMOLL;
+ }
+
+ public static Double toUnits(Double valueInMgdl, Double valueInMmol, String units) {
+ if (units.equals(Constants.MGDL)) return valueInMgdl;
+ else return valueInMmol;
+ }
+
+ public static String toUnitsString(Double valueInMgdl, Double valueInMmol, String units) {
+ if (units.equals(Constants.MGDL)) return DecimalFormatter.to0Decimal(valueInMgdl);
+ else return DecimalFormatter.to1Decimal(valueInMmol);
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java
new file mode 100644
index 0000000000..ef255ed901
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java
@@ -0,0 +1,109 @@
+package info.nightscout.androidaps.data;
+
+import android.support.annotation.Nullable;
+import android.support.v4.util.LongSparseArray;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import info.nightscout.androidaps.interfaces.Interval;
+
+/**
+ * Created by mike on 09.05.2017.
+ */
+
+// Zero duration means profile is valid until is chaged
+// When no interval match the lastest record without duration is used
+
+public class ProfileIntervals {
+
+ private LongSparseArray rawData = new LongSparseArray<>(); // oldest at index 0
+
+ public ProfileIntervals reset() {
+ rawData = new LongSparseArray<>();
+ return this;
+ }
+
+ public void add(T newInterval) {
+ rawData.put(newInterval.start(), newInterval);
+ merge();
+ }
+
+ public void add(List list) {
+ for (T interval : list) {
+ rawData.put(interval.start(), interval);
+ }
+ merge();
+ }
+
+ private void merge() {
+ for (int index = 0; index < rawData.size() - 1; index++) {
+ Interval i = rawData.valueAt(index);
+ long startOfNewer = rawData.valueAt(index + 1).start();
+ if (i.originalEnd() > startOfNewer) {
+ i.cutEndTo(startOfNewer);
+ }
+ }
+ }
+
+ @Nullable
+ public Interval getValueToTime(long time) {
+ int index = binarySearch(time);
+ if (index >= 0) return rawData.valueAt(index);
+ return null;
+ }
+
+ public List getList() {
+ List list = new ArrayList<>();
+ for (int i = 0; i < rawData.size(); i++)
+ list.add(rawData.valueAt(i));
+ return list;
+ }
+
+ public List getReversedList() {
+ List list = new ArrayList<>();
+ for (int i = rawData.size() -1; i>=0; i--)
+ list.add(rawData.valueAt(i));
+ return list;
+ }
+
+ private int binarySearch(long value) {
+ if (rawData.size() == 0)
+ return -1;
+ int lo = 0;
+ int hi = rawData.size() - 1;
+
+ while (lo <= hi) {
+ final int mid = (lo + hi) >>> 1;
+ final Interval midVal = rawData.valueAt(mid);
+
+ if (midVal.match(value)) {
+ return mid; // value found
+ } else if (midVal.before(value)) {
+ lo = mid + 1;
+ } else if (midVal.after(value)) {
+ hi = mid - 1;
+ }
+ }
+ // not found, try nearest older with duration 0
+ lo = lo - 1;
+ while (lo >= 0 && lo < rawData.size()) {
+ if (rawData.valueAt(lo).isEndingEvent())
+ return lo;
+ lo--;
+ }
+ return -1; // value not present
+ }
+
+ public int size() {
+ return rawData.size();
+ }
+
+ public T get(int index) {
+ return rawData.valueAt(index);
+ }
+
+ public T getReversed(int index) {
+ return rawData.valueAt(size() - 1 - index);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java
new file mode 100644
index 0000000000..466351076b
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java
@@ -0,0 +1,99 @@
+package info.nightscout.androidaps.data;
+
+import android.support.annotation.Nullable;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+/**
+ * Created by mike on 01.06.2017.
+ */
+
+public class ProfileStore {
+ private static Logger log = LoggerFactory.getLogger(ProfileStore.class);
+ private JSONObject json = null;
+
+ public ProfileStore(JSONObject json) {
+ this.json = json;
+ }
+
+ public JSONObject getData() {
+ return json;
+ }
+
+ @Nullable
+ public Profile getDefaultProfile() {
+ Profile profile = null;
+ try {
+ String defaultProfileName = json.getString("defaultProfile");
+ JSONObject store = json.getJSONObject("store");
+ if (store.has(defaultProfileName)) {
+ String units = null;
+ if (store.has("units"))
+ units = store.getString("units");
+ profile = new Profile(store.getJSONObject(defaultProfileName), units);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ return profile;
+ }
+
+ @Nullable
+ public String getDefaultProfileName() {
+ String defaultProfileName = null;
+ try {
+ defaultProfileName = json.getString("defaultProfile");
+ JSONObject store = json.getJSONObject("store");
+ if (store.has(defaultProfileName)) {
+ return defaultProfileName;
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ return defaultProfileName;
+ }
+
+ @Nullable
+ public Profile getSpecificProfile(String profileName) {
+ Profile profile = null;
+ try {
+ JSONObject store = json.getJSONObject("store");
+ if (store.has(profileName)) {
+ String units = null;
+ if (json.has("units"))
+ units = json.getString("units");
+ profile = new Profile(store.getJSONObject(profileName), units);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ return profile;
+ }
+
+ public ArrayList getProfileList() {
+ ArrayList ret = new ArrayList();
+
+ JSONObject store;
+ try {
+ store = json.getJSONObject("store");
+ Iterator> keys = store.keys();
+
+ while (keys.hasNext()) {
+ String profileName = (String) keys.next();
+ ret.add(profileName);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+
+ return ret;
+ }
+
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java
index a2a5b91870..bfddeff320 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java
@@ -8,7 +8,6 @@ import org.json.JSONObject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round;
@@ -25,7 +24,7 @@ public class PumpEnactResult extends Object {
public boolean isTempCancel = false; // if true we are caceling temp basal
// Result of treatment delivery
public Double bolusDelivered = 0d; // real value of delivered insulin
- public Integer carbsDelivered = 0; // real value of delivered carbs
+ public Double carbsDelivered = 0d; // real value of delivered carbs
public boolean queued = false;
@@ -94,7 +93,7 @@ public class PumpEnactResult extends Object {
result.put("duration", 0);
} else if (isPercent) {
// Nightscout is expecting absolute value
- Double abs = Round.roundTo(MainApp.getConfigBuilder().getActiveProfile().getProfile().getBasal(NSProfile.secondsFromMidnight()) * percent / 100, 0.01);
+ Double abs = Round.roundTo(MainApp.getConfigBuilder().getProfile().getBasal() * percent / 100, 0.01);
result.put("rate", abs);
result.put("duration", duration);
} else {
diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java
index 8a0aaf96e1..fa5cd00c54 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java
@@ -2,50 +2,54 @@ package info.nightscout.androidaps.db;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
-import com.jjoe64.graphview.series.DataPointInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
+import java.util.Objects;
import info.nightscout.androidaps.Constants;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
+import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.utils.SP;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)
-public class BgReading implements DataPointInterface {
+public class BgReading implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(BgReading.class);
- public long getTimeIndex() {
- return timeIndex;
- }
+ @DatabaseField(id = true)
+ public long date;
- public void setTimeIndex(long timeIndex) {
- this.timeIndex = timeIndex;
- }
-
- @DatabaseField(id = true, useGetSet = true)
- public long timeIndex;
+ @DatabaseField
+ public boolean isValid = true;
@DatabaseField
public double value;
-
@DatabaseField
public String direction;
-
@DatabaseField
public double raw;
@DatabaseField
- public int battery_level;
+ public int source = Source.NONE;
+ @DatabaseField
+ public String _id = null; // NS _id
- public static String units = Constants.MGDL;
+ public boolean isPrediction = false; // true when drawing predictions as bg points
- public BgReading() {}
+ public BgReading() {
+ }
public BgReading(NSSgv sgv) {
- timeIndex = sgv.getMills();
+ date = sgv.getMills();
value = sgv.getMgdl();
raw = sgv.getFiltered() != null ? sgv.getFiltered() : value;
direction = sgv.getDirection();
@@ -63,7 +67,7 @@ public class BgReading implements DataPointInterface {
else return DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL);
}
- public String directionToSymbol() {
+ public String directionToSymbol() {
String symbol = "";
if (direction.compareTo("DoubleDown") == 0) {
symbol = "\u21ca";
@@ -101,23 +105,108 @@ public class BgReading implements DataPointInterface {
@Override
public String toString() {
return "BgReading{" +
- "timeIndex=" + timeIndex +
- ", date=" + new Date(timeIndex) +
+ "date=" + date +
+ ", date=" + new Date(date).toLocaleString() +
", value=" + value +
", direction=" + direction +
", raw=" + raw +
- ", battery_level=" + battery_level +
'}';
}
+ public boolean isDataChanging(BgReading other) {
+ if (date != other.date) {
+ log.error("Comparing different");
+ return false;
+ }
+ if (value != other.value)
+ return true;
+ return false;
+ }
+
+ public boolean isEqual(BgReading other) {
+ if (date != other.date) {
+ log.error("Comparing different");
+ return false;
+ }
+ if (value != other.value)
+ return false;
+ if (raw != other.raw)
+ return false;
+ if (!direction.equals(other.direction))
+ return false;
+ if (!Objects.equals(_id, other._id))
+ return false;
+ return true;
+ }
+
+ public void copyFrom(BgReading other) {
+ if (date != other.date) {
+ log.error("Copying different");
+ return;
+ }
+ value = other.value;
+ raw = other.raw;
+ direction = other.direction;
+ _id = other._id;
+ }
+
+ // ------------------ DataPointWithLabelInterface ------------------
@Override
public double getX() {
- return timeIndex;
+ return date;
}
@Override
public double getY() {
+ String units = MainApp.getConfigBuilder().getProfile().getUnits();
return valueToUnits(units);
}
+ @Override
+ public void setY(double y) {
+
+ }
+
+ @Override
+ public String getLabel() {
+ return null;
+ }
+
+ @Override
+ public long getDuration() {
+ return 0;
+ }
+
+ @Override
+ public PointsWithLabelGraphSeries.Shape getShape() {
+ return PointsWithLabelGraphSeries.Shape.POINT;
+ }
+
+ @Override
+ public float getSize() {
+ boolean isTablet = MainApp.sResources.getBoolean(R.bool.isTablet);
+ return isTablet ? 8 : 5;
+ }
+
+ @Override
+ public int getColor() {
+ String units = MainApp.getConfigBuilder().getProfile().getUnits();
+ Double lowLine = SP.getDouble("low_mark", 0d);
+ Double highLine = SP.getDouble("high_mark", 0d);
+ if (lowLine < 1) {
+ lowLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
+ }
+ if (highLine < 1) {
+ highLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
+ }
+ int color = MainApp.sResources.getColor(R.color.inrange);
+ if (isPrediction)
+ color = MainApp.sResources.getColor(R.color.prediction);
+ else if (valueToUnits(units) < lowLine)
+ color = MainApp.sResources.getColor(R.color.low);
+ else if (valueToUnits(units) > highLine)
+ color = MainApp.sResources.getColor(R.color.high);
+ return color;
+ }
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
new file mode 100644
index 0000000000..3d67abc597
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
@@ -0,0 +1,244 @@
+package info.nightscout.androidaps.db;
+
+import android.graphics.Color;
+
+import com.j256.ormlite.field.DatabaseField;
+import com.j256.ormlite.table.DatabaseTable;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import info.nightscout.androidaps.Constants;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.Translator;
+
+@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
+public class CareportalEvent implements DataPointWithLabelInterface {
+ private static Logger log = LoggerFactory.getLogger(CareportalEvent.class);
+
+ @DatabaseField(id = true)
+ public long date;
+
+ @DatabaseField
+ public boolean isValid = true;
+
+ @DatabaseField
+ public int source = Source.NONE;
+ @DatabaseField
+ public String _id;
+
+ @DatabaseField
+ public String eventType;
+ @DatabaseField
+ public String json;
+
+ public static final String CARBCORRECTION = "Carb Correction";
+ public static final String BOLUSWIZARD = "Bolus Wizard";
+ public static final String CORRECTIONBOLUS = "Correction Bolus";
+ public static final String MEALBOLUS = "Meal Bolus";
+ public static final String COMBOBOLUS = "Combo Bolus";
+ public static final String TEMPBASAL = "Temp Basal";
+ public static final String TEMPORARYTARGET = "Temporary Target";
+ public static final String PROFILESWITCH = "Profile Switch";
+ public static final String SITECHANGE = "Site Change";
+ public static final String INSULINCHANGE = "Insulin Change";
+ public static final String SENSORCHANGE = "Sensor Change";
+ public static final String PUMPBATTERYCHANGE = "Pump Battery Change";
+ public static final String BGCHECK = "BG Check";
+ public static final String ANNOUNCEMENT = "Announcement";
+ public static final String NOTE = "Note";
+ public static final String QUESTION = "Question";
+ public static final String EXERCISE = "Exercise";
+ public static final String OPENAPSOFFLINE = "OpenAPS Offline";
+ public static final String NONE = "";
+
+ public static final String MBG = "Mbg"; // comming from entries
+
+ public CareportalEvent() {
+ }
+
+ public CareportalEvent(NSMbg mbg) {
+ date = mbg.date;
+ eventType = MBG;
+ json = mbg.json;
+ }
+
+ public long getMillisecondsFromStart() {
+ return new Date().getTime() - date;
+ }
+
+ public long getHoursFromStart() {
+ return (new Date().getTime() - date) / (60 * 1000);
+ }
+
+ public String age() {
+ Map diff = computeDiff(date, new Date().getTime());
+ return diff.get(TimeUnit.DAYS) + " " + MainApp.sResources.getString(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.sResources.getString(R.string.hours);
+ }
+
+ public String log() {
+ return "CareportalEvent{" +
+ "date= " + date +
+ ", date= " + DateUtil.dateAndTimeString(date) +
+ ", isValid= " + isValid +
+ ", _id= " + _id +
+ ", eventType= " + eventType +
+ ", json= " + json +
+ "}";
+ }
+
+ //Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
+ public static Map computeDiff(long date1, long date2) {
+ long diffInMillies = date2 - date1;
+ List units = new ArrayList(EnumSet.allOf(TimeUnit.class));
+ Collections.reverse(units);
+ Map result = new LinkedHashMap();
+ long milliesRest = diffInMillies;
+ for ( TimeUnit unit : units ) {
+ long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
+ long diffInMilliesForUnit = unit.toMillis(diff);
+ milliesRest = milliesRest - diffInMilliesForUnit;
+ result.put(unit,diff);
+ }
+ return result;
+ }
+
+ // -------- DataPointWithLabelInterface -------
+
+ @Override
+ public double getX() {
+ return date;
+ }
+
+ double yValue = 0;
+
+ @Override
+ public double getY() {
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ if (eventType.equals(MBG)) {
+ double mbg = 0d;
+ try {
+ JSONObject object = new JSONObject(json);
+ mbg = object.getDouble("mgdl");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ if (profile != null)
+ return profile.fromMgdlToUnits(mbg, profile.getUnits());
+ return 0d;
+ }
+
+ double glucose = 0d;
+ String units = Constants.MGDL;
+ try {
+ JSONObject object = new JSONObject(json);
+ if (object.has("glucose")) {
+ glucose = object.getDouble("glucose");
+ units = object.getString("units");
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ if (profile != null && glucose != 0d) {
+ double mmol = 0d;
+ double mgdl = 0;
+ if (units.equals(Constants.MGDL)) {
+ mgdl = glucose;
+ mmol = glucose * Constants.MGDL_TO_MMOLL;
+ }
+ if (units.equals(Constants.MMOL)) {
+ mmol = glucose;
+ mgdl = glucose * Constants.MMOLL_TO_MGDL;
+ }
+ return profile.toUnits(mgdl, mmol, profile.getUnits());
+ }
+
+ return yValue;
+ }
+
+ @Override
+ public void setY(double y) {
+ yValue = y;
+ }
+
+ @Override
+ public String getLabel() {
+ try {
+ JSONObject object = new JSONObject(json);
+ if (object.has("notes"))
+ return object.getString("notes");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ return Translator.translate(eventType);
+ }
+
+ @Override
+ public long getDuration() {
+ try {
+ JSONObject object = new JSONObject(json);
+ if (object.has("duration"))
+ return object.getInt("duration") * 60 * 1000L;
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ return 0;
+ }
+
+ @Override
+ public PointsWithLabelGraphSeries.Shape getShape() {
+ switch (eventType) {
+ case CareportalEvent.MBG:
+ return PointsWithLabelGraphSeries.Shape.MBG;
+ case CareportalEvent.BGCHECK:
+ return PointsWithLabelGraphSeries.Shape.BGCHECK;
+ case CareportalEvent.ANNOUNCEMENT:
+ return PointsWithLabelGraphSeries.Shape.ANNOUNCEMENT;
+ case CareportalEvent.OPENAPSOFFLINE:
+ return PointsWithLabelGraphSeries.Shape.OPENAPSOFFLINE;
+ case CareportalEvent.EXERCISE:
+ return PointsWithLabelGraphSeries.Shape.EXERCISE;
+ }
+ if (getDuration() > 0)
+ return PointsWithLabelGraphSeries.Shape.GENERALWITHDURATION;
+ return PointsWithLabelGraphSeries.Shape.GENERAL;
+ }
+
+ @Override
+ public float getSize() {
+ boolean isTablet = MainApp.sResources.getBoolean(R.bool.isTablet);
+ return isTablet ? 12 : 10;
+ }
+
+ @Override
+ public int getColor() {
+ if (eventType.equals(ANNOUNCEMENT))
+ return 0xFFFF8C00;
+ if (eventType.equals(MBG))
+ return Color.RED;
+ if (eventType.equals(BGCHECK))
+ return Color.RED;
+ if (eventType.equals(EXERCISE))
+ return Color.BLUE;
+ if (eventType.equals(OPENAPSOFFLINE))
+ return Color.GRAY;
+ return Color.GRAY;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DanaRHistoryRecord.java b/app/src/main/java/info/nightscout/androidaps/db/DanaRHistoryRecord.java
index 48b976548b..5c2e4f4985 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DanaRHistoryRecord.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DanaRHistoryRecord.java
@@ -8,38 +8,38 @@ import java.util.Date;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_DANARHISTORY)
public class DanaRHistoryRecord {
- @DatabaseField(useGetSet = true)
- private String _id;
+ @DatabaseField
+ public String _id;
- @DatabaseField(useGetSet = true)
- private byte recordCode;
+ @DatabaseField
+ public byte recordCode;
- @DatabaseField(id = true, useGetSet = true)
- private String bytes;
+ @DatabaseField(id = true)
+ public String bytes;
- @DatabaseField(useGetSet = true)
- private long recordDate;
+ @DatabaseField
+ public long recordDate;
- @DatabaseField(useGetSet = true)
- private double recordValue;
+ @DatabaseField
+ public double recordValue;
- @DatabaseField(useGetSet = true)
- private String bolusType;
+ @DatabaseField
+ public String bolusType;
- @DatabaseField(useGetSet = true)
- private String stringRecordValue;
+ @DatabaseField
+ public String stringRecordValue;
- @DatabaseField(useGetSet = true)
- private int recordDuration;
+ @DatabaseField
+ public int recordDuration;
- @DatabaseField(useGetSet = true)
- private double recordDailyBasal;
+ @DatabaseField
+ public double recordDailyBasal;
- @DatabaseField(useGetSet = true)
- private double recordDailyBolus;
+ @DatabaseField
+ public double recordDailyBolus;
- @DatabaseField(useGetSet = true)
- private String recordAlarm;
+ @DatabaseField
+ public String recordAlarm;
public DanaRHistoryRecord() {
this.recordDate = 0;
@@ -50,74 +50,6 @@ public class DanaRHistoryRecord {
this._id = null;
}
- public void setRecordDate(Date dtRecordDate) {
- this.recordDate = dtRecordDate.getTime();
- }
-
- public long getRecordDate() {
- return this.recordDate;
- }
-
- public void setRecordDate(long dtRecordDate) {
- this.recordDate = dtRecordDate;
- }
-
- public double getRecordValue() {
- return this.recordValue;
- }
-
- public void setRecordValue(double dRecordValue) {
- this.recordValue = dRecordValue;
- }
-
- public String getBolusType() {
- return this.bolusType;
- }
-
- public void setBolusType(String strRecordType) {
- this.bolusType = strRecordType;
- }
-
- public String getStringRecordValue() {
- return this.stringRecordValue;
- }
-
- public void setStringRecordValue(String strRecordValue) {
- this.stringRecordValue = strRecordValue;
- }
-
- public byte getRecordCode() {
- return this.recordCode;
- }
-
- public void setRecordCode(byte cRecordCode) {
- this.recordCode = cRecordCode;
- }
-
- public int getRecordDuration() {
- return this.recordDuration;
- }
-
- public void setRecordDuration(int dRecordDuraion) {
- this.recordDuration = dRecordDuraion;
- }
-
- public double getRecordDailyBasal() {
- return this.recordDailyBasal;
- }
-
- public void setRecordDailyBasal(double dRecordDailyBasal) {
- this.recordDailyBasal = dRecordDailyBasal;
- }
-
- public double getRecordDailyBolus() {
- return this.recordDailyBolus;
- }
-
- public void setRecordDailyBolus(double dRecordDailyBolus) {
- this.recordDailyBolus = dRecordDailyBolus;
- }
-
public int getRecordLevel(double dExLow, double dLow, double dHigh, double dExHigh) {
if (this.recordValue < dExLow)
return 0;
@@ -128,34 +60,10 @@ public class DanaRHistoryRecord {
return this.recordValue < dExHigh ? 3 : 4;
}
- public String getRecordAlarm() {
- return this.recordAlarm;
- }
-
- public void setRecordAlarm(String strAlarm) {
- this.recordAlarm = strAlarm;
- }
-
- public String get_id() {
- return this._id;
- }
-
- public void set_id(String _id) {
- this._id = _id;
- }
-
public void setBytes(byte[] raw) {
this.bytes = bytesToHex(raw);
}
- public void setBytes(String bytes) {
- this.bytes = bytes;
- }
-
- public String getBytes() {
- return this.bytes;
- }
-
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
index 17ee574678..cd216ef8e0 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
@@ -6,6 +6,7 @@ import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
+import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
@@ -13,6 +14,8 @@ import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,42 +31,78 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.events.EventCareportalEventChange;
+import info.nightscout.androidaps.events.EventExtendedBolusChange;
+import info.nightscout.androidaps.events.EventNewBG;
+import info.nightscout.androidaps.events.EventProfileSwitchChange;
+import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventReloadTempBasalData;
+import info.nightscout.androidaps.events.EventReloadTreatmentData;
+import info.nightscout.androidaps.events.EventTempBasalChange;
+import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
+import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
+import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings";
- public static final String DATABASE_TEMPBASALS = "TempBasals";
+ public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
+ public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
public static final String DATABASE_TEMPTARGETS = "TempTargets";
public static final String DATABASE_TREATMENTS = "Treatments";
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
public static final String DATABASE_DBREQUESTS = "DBRequests";
+ public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
+ public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
- private static final int DATABASE_VERSION = 5;
+ private static final int DATABASE_VERSION = 7;
- private long latestTreatmentChange = 0;
+ private static Long earliestDataChange = null;
- private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
- private static ScheduledFuture> scheduledPost = null;
+ private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledBgPost = null;
+
+ private static final ScheduledExecutorService treatmentsWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledTratmentPost = null;
+
+ private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledTemBasalsPost = null;
+
+ private static final ScheduledExecutorService tempTargetWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledTemTargetPost = null;
+
+ private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledExtendedBolusPost = null;
+
+ private static final ScheduledExecutorService careportalEventWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledCareportalEventPost = null;
+
+ private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledProfileSwitchEventPost = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(getWritableDatabase(), getConnectionSource());
+ //onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1);
}
-
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
log.info("onCreate");
- TableUtils.createTableIfNotExists(connectionSource, TempBasal.class);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
+ TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
+ TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
+ TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
+ TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
@@ -74,12 +113,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
- TableUtils.dropTable(connectionSource, TempBasal.class, true);
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
+ TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
+ TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
+ TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
+ TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
log.error("Can't drop databases", e);
@@ -98,53 +140,95 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void cleanUpDatabases() {
// TODO: call it somewhere
log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
- getWritableDatabase().delete(DATABASE_BGREADINGS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
+ getWritableDatabase().delete(DATABASE_BGREADINGS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
- log.debug("Before TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPBASALS));
- getWritableDatabase().delete(DATABASE_TEMPBASALS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
- log.debug("After TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPBASALS));
-
log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
- getWritableDatabase().delete(DATABASE_TEMPTARGETS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
+ getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
- getWritableDatabase().delete(DATABASE_TREATMENTS, "timeIndex" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
+ getWritableDatabase().delete(DATABASE_TREATMENTS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
log.debug("Before History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
getWritableDatabase().delete(DATABASE_DANARHISTORY, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
log.debug("After History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
+
+ log.debug("Before TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS));
+ getWritableDatabase().delete(DATABASE_TEMPORARYBASALS, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
+ log.debug("After TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS));
+
+ log.debug("Before ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES));
+ getWritableDatabase().delete(DATABASE_EXTENDEDBOLUSES, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
+ log.debug("After ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES));
+
+ log.debug("Before CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
+ getWritableDatabase().delete(DATABASE_CAREPORTALEVENTS, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
+ log.debug("After CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
+
+ log.debug("Before ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
+ getWritableDatabase().delete(DATABASE_PROFILESWITCHES, "recordDate" + " < '" + (new Date().getTime() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
+ log.debug("After ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
}
+ public long size(String database) {
+ return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
+ }
+
+ // --------------------- DB resets ---------------------
+
public void resetDatabases() {
try {
- TableUtils.dropTable(connectionSource, TempBasal.class, true);
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
- //DbRequests can be cleared from NSClient fragment
- TableUtils.createTableIfNotExists(connectionSource, TempBasal.class);
+ TableUtils.dropTable(connectionSource, DbRequest.class, true);
+ TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
+ TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
+ TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
+ TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
- latestTreatmentChange = 0;
+ TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
+ TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
+ TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
+ TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
+ TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
+ updateEarliestDataChange(0);
} catch (SQLException e) {
e.printStackTrace();
}
+ scheduleBgChange(); // trigger refresh
+ scheduleTemporaryBasalChange();
+ scheduleTreatmentChange();
+ scheduleExtendedBolusChange();
+ scheduleTemporaryTargetChange();
+ scheduleCareportalEventChange();
+ scheduleProfileSwitchChange();
+ new java.util.Timer().schedule(
+ new java.util.TimerTask() {
+ @Override
+ public void run() {
+ MainApp.bus().post(new EventRefreshGui(false));
+ }
+ },
+ 3000
+ );
}
public void resetTreatments() {
try {
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
- latestTreatmentChange = 0;
+ updateEarliestDataChange(0);
} catch (SQLException e) {
e.printStackTrace();
}
+ scheduleTreatmentChange();
}
public void resetTempTargets() {
@@ -154,13 +238,54 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
e.printStackTrace();
}
+ scheduleTemporaryTargetChange();
}
- public Dao getDaoTempBasals() throws SQLException {
- return getDao(TempBasal.class);
+ public void resetTemporaryBasals() {
+ try {
+ TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
+ TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
+ updateEarliestDataChange(0);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleTemporaryBasalChange();
}
- public Dao getDaoTempTargets() throws SQLException {
+ public void resetExtededBoluses() {
+ try {
+ TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
+ TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
+ updateEarliestDataChange(0);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleExtendedBolusChange();
+ }
+
+ public void resetCareportalEvents() {
+ try {
+ TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
+ TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleCareportalEventChange();
+ }
+
+ public void resetProfileSwitch() {
+ try {
+ TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
+ TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleProfileSwitchChange();
+ }
+
+ // ------------------ getDao -------------------------------------------
+
+ private Dao getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
}
@@ -168,30 +293,130 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(Treatment.class);
}
- public Dao getDaoBgReadings() throws SQLException {
+ private Dao getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
- public Dao getDaoDanaRHistory() throws SQLException {
+ private Dao getDaoDanaRHistory() throws SQLException {
return getDao(DanaRHistoryRecord.class);
}
- public Dao getDaoDbRequest() throws SQLException {
+ private Dao getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
- public long size(String database) {
- return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
+ private Dao getDaoTemporaryBasal() throws SQLException {
+ return getDao(TemporaryBasal.class);
}
+ private Dao getDaoExtendedBolus() throws SQLException {
+ return getDao(ExtendedBolus.class);
+ }
+
+ private Dao getDaoCareportalEvents() throws SQLException {
+ return getDao(CareportalEvent.class);
+ }
+
+ private Dao getDaoProfileSwitch() throws SQLException {
+ return getDao(ProfileSwitch.class);
+ }
+
+ public long roundDateToSec(long date) {
+ return date - date % 1000;
+ }
+ // ------------------- BgReading handling -----------------------
+
+ public void createIfNotExists(BgReading bgReading, String from) {
+ try {
+ bgReading.date = roundDateToSec(bgReading.date);
+ BgReading old = getDaoBgReadings().queryForId(bgReading.date);
+ if (old == null) {
+ getDaoBgReadings().create(bgReading);
+ log.debug("BG: New record from: " + from + " " + bgReading.toString());
+ scheduleBgChange();
+ return;
+ }
+ if (!old.isEqual(bgReading)) {
+ old.copyFrom(bgReading);
+ getDaoBgReadings().update(old);
+ log.debug("BG: Updating record from: " + from + " " + old.toString());
+ scheduleBgChange();
+ return;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void scheduleBgChange() {
+ class PostRunnable implements Runnable {
+ public void run() {
+ log.debug("Firing EventNewBg");
+ MainApp.bus().post(new EventNewBG());
+ scheduledBgPost = null;
+ }
+ }
+ // prepare task for execution in 1 sec
+ // cancel waiting task to prevent sending multiple posts
+ if (scheduledBgPost != null)
+ scheduledBgPost.cancel(false);
+ Runnable task = new PostRunnable();
+ final int sec = 1;
+ scheduledBgPost = bgWorker.schedule(task, sec, TimeUnit.SECONDS);
+
+ }
+
+ /*
+ * Return last BgReading from database or null if db is empty
+ */
+ @Nullable
+ public static BgReading lastBg() {
+ List bgList = null;
+
+ try {
+ Dao daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
+ QueryBuilder queryBuilder = daoBgReadings.queryBuilder();
+ queryBuilder.orderBy("date", false);
+ queryBuilder.limit(1L);
+ queryBuilder.where().gt("value", 38);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ bgList = daoBgReadings.query(preparedQuery);
+
+ } catch (SQLException e) {
+ log.debug(e.getMessage(), e);
+ }
+ if (bgList != null && bgList.size() > 0)
+ return bgList.get(0);
+ else
+ return null;
+ }
+
+ /*
+ * Return bg reading if not old ( <9 min )
+ * or null if older
+ */
+ @Nullable
+ public static BgReading actualBg() {
+ BgReading lastBg = lastBg();
+
+ if (lastBg == null)
+ return null;
+
+ if (lastBg.date > new Date().getTime() - 9 * 60 * 1000)
+ return lastBg;
+
+ return null;
+ }
+
+
public List getBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao daoBgreadings = getDaoBgReadings();
List bgReadings;
QueryBuilder queryBuilder = daoBgreadings.queryBuilder();
- queryBuilder.orderBy("timeIndex", ascending);
+ queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
- where.ge("timeIndex", mills).and().gt("value", 38);
+ where.ge("date", mills).and().gt("value", 38);
PreparedQuery preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
@@ -201,7 +426,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList();
}
- // DbRequests handling
+ // ------------- DbRequests handling -------------------
public void create(DbRequest dbr) {
try {
@@ -211,7 +436,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
- public int delete(DbRequest dbr) {
+ public int delete(DbRequest dbr) {
try {
return getDaoDbRequest().delete(dbr);
} catch (SQLException e) {
@@ -257,75 +482,121 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
- // TREATMENT HANDLING
-
- public boolean isDataUnchanged(long time) {
- if (time >= latestTreatmentChange) return true;
- else return false;
+ public CloseableIterator getDbRequestInterator() {
+ try {
+ return getDaoDbRequest().closeableIterator();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ return null;
+ }
}
- public int update(Treatment treatment) {
- int updated = 0;
+ // -------------------- TREATMENT HANDLING -------------------
+
+ // return true if new record is created
+ public boolean createOrUpdate(Treatment treatment) {
try {
- updated = getDaoTreatments().update(treatment);
- latestTreatmentChange = treatment.getTimeIndex();
+ Treatment old;
+ treatment.date = roundDateToSec(treatment.date);
+
+ if (treatment.source == Source.PUMP) {
+ // check for changed from pump change in NS
+ QueryBuilder queryBuilder = getDaoTreatments().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("pumpId", treatment.pumpId);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoTreatments().query(preparedQuery);
+ if (trList.size() > 0) {
+ // do nothing, pump history record cannot be changed
+ return false;
+ }
+ getDaoTreatments().create(treatment);
+ log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
+ updateEarliestDataChange(treatment.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ if (treatment.source == Source.NIGHTSCOUT) {
+ old = getDaoTreatments().queryForId(treatment.date);
+ if (old != null) {
+ if (!old.isEqual(treatment)) {
+ boolean historyChange = old.isDataChanging(treatment);
+ long oldDate = old.date;
+ getDaoTreatments().delete(old); // need to delete/create because date may change too
+ old.copyFrom(treatment);
+ getDaoTreatments().create(old);
+ log.debug("TREATMENT: Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString());
+ if (historyChange) {
+ updateEarliestDataChange(oldDate);
+ updateEarliestDataChange(old.date);
+ }
+ scheduleTreatmentChange();
+ return true;
+ }
+ return false;
+ }
+ // find by NS _id
+ if (treatment._id != null) {
+ QueryBuilder queryBuilder = getDaoTreatments().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", treatment._id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoTreatments().query(preparedQuery);
+ if (trList.size() > 0) {
+ old = trList.get(0);
+ if (!old.isEqual(treatment)) {
+ boolean historyChange = old.isDataChanging(treatment);
+ long oldDate = old.date;
+ getDaoTreatments().delete(old); // need to delete/create because date may change too
+ old.copyFrom(treatment);
+ getDaoTreatments().create(old);
+ log.debug("TREATMENT: Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
+ if (historyChange) {
+ updateEarliestDataChange(oldDate);
+ updateEarliestDataChange(old.date);
+ }
+ scheduleTreatmentChange();
+ return true;
+ }
+ }
+ }
+ getDaoTreatments().create(treatment);
+ log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
+ updateEarliestDataChange(treatment.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ if (treatment.source == Source.USER) {
+ getDaoTreatments().create(treatment);
+ log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
+ updateEarliestDataChange(treatment.date);
+ scheduleTreatmentChange();
+ return true;
+ }
} catch (SQLException e) {
e.printStackTrace();
}
- scheduleTreatmentChange();
- return updated;
- }
-
- public Dao.CreateOrUpdateStatus createOrUpdate(Treatment treatment) {
- Dao.CreateOrUpdateStatus status = null;
- try {
- status = getDaoTreatments().createOrUpdate(treatment);
- latestTreatmentChange = treatment.getTimeIndex();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- scheduleTreatmentChange();
- return status;
- }
-
- public void create(Treatment treatment) {
- try {
- getDaoTreatments().create(treatment);
- latestTreatmentChange = treatment.getTimeIndex();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- scheduleTreatmentChange();
+ return false;
}
public void delete(Treatment treatment) {
try {
getDaoTreatments().delete(treatment);
- latestTreatmentChange = treatment.getTimeIndex();
+ updateEarliestDataChange(treatment.date);
} catch (SQLException e) {
e.printStackTrace();
}
scheduleTreatmentChange();
}
- public int delete(String _id) {
+ public void deleteTreatmentById(String _id) {
Treatment stored = findTreatmentById(_id);
- int removed = 0;
if (stored != null) {
- log.debug("REMOVE: Existing treatment (removing): " + _id);
- try {
- removed = getDaoTreatments().delete(stored);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if (Config.logIncommingData)
- log.debug("Records removed: " + removed);
- latestTreatmentChange = stored.getTimeIndex();
+ log.debug("TREATMENT: Removing Treatment record from database: " + stored.toString());
+ delete(stored);
+ updateEarliestDataChange(stored.date);
scheduleTreatmentChange();
- } else {
- log.debug("REMOVE: Not stored treatment (ignoring): " + _id);
}
- return removed;
}
@Nullable
@@ -351,44 +622,35 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null;
}
- @Nullable
- public Treatment findTreatmentByTimeIndex(Long timeIndex) {
- try {
- QueryBuilder qb = null;
- Dao daoTreatments = getDaoTreatments();
- QueryBuilder queryBuilder = daoTreatments.queryBuilder();
- Where where = queryBuilder.where();
- where.eq("timeIndex", timeIndex);
- queryBuilder.limit(10L);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = daoTreatments.query(preparedQuery);
- if (trList.size() != 1) {
- log.debug("Treatment findTreatmentByTimeIndex query size: " + trList.size());
- return null;
- } else {
- log.debug("Treatment findTreatmentByTimeIndex found: " + trList.get(0).log());
- return trList.get(0);
- }
- } catch (SQLException e) {
- e.printStackTrace();
+ private void updateEarliestDataChange(long newDate) {
+ if (earliestDataChange == null) {
+ earliestDataChange = newDate;
+ return;
+ }
+ if (newDate < earliestDataChange) {
+ earliestDataChange = newDate;
}
- return null;
}
- static public void scheduleTreatmentChange() {
+ private static void scheduleTreatmentChange() {
class PostRunnable implements Runnable {
public void run() {
+ log.debug("Firing EventTreatmentChange");
+ MainApp.bus().post(new EventReloadTreatmentData());
MainApp.bus().post(new EventTreatmentChange());
- scheduledPost = null;
+ if (earliestDataChange != null)
+ MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
+ earliestDataChange = null;
+ scheduledTratmentPost = null;
}
}
- // prepare task for execution in 5 sec
+ // prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
- if (scheduledPost != null)
- scheduledPost.cancel(false);
+ if (scheduledTratmentPost != null)
+ scheduledTratmentPost.cancel(false);
Runnable task = new PostRunnable();
- final int sec = 5;
- scheduledPost = worker.schedule(task, sec, TimeUnit.SECONDS);
+ final int sec = 1;
+ scheduledTratmentPost = treatmentsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
@@ -397,9 +659,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
Dao daoTreatments = getDaoTreatments();
List treatments;
QueryBuilder queryBuilder = daoTreatments.queryBuilder();
- queryBuilder.orderBy("timeIndex", ascending);
+ queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
- where.ge("timeIndex", mills);
+ where.ge("date", mills);
PreparedQuery preparedQuery = queryBuilder.prepare();
treatments = daoTreatments.query(preparedQuery);
return treatments;
@@ -409,14 +671,43 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList();
}
+ public void createTreatmentFromJsonIfNotExists(JSONObject trJson) {
+ try {
+ Treatment treatment = new Treatment();
+ treatment.source = Source.NIGHTSCOUT;
+ treatment.date = roundDateToSec(trJson.getLong("mills"));
+ treatment.carbs = trJson.has("carbs") ? trJson.getDouble("carbs") : 0;
+ treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d;
+ treatment.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
+ treatment._id = trJson.getString("_id");
+ if (trJson.has("eventType")) {
+ treatment.mealBolus = !trJson.get("eventType").equals("Correction Bolus");
+ double carbs = treatment.carbs;
+ if (trJson.has("boluscalc")) {
+ JSONObject boluscalc = trJson.getJSONObject("boluscalc");
+ if (boluscalc.has("carbs")) {
+ carbs = Math.max(boluscalc.getDouble("carbs"), carbs);
+ }
+ }
+ if (carbs <= 0)
+ treatment.mealBolus = false;
+ }
+ createOrUpdate(treatment);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // ---------------- TempTargets handling ---------------
+
public List getTemptargetsDataFromTime(long mills, boolean ascending) {
try {
Dao daoTempTargets = getDaoTempTargets();
List tempTargets;
QueryBuilder queryBuilder = daoTempTargets.queryBuilder();
- queryBuilder.orderBy("timeIndex", ascending);
+ queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
- where.ge("timeIndex", mills);
+ where.ge("date", mills);
PreparedQuery preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
@@ -426,22 +717,923 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList();
}
-
- public List getTempbasalsDataFromTime(long mills, boolean ascending, boolean isExtended) {
+ public boolean createOrUpdate(TempTarget tempTarget) {
try {
- Dao daoTempbasals = getDaoTempBasals();
- List tempbasals;
- QueryBuilder queryBuilder = daoTempbasals.queryBuilder();
- queryBuilder.orderBy("timeIndex", ascending);
+ TempTarget old;
+ tempTarget.date = roundDateToSec(tempTarget.date);
+
+ if (tempTarget.source == Source.NIGHTSCOUT) {
+ old = getDaoTempTargets().queryForId(tempTarget.date);
+ if (old != null) {
+ if (!old.isEqual(tempTarget)) {
+ getDaoTempTargets().delete(old); // need to delete/create because date may change too
+ old.copyFrom(tempTarget);
+ getDaoTempTargets().create(old);
+ log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ return false;
+ }
+ // find by NS _id
+ if (tempTarget._id != null) {
+ QueryBuilder queryBuilder = getDaoTempTargets().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", tempTarget._id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoTempTargets().query(preparedQuery);
+ if (trList.size() > 0) {
+ old = trList.get(0);
+ if (!old.isEqual(tempTarget)) {
+ getDaoTempTargets().delete(old); // need to delete/create because date may change too
+ old.copyFrom(tempTarget);
+ getDaoTempTargets().create(old);
+ log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ }
+ }
+ getDaoTempTargets().create(tempTarget);
+ log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ if (tempTarget.source == Source.USER) {
+ getDaoTempTargets().create(tempTarget);
+ log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+
+ public void delete(TempTarget tempTarget) {
+ try {
+ getDaoTempTargets().delete(tempTarget);
+ scheduleTemporaryTargetChange();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void scheduleTemporaryTargetChange() {
+ class PostRunnable implements Runnable {
+ public void run() {
+ log.debug("Firing EventTempTargetChange");
+ MainApp.bus().post(new EventTempTargetChange());
+ scheduledTemTargetPost = null;
+ }
+ }
+ // prepare task for execution in 1 sec
+ // cancel waiting task to prevent sending multiple posts
+ if (scheduledTemTargetPost != null)
+ scheduledTemTargetPost.cancel(false);
+ Runnable task = new PostRunnable();
+ final int sec = 1;
+ scheduledTemTargetPost = tempTargetWorker.schedule(task, sec, TimeUnit.SECONDS);
+
+ }
+
+ /*
+ {
+ "_id": "58795998aa86647ba4d68ce7",
+ "enteredBy": "",
+ "eventType": "Temporary Target",
+ "reason": "Eating Soon",
+ "targetTop": 80,
+ "targetBottom": 80,
+ "duration": 120,
+ "created_at": "2017-01-13T22:50:00.782Z",
+ "carbs": null,
+ "insulin": null
+}
+ */
+
+ public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
+ try {
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ String units = profile.getUnits();
+ TempTarget tempTarget = new TempTarget();
+ tempTarget.date = trJson.getLong("mills");
+ tempTarget.durationInMinutes = trJson.getInt("duration");
+ tempTarget.low = Profile.toMgdl(trJson.getDouble("targetBottom"), units);
+ tempTarget.high = Profile.toMgdl(trJson.getDouble("targetTop"), units);
+ tempTarget.reason = trJson.getString("reason");
+ tempTarget._id = trJson.getString("_id");
+ tempTarget.source = Source.NIGHTSCOUT;
+ createOrUpdate(tempTarget);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void deleteTempTargetById(String _id) {
+ TempTarget stored = findTempTargetById(_id);
+ if (stored != null) {
+ log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString());
+ delete(stored);
+ scheduleTemporaryTargetChange();
+ }
+ }
+
+ public TempTarget findTempTargetById(String _id) {
+ try {
+ QueryBuilder queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
- where.ge("timeIndex", mills).and().eq("isExtended", isExtended);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- tempbasals = daoTempbasals.query(preparedQuery);
+ where.eq("_id", _id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoTempTargets().query(preparedQuery);
+
+ if (list.size() == 1) {
+ return list.get(0);
+ } else {
+ return null;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ // ----------------- DanaRHistory handling --------------------
+
+ public void createOrUpdate(DanaRHistoryRecord record) {
+ try {
+ getDaoDanaRHistory().createOrUpdate(record);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public List getDanaRHistoryRecordsByType(byte type) {
+ List historyList;
+ try {
+ QueryBuilder queryBuilder = getDaoDanaRHistory().queryBuilder();
+ queryBuilder.orderBy("recordDate", false);
+ Where where = queryBuilder.where();
+ where.eq("recordCode", type);
+ queryBuilder.limit(200L);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ historyList = getDaoDanaRHistory().query(preparedQuery);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ historyList = new ArrayList<>();
+ }
+ return historyList;
+ }
+
+ public void updateDanaRHistoryRecordId(JSONObject trJson) {
+ try {
+ QueryBuilder queryBuilder = getDaoDanaRHistory().queryBuilder();
+ Where where = queryBuilder.where();
+ where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoDanaRHistory().query(preparedQuery);
+ if (list.size() == 0) {
+ // Record does not exists. Ignore
+ } else if (list.size() == 1) {
+ DanaRHistoryRecord record = list.get(0);
+ if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
+ if (Config.logIncommingData)
+ log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
+ record._id = trJson.getString("_id");
+ getDaoDanaRHistory().update(record);
+ } else {
+ // already set
+ }
+ }
+ } catch (SQLException | JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // ------------ TemporaryBasal handling ---------------
+
+ //return true if new record was created
+ public boolean createOrUpdate(TemporaryBasal tempBasal) {
+ try {
+ TemporaryBasal old;
+ tempBasal.date = roundDateToSec(tempBasal.date);
+
+ if (tempBasal.source == Source.PUMP) {
+ // check for changed from pump change in NS
+ QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("pumpId", tempBasal.pumpId);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoTemporaryBasal().query(preparedQuery);
+ if (trList.size() > 0) {
+ // do nothing, pump history record cannot be changed
+ log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
+ return false;
+ }
+ getDaoTemporaryBasal().create(tempBasal);
+ log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
+ updateEarliestDataChange(tempBasal.date);
+ scheduleTemporaryBasalChange();
+ return true;
+ }
+ if (tempBasal.source == Source.NIGHTSCOUT) {
+ old = getDaoTemporaryBasal().queryForId(tempBasal.date);
+ if (old != null) {
+ if (!old.isEqual(tempBasal)) {
+ long oldDate = old.date;
+ getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
+ old.copyFrom(tempBasal);
+ getDaoTemporaryBasal().create(old);
+ log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
+ updateEarliestDataChange(oldDate);
+ updateEarliestDataChange(old.date);
+ scheduleTemporaryBasalChange();
+ return true;
+ }
+ return false;
+ }
+ // find by NS _id
+ if (tempBasal._id != null) {
+ QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", tempBasal._id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoTemporaryBasal().query(preparedQuery);
+ if (trList.size() > 0) {
+ old = trList.get(0);
+ if (!old.isEqual(tempBasal)) {
+ long oldDate = old.date;
+ getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
+ old.copyFrom(tempBasal);
+ getDaoTemporaryBasal().create(old);
+ log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
+ updateEarliestDataChange(oldDate);
+ updateEarliestDataChange(old.date);
+ scheduleTemporaryBasalChange();
+ return true;
+ }
+ }
+ }
+ getDaoTemporaryBasal().create(tempBasal);
+ log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
+ updateEarliestDataChange(tempBasal.date);
+ scheduleTemporaryBasalChange();
+ return true;
+ }
+ if (tempBasal.source == Source.USER) {
+ getDaoTemporaryBasal().create(tempBasal);
+ log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
+ updateEarliestDataChange(tempBasal.date);
+ scheduleTemporaryBasalChange();
+ return true;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+
+ public void delete(TemporaryBasal tempBasal) {
+ try {
+ getDaoTemporaryBasal().delete(tempBasal);
+ updateEarliestDataChange(tempBasal.date);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleTemporaryBasalChange();
+ }
+
+ public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
+ try {
+ List tempbasals;
+ QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ Where where = queryBuilder.where();
+ where.ge("date", mills);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
e.printStackTrace();
}
- return new ArrayList();
+ return new ArrayList();
}
+ private static void scheduleTemporaryBasalChange() {
+ class PostRunnable implements Runnable {
+ public void run() {
+ log.debug("Firing EventTempBasalChange");
+ MainApp.bus().post(new EventReloadTempBasalData());
+ MainApp.bus().post(new EventTempBasalChange());
+ if (earliestDataChange != null)
+ MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
+ earliestDataChange = null;
+ scheduledTemBasalsPost = null;
+ }
+ }
+ // prepare task for execution in 1 sec
+ // cancel waiting task to prevent sending multiple posts
+ if (scheduledTemBasalsPost != null)
+ scheduledTemBasalsPost.cancel(false);
+ Runnable task = new PostRunnable();
+ final int sec = 1;
+ scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
+
+ }
+
+ /*
+ {
+ "_id": "59232e1ddd032d04218dab00",
+ "eventType": "Temp Basal",
+ "duration": 60,
+ "percent": -50,
+ "created_at": "2017-05-22T18:29:57Z",
+ "enteredBy": "AndroidAPS",
+ "notes": "Basal Temp Start 50% 60.0 min",
+ "NSCLIENT_ID": 1495477797863,
+ "mills": 1495477797000,
+ "mgdl": 194.5,
+ "endmills": 1495481397000
+ }
+ */
+
+ public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
+ try {
+ if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
+ ExtendedBolus extendedBolus = new ExtendedBolus();
+ extendedBolus.source = Source.NIGHTSCOUT;
+ extendedBolus.date = trJson.getLong("mills");
+ extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
+ extendedBolus.durationInMinutes = trJson.getInt("duration");
+ extendedBolus.insulin = trJson.getDouble("originalExtendedAmount");
+ extendedBolus._id = trJson.getString("_id");
+ createOrUpdate(extendedBolus);
+ } else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
+ ExtendedBolus extendedBolus = new ExtendedBolus();
+ extendedBolus.source = Source.NIGHTSCOUT;
+ extendedBolus.date = trJson.getLong("mills");
+ extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
+ extendedBolus.durationInMinutes = 0;
+ extendedBolus.insulin = 0;
+ extendedBolus._id = trJson.getString("_id");
+ createOrUpdate(extendedBolus);
+ } else {
+ TemporaryBasal tempBasal = new TemporaryBasal();
+ tempBasal.date = trJson.getLong("mills");
+ tempBasal.source = Source.NIGHTSCOUT;
+ tempBasal.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
+ if (trJson.has("duration")) {
+ tempBasal.durationInMinutes = trJson.getInt("duration");
+ }
+ if (trJson.has("percent")) {
+ tempBasal.percentRate = trJson.getInt("percent") + 100;
+ tempBasal.isAbsolute = false;
+ }
+ if (trJson.has("absolute")) {
+ tempBasal.absoluteRate = trJson.getDouble("absolute");
+ tempBasal.isAbsolute = true;
+ }
+ tempBasal._id = trJson.getString("_id");
+ createOrUpdate(tempBasal);
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void deleteTempBasalById(String _id) {
+ TemporaryBasal stored = findTempBasalById(_id);
+ if (stored != null) {
+ log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
+ delete(stored);
+ updateEarliestDataChange(stored.date);
+ scheduleTemporaryBasalChange();
+ }
+ }
+
+ public TemporaryBasal findTempBasalById(String _id) {
+ try {
+ QueryBuilder queryBuilder = null;
+ queryBuilder = getDaoTemporaryBasal().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", _id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoTemporaryBasal().query(preparedQuery);
+
+ if (list.size() != 1) {
+ return null;
+ } else {
+ return list.get(0);
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ // ------------ ExtendedBolus handling ---------------
+
+ public boolean createOrUpdate(ExtendedBolus extendedBolus) {
+ try {
+ ExtendedBolus old;
+ extendedBolus.date = roundDateToSec(extendedBolus.date);
+
+ if (extendedBolus.source == Source.PUMP) {
+ // check for changed from pump change in NS
+ QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("pumpId", extendedBolus.pumpId);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoExtendedBolus().query(preparedQuery);
+ if (trList.size() > 0) {
+ // do nothing, pump history record cannot be changed
+ return false;
+ }
+ getDaoExtendedBolus().create(extendedBolus);
+ log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
+ updateEarliestDataChange(extendedBolus.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ if (extendedBolus.source == Source.NIGHTSCOUT) {
+ old = getDaoExtendedBolus().queryForId(extendedBolus.date);
+ if (old != null) {
+ if (!old.isEqual(extendedBolus)) {
+ long oldDate = old.date;
+ getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
+ old.copyFrom(extendedBolus);
+ getDaoExtendedBolus().create(old);
+ log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString());
+ updateEarliestDataChange(oldDate);
+ updateEarliestDataChange(old.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ return false;
+ }
+ // find by NS _id
+ if (extendedBolus._id != null) {
+ QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", extendedBolus._id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoExtendedBolus().query(preparedQuery);
+ if (trList.size() > 0) {
+ old = trList.get(0);
+ if (!old.isEqual(extendedBolus)) {
+ long oldDate = old.date;
+ getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
+ old.copyFrom(extendedBolus);
+ getDaoExtendedBolus().create(old);
+ log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString());
+ updateEarliestDataChange(oldDate);
+ updateEarliestDataChange(old.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ }
+ }
+ getDaoExtendedBolus().create(extendedBolus);
+ log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
+ updateEarliestDataChange(extendedBolus.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ if (extendedBolus.source == Source.USER) {
+ getDaoExtendedBolus().create(extendedBolus);
+ log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
+ updateEarliestDataChange(extendedBolus.date);
+ scheduleTreatmentChange();
+ return true;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+
+ public void delete(ExtendedBolus extendedBolus) {
+ try {
+ getDaoExtendedBolus().delete(extendedBolus);
+ updateEarliestDataChange(extendedBolus.date);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleExtendedBolusChange();
+ }
+
+ public List getExtendedBolusDataFromTime(long mills, boolean ascending) {
+ try {
+ List extendedBoluses;
+ QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ Where where = queryBuilder.where();
+ where.ge("date", mills);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
+ return extendedBoluses;
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return new ArrayList();
+ }
+
+ public void deleteExtendedBolusById(String _id) {
+ ExtendedBolus stored = findExtendedBolusById(_id);
+ if (stored != null) {
+ log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
+ delete(stored);
+ updateEarliestDataChange(stored.date);
+ scheduleExtendedBolusChange();
+ }
+ }
+ public ExtendedBolus findExtendedBolusById(String _id) {
+ try {
+ QueryBuilder queryBuilder = null;
+ queryBuilder = getDaoExtendedBolus().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", _id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoExtendedBolus().query(preparedQuery);
+
+ if (list.size() == 1) {
+ return list.get(0);
+ } else {
+ return null;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /*
+{
+ "_id": "5924898d577eb0880e355337",
+ "eventType": "Combo Bolus",
+ "duration": 120,
+ "splitNow": 0,
+ "splitExt": 100,
+ "enteredinsulin": 1,
+ "relative": 1,
+ "created_at": "2017-05-23T19:12:14Z",
+ "enteredBy": "AndroidAPS",
+ "NSCLIENT_ID": 1495566734628,
+ "mills": 1495566734000,
+ "mgdl": 106
}
+ */
+
+ public void createExtendedBolusFromJsonIfNotExists(JSONObject trJson) {
+ try {
+ QueryBuilder queryBuilder = null;
+ queryBuilder = getDaoExtendedBolus().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoExtendedBolus().query(preparedQuery);
+ ExtendedBolus extendedBolus;
+ if (list.size() == 0) {
+ extendedBolus = new ExtendedBolus();
+ extendedBolus.source = Source.NIGHTSCOUT;
+ if (Config.logIncommingData)
+ log.debug("Adding ExtendedBolus record to database: " + trJson.toString());
+ // Record does not exists. add
+ } else if (list.size() == 1) {
+ extendedBolus = list.get(0);
+ if (Config.logIncommingData)
+ log.debug("Updating ExtendedBolus record in database: " + trJson.toString());
+ } else {
+ log.error("Something went wrong");
+ return;
+ }
+ extendedBolus.date = trJson.getLong("mills");
+ extendedBolus.durationInMinutes = trJson.getInt("duration");
+ extendedBolus.insulin = trJson.getDouble("relative");
+ extendedBolus._id = trJson.getString("_id");
+ createOrUpdate(extendedBolus);
+ } catch (SQLException | JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void scheduleExtendedBolusChange() {
+ class PostRunnable implements Runnable {
+ public void run() {
+ log.debug("Firing EventExtendedBolusChange");
+ MainApp.bus().post(new EventReloadTreatmentData());
+ MainApp.bus().post(new EventExtendedBolusChange());
+ if (earliestDataChange != null)
+ MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
+ earliestDataChange = null;
+ scheduledExtendedBolusPost = null;
+ }
+ }
+ // prepare task for execution in 1 sec
+ // cancel waiting task to prevent sending multiple posts
+ if (scheduledExtendedBolusPost != null)
+ scheduledExtendedBolusPost.cancel(false);
+ Runnable task = new PostRunnable();
+ final int sec = 1;
+ scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
+
+ }
+
+
+ // ------------ CareportalEvent handling ---------------
+
+ public void createOrUpdate(CareportalEvent careportalEvent) {
+ careportalEvent.date = careportalEvent.date - careportalEvent.date % 1000;
+ try {
+ getDaoCareportalEvents().createOrUpdate(careportalEvent);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleCareportalEventChange();
+ }
+
+ public void delete(CareportalEvent careportalEvent) {
+ try {
+ getDaoCareportalEvents().delete(careportalEvent);
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ scheduleCareportalEventChange();
+ }
+
+ @Nullable
+ public CareportalEvent getLastCareportalEvent(String event) {
+ try {
+ List careportalEvents;
+ QueryBuilder queryBuilder = getDaoCareportalEvents().queryBuilder();
+ queryBuilder.orderBy("date", false);
+ Where where = queryBuilder.where();
+ where.eq("eventType", event);
+ queryBuilder.limit(1L);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ careportalEvents = getDaoCareportalEvents().query(preparedQuery);
+ if (careportalEvents.size() == 1)
+ return careportalEvents.get(0);
+ else
+ return null;
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ public List getCareportalEventsFromTime(long mills, boolean ascending) {
+ try {
+ List careportalEvents;
+ QueryBuilder queryBuilder = getDaoCareportalEvents().queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ Where where = queryBuilder.where();
+ where.ge("date", mills);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ careportalEvents = getDaoCareportalEvents().query(preparedQuery);
+ return careportalEvents;
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return new ArrayList();
+ }
+
+ public void deleteCareportalEventById(String _id) {
+ try {
+ QueryBuilder queryBuilder = null;
+ queryBuilder = getDaoCareportalEvents().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", _id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoCareportalEvents().query(preparedQuery);
+
+ if (list.size() == 1) {
+ CareportalEvent record = list.get(0);
+ if (Config.logIncommingData)
+ log.debug("Removing CareportalEvent record from database: " + record.log());
+ delete(record);
+ } else {
+ if (Config.logIncommingData)
+ log.debug("CareportalEvent not found database: " + _id);
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) {
+ try {
+ QueryBuilder queryBuilder = null;
+ queryBuilder = getDaoCareportalEvents().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoCareportalEvents().query(preparedQuery);
+ CareportalEvent careportalEvent;
+ if (list.size() == 0) {
+ careportalEvent = new CareportalEvent();
+ careportalEvent.source = Source.NIGHTSCOUT;
+ if (Config.logIncommingData)
+ log.debug("Adding CareportalEvent record to database: " + trJson.toString());
+ // Record does not exists. add
+ } else if (list.size() == 1) {
+ careportalEvent = list.get(0);
+ if (Config.logIncommingData)
+ log.debug("Updating CareportalEvent record in database: " + trJson.toString());
+ } else {
+ log.error("Something went wrong");
+ return;
+ }
+ careportalEvent.date = trJson.getLong("mills");
+ careportalEvent.eventType = trJson.getString("eventType");
+ careportalEvent.json = trJson.toString();
+ careportalEvent._id = trJson.getString("_id");
+ createOrUpdate(careportalEvent);
+ } catch (SQLException | JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void scheduleCareportalEventChange() {
+ class PostRunnable implements Runnable {
+ public void run() {
+ log.debug("Firing scheduleCareportalEventChange");
+ MainApp.bus().post(new EventCareportalEventChange());
+ scheduledCareportalEventPost = null;
+ }
+ }
+ // prepare task for execution in 1 sec
+ // cancel waiting task to prevent sending multiple posts
+ if (scheduledCareportalEventPost != null)
+ scheduledCareportalEventPost.cancel(false);
+ Runnable task = new PostRunnable();
+ final int sec = 1;
+ scheduledCareportalEventPost = careportalEventWorker.schedule(task, sec, TimeUnit.SECONDS);
+
+ }
+
+ // ---------------- ProfileSwitch handling ---------------
+
+ public List getProfileSwitchData(boolean ascending) {
+ try {
+ Dao daoProfileSwitch = getDaoProfileSwitch();
+ List profileSwitches;
+ QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ queryBuilder.limit(20L);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ profileSwitches = daoProfileSwitch.query(preparedQuery);
+ return profileSwitches;
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return new ArrayList();
+ }
+
+ public boolean createOrUpdate(ProfileSwitch profileSwitch) {
+ try {
+ ProfileSwitch old;
+ profileSwitch.date = roundDateToSec(profileSwitch.date);
+
+ if (profileSwitch.source == Source.NIGHTSCOUT) {
+ old = getDaoProfileSwitch().queryForId(profileSwitch.date);
+ if (old != null) {
+ if (!old.isEqual(profileSwitch)) {
+ getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
+ old.copyFrom(profileSwitch);
+ getDaoProfileSwitch().create(old);
+ log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ return false;
+ }
+ // find by NS _id
+ if (profileSwitch._id != null) {
+ QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", profileSwitch._id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List trList = getDaoProfileSwitch().query(preparedQuery);
+ if (trList.size() > 0) {
+ old = trList.get(0);
+ if (!old.isEqual(profileSwitch)) {
+ getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
+ old.copyFrom(profileSwitch);
+ getDaoProfileSwitch().create(old);
+ log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ }
+ }
+ getDaoProfileSwitch().create(profileSwitch);
+ log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ if (profileSwitch.source == Source.USER) {
+ getDaoProfileSwitch().create(profileSwitch);
+ log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
+ scheduleTemporaryTargetChange();
+ return true;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+
+ public void delete(ProfileSwitch profileSwitch) {
+ try {
+ getDaoProfileSwitch().delete(profileSwitch);
+ scheduleProfileSwitchChange();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void scheduleProfileSwitchChange() {
+ class PostRunnable implements Runnable {
+ public void run() {
+ log.debug("Firing EventProfileSwitchChange");
+ MainApp.bus().post(new EventProfileSwitchChange());
+ scheduledProfileSwitchEventPost = null;
+ }
+ }
+ // prepare task for execution in 1 sec
+ // cancel waiting task to prevent sending multiple posts
+ if (scheduledProfileSwitchEventPost != null)
+ scheduledProfileSwitchEventPost.cancel(false);
+ Runnable task = new PostRunnable();
+ final int sec = 1;
+ scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
+
+ }
+
+ /*
+{
+ "_id":"592fa43ed97496a80da913d2",
+ "created_at":"2017-06-01T05:20:06Z",
+ "eventType":"Profile Switch",
+ "profile":"2016 +30%",
+ "units":"mmol",
+ "enteredBy":"sony",
+ "NSCLIENT_ID":1496294454309,
+}
+ */
+
+ public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
+ try {
+ ProfileSwitch profileSwitch = new ProfileSwitch();
+ profileSwitch.date = trJson.getLong("mills");
+ if (trJson.has("duration"))
+ profileSwitch.durationInMinutes = trJson.getInt("duration");
+ profileSwitch._id = trJson.getString("_id");
+ profileSwitch.profileName = trJson.getString("profile");
+ profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
+ profileSwitch.source = Source.NIGHTSCOUT;
+ if (trJson.has("timeshift"))
+ profileSwitch.timeshift = trJson.getInt("timeshift");
+ if (trJson.has("percentage"))
+ profileSwitch.percentage = trJson.getInt("percentage");
+ if (trJson.has("profileJson"))
+ profileSwitch.profileJson = trJson.getString("profileJson");
+ if (trJson.has("profilePlugin"))
+ profileSwitch.profilePlugin = trJson.getString("profilePlugin");
+ createOrUpdate(profileSwitch);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void deleteProfileSwitchById(String _id) {
+ ProfileSwitch stored = findProfileSwitchById(_id);
+ if (stored != null) {
+ log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
+ delete(stored);
+ scheduleTemporaryTargetChange();
+ }
+ }
+
+ public ProfileSwitch findProfileSwitchById(String _id) {
+ try {
+ QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder();
+ Where where = queryBuilder.where();
+ where.eq("_id", _id);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoProfileSwitch().query(preparedQuery);
+
+ if (list.size() == 1) {
+ return list.get(0);
+ } else {
+ return null;
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java b/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java
index 0ecc5d4f32..203436661c 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java
@@ -19,15 +19,7 @@ import org.slf4j.LoggerFactory;
public class DbRequest {
private static Logger log = LoggerFactory.getLogger(DbRequest.class);
- public String getNsClientID() {
- return nsClientID;
- }
-
- public void setNsClientID(String nsClientID) {
- this.nsClientID = nsClientID;
- }
-
- @DatabaseField(id = true, useGetSet = true)
+ @DatabaseField(id = true)
public String nsClientID = null;
@DatabaseField
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
new file mode 100644
index 0000000000..d422a94211
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
@@ -0,0 +1,287 @@
+package info.nightscout.androidaps.db;
+
+/**
+ * Created by mike on 21.05.2017.
+ */
+
+import android.graphics.Color;
+
+import com.j256.ormlite.field.DatabaseField;
+import com.j256.ormlite.table.DatabaseTable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Date;
+import java.util.Objects;
+
+import info.nightscout.androidaps.Constants;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
+import info.nightscout.androidaps.interfaces.Interval;
+import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.utils.Round;
+
+/**
+ * Created by mike on 21.05.2017.
+ */
+
+@DatabaseTable(tableName = DatabaseHelper.DATABASE_EXTENDEDBOLUSES)
+public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
+ private static Logger log = LoggerFactory.getLogger(ExtendedBolus.class);
+
+ @DatabaseField(id = true)
+ public long date;
+
+ @DatabaseField
+ public boolean isValid = true;
+
+ @DatabaseField(index = true)
+ public long pumpId = 0;
+
+ @DatabaseField
+ public int source = Source.NONE;
+ @DatabaseField
+ public String _id = null; // NS _id
+
+ @DatabaseField
+ public double insulin = 0d;
+ @DatabaseField
+ public int durationInMinutes = 0; // duration == 0 means end of extended bolus
+
+ @DatabaseField
+ public int insulinInterfaceID = InsulinInterface.FASTACTINGINSULIN;
+ @DatabaseField
+ public double dia = Constants.defaultDIA;
+
+ public ExtendedBolus() {
+ }
+
+ public ExtendedBolus(long date) {
+ this.date = date;
+ }
+
+ public boolean isEqual(ExtendedBolus other) {
+ if (date != other.date) {
+ return false;
+ }
+ if (durationInMinutes != other.durationInMinutes)
+ return false;
+ if (insulin != other.insulin)
+ return false;
+ if (pumpId != other.pumpId)
+ return false;
+ if (!Objects.equals(_id, other._id))
+ return false;
+ return true;
+ }
+
+ public void copyFrom(ExtendedBolus t) {
+ date = t.date;
+ _id = t._id;
+ durationInMinutes = t.durationInMinutes;
+ insulin = t.insulin;
+ pumpId = t.pumpId;
+ }
+
+ // -------- Interval interface ---------
+
+ Long cuttedEnd = null;
+
+ public long durationInMsec() {
+ return durationInMinutes * 60 * 1000L;
+ }
+
+ public long start() {
+ return date;
+ }
+
+ // planned end time at time of creation
+ public long originalEnd() {
+ return date + durationInMinutes * 60 * 1000L;
+ }
+
+ // end time after cut
+ public long end() {
+ if (cuttedEnd != null)
+ return cuttedEnd;
+ return originalEnd();
+ }
+
+ public void cutEndTo(long end) {
+ cuttedEnd = end;
+ }
+
+ public boolean match(long time) {
+ if (start() <= time && end() >= time)
+ return true;
+ return false;
+ }
+
+ public boolean before(long time) {
+ if (end() < time)
+ return true;
+ return false;
+ }
+
+ public boolean after(long time) {
+ if (start() > time)
+ return true;
+ return false;
+ }
+
+ @Override
+ public boolean isInProgress() {
+ return match(new Date().getTime());
+ }
+
+ @Override
+ public boolean isEndingEvent() {
+ return durationInMinutes == 0;
+ }
+
+ // -------- Interval interface end ---------
+
+ public String log() {
+ return "Bolus{" +
+ "date= " + date +
+ ", date= " + DateUtil.dateAndTimeString(date) +
+ ", isValid=" + isValid +
+ ", _id= " + _id +
+ ", pumpId= " + pumpId +
+ ", insulin= " + insulin +
+ ", durationInMinutes= " + durationInMinutes +
+ "}";
+ }
+
+ public double absoluteRate() {
+ return Round.roundTo(insulin / durationInMinutes * 60, 0.01);
+ }
+
+ public double insulinSoFar() {
+ return absoluteRate() * getRealDuration() / 60d;
+ }
+
+ public IobTotal iobCalc(long time) {
+ IobTotal result = new IobTotal(time);
+ Profile profile = MainApp.getConfigBuilder().getProfile(time);
+ InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
+
+ if (profile == null)
+ return result;
+
+ int realDuration = getDurationToTime(time);
+
+ if (realDuration > 0) {
+ Double dia_ago = time - profile.getDia() * 60 * 60 * 1000;
+ int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
+ double spacing = realDuration / aboutFiveMinIntervals;
+
+ for (Long j = 0L; j < aboutFiveMinIntervals; j++) {
+ // find middle of the interval
+ Long calcdate = (long) (date + j * spacing * 60 * 1000 + 0.5d * spacing * 60 * 1000);
+
+ if (calcdate > dia_ago && calcdate <= time) {
+ double tempBolusSize = absoluteRate() * spacing / 60d;
+
+ Treatment tempBolusPart = new Treatment(insulinInterface);
+ tempBolusPart.insulin = tempBolusSize;
+ tempBolusPart.date = calcdate;
+
+ Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, profile.getDia());
+ result.iob += aIOB.iobContrib;
+ result.activity += aIOB.activityContrib;
+ result.extendedBolusInsulin += tempBolusPart.insulin;
+ }
+ }
+ }
+ return result;
+ }
+
+ public int getRealDuration() {
+ return getDurationToTime(new Date().getTime());
+ }
+
+ private int getDurationToTime(long time) {
+ long endTime = Math.min(time, end());
+ long msecs = endTime - date;
+ return Math.round(msecs / 60f / 1000);
+ }
+
+ public int getPlannedRemainingMinutes() {
+ float remainingMin = (end() - new Date().getTime()) / 1000f / 60;
+ return (remainingMin < 0) ? 0 : Math.round(remainingMin);
+ }
+
+ public String toString() {
+ return "E " + DecimalFormatter.to2Decimal(absoluteRate()) + "U/h @" +
+ DateUtil.timeString(date) +
+ " " + getRealDuration() + "/" + durationInMinutes + "min";
+ }
+
+ public String toStringShort() {
+ return "E " + DecimalFormatter.to2Decimal(absoluteRate()) + "U/h ";
+ }
+
+ public String toStringMedium() {
+ return "E " + DecimalFormatter.to2Decimal(absoluteRate()) + "U/h ("
+ + getRealDuration() + "/" + durationInMinutes + ") ";
+ }
+
+ public String toStringTotal() {
+ return DecimalFormatter.to2Decimal(insulin) + "U ( " +
+ DecimalFormatter.to2Decimal(absoluteRate()) + " U/h )";
+ }
+
+ // -------- DataPointWithLabelInterface --------
+ @Override
+ public double getX() {
+ return date;
+ }
+
+ // default when no sgv around available
+ private double yValue = 0;
+
+
+ @Override
+ public double getY() {
+ return yValue;
+ }
+
+ @Override
+ public void setY(double y) {
+ yValue = y;
+ }
+
+ @Override
+ public String getLabel() {
+ return toStringTotal();
+ }
+
+ @Override
+ public long getDuration() {
+ return durationInMinutes * 60 * 1000L;
+ }
+
+ @Override
+ public PointsWithLabelGraphSeries.Shape getShape() {
+ return PointsWithLabelGraphSeries.Shape.EXTENDEDBOLUS;
+ }
+
+ @Override
+ public float getSize() {
+ return 10;
+ }
+
+ @Override
+ public int getColor() {
+ return Color.CYAN;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
new file mode 100644
index 0000000000..448f6cdd51
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
@@ -0,0 +1,202 @@
+package info.nightscout.androidaps.db;
+
+import android.graphics.Color;
+
+import com.j256.ormlite.field.DatabaseField;
+import com.j256.ormlite.table.DatabaseTable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Date;
+import java.util.Objects;
+
+import info.nightscout.androidaps.interfaces.Interval;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.utils.DateUtil;
+
+@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
+public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
+ private static Logger log = LoggerFactory.getLogger(ProfileSwitch.class);
+
+ @DatabaseField(id = true)
+ public long date;
+
+ @DatabaseField
+ public boolean isValid = true;
+
+ @DatabaseField
+ public int source = Source.NONE;
+ @DatabaseField
+ public String _id = null; // NS _id
+
+ @DatabaseField
+ public boolean isCPP = false; // CPP NS="CircadianPercentageProfile"
+ @DatabaseField
+ public int timeshift = 0; // CPP NS="timeshift"
+ @DatabaseField
+ public int percentage = 100; // CPP NS="percentage"
+
+ @DatabaseField
+ public String profileName = null;
+
+ @DatabaseField
+ public String profileJson = null;
+
+ @DatabaseField
+ public String profilePlugin = null; // NSProfilePlugin.class.getName();
+
+ @DatabaseField
+ public int durationInMinutes = 0;
+
+ public boolean isEqual(ProfileSwitch other) {
+ if (date != other.date) {
+ return false;
+ }
+ if (durationInMinutes != other.durationInMinutes)
+ return false;
+ if (percentage != other.percentage)
+ return false;
+ if (timeshift != other.timeshift)
+ return false;
+ if (isCPP != other.isCPP)
+ return false;
+ if (!Objects.equals(_id, other._id))
+ return false;
+ if (!Objects.equals(profilePlugin, other.profilePlugin))
+ return false;
+ if (!Objects.equals(profileJson, other.profileJson))
+ return false;
+ if (!Objects.equals(profileName, other.profileName))
+ return false;
+ return true;
+ }
+
+ public void copyFrom(ProfileSwitch t) {
+ date = t.date;
+ _id = t._id;
+ durationInMinutes = t.durationInMinutes;
+ percentage = t.percentage;
+ timeshift = t.timeshift;
+ isCPP = t.isCPP;
+ profilePlugin = t.profilePlugin;
+ profileJson = t.profileJson;
+ profileName = t.profileName;
+ }
+
+ // -------- Interval interface ---------
+
+ Long cuttedEnd = null;
+
+ public long durationInMsec() {
+ return durationInMinutes * 60 * 1000L;
+ }
+
+ public long start() {
+ return date;
+ }
+
+ // planned end time at time of creation
+ public long originalEnd() {
+ return date + durationInMinutes * 60 * 1000L;
+ }
+
+ // end time after cut
+ public long end() {
+ if (cuttedEnd != null)
+ return cuttedEnd;
+ return originalEnd();
+ }
+
+ public void cutEndTo(long end) {
+ cuttedEnd = end;
+ }
+
+ public boolean match(long time) {
+ if (start() <= time && end() >= time)
+ return true;
+ return false;
+ }
+
+ public boolean before(long time) {
+ if (end() < time)
+ return true;
+ return false;
+ }
+
+ public boolean after(long time) {
+ if (start() > time)
+ return true;
+ return false;
+ }
+
+ @Override
+ public boolean isInProgress() {
+ return match(new Date().getTime());
+ }
+
+ @Override
+ public boolean isEndingEvent() {
+ return durationInMinutes == 0;
+ }
+
+ // -------- Interval interface end ---------
+
+ // ----------------- DataPointInterface --------------------
+ @Override
+ public double getX() {
+ return date;
+ }
+
+ // default when no sgv around available
+ private double yValue = 0;
+
+ @Override
+ public double getY() {
+ return yValue;
+ }
+
+ @Override
+ public void setY(double y) {
+ yValue = y;
+ }
+
+ @Override
+ public String getLabel() {
+ return profileName;
+ }
+
+ @Override
+ public long getDuration() {
+ return 0;
+ }
+
+ @Override
+ public PointsWithLabelGraphSeries.Shape getShape() {
+ return PointsWithLabelGraphSeries.Shape.PROFILE;
+ }
+
+ @Override
+ public float getSize() {
+ return 10;
+ }
+
+ @Override
+ public int getColor() {
+ return Color.CYAN;
+ }
+
+ public String log() {
+ return "ProfileSwitch{" +
+ "date=" + date +
+ "date=" + DateUtil.dateAndTimeString(date) +
+ ", isValid=" + isValid +
+ ", duration=" + durationInMinutes +
+ ", profileName=" + profileName +
+ ", percentage=" + percentage +
+ ", timeshift=" + timeshift +
+ '}';
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/Source.java b/app/src/main/java/info/nightscout/androidaps/db/Source.java
new file mode 100644
index 0000000000..c126794769
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/Source.java
@@ -0,0 +1,24 @@
+package info.nightscout.androidaps.db;
+
+/**
+ * Created by mike on 21.05.2017.
+ */
+
+public class Source {
+ public final static int NONE = 0;
+ public final static int PUMP = 1; // Pump history
+ public final static int NIGHTSCOUT = 2; // created in NS
+ public final static int USER = 3; // created by user or driver not using history
+
+ public static String getString(int source) {
+ switch (source) {
+ case PUMP:
+ return "PUMP";
+ case NIGHTSCOUT:
+ return "NIGHTSCOUT";
+ case USER:
+ return "USER";
+ }
+ return "NONE";
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java
deleted file mode 100644
index 149d188b7c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java
+++ /dev/null
@@ -1,230 +0,0 @@
-package info.nightscout.androidaps.db;
-
-import com.j256.ormlite.field.DatabaseField;
-import com.j256.ormlite.table.DatabaseTable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Date;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.data.Iob;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-
-@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPBASALS)
-public class TempBasal {
- private static Logger log = LoggerFactory.getLogger(TempBasal.class);
-
- public long getTimeIndex() {
- return timeStart.getTime();
- }
-
- public void setTimeIndex(long timeIndex) {
- this.timeIndex = timeIndex;
- }
-
- @DatabaseField(id = true, useGetSet = true)
- public long timeIndex;
-
- @DatabaseField
- public Date timeStart;
-
- @DatabaseField
- public Date timeEnd;
-
- @DatabaseField
- public int percent; // In % of current basal. 100% == current basal
-
- @DatabaseField
- public Double absolute; // Absolute value in U
-
- @DatabaseField
- public int duration; // in minutes
-
- @DatabaseField
- public boolean isExtended = false; // true if set as extended bolus
-
- @DatabaseField
- public boolean isAbsolute = false; // true if if set as absolute value in U
-
-
- public IobTotal iobCalc(Date time) {
- IobTotal result = new IobTotal(time.getTime());
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
-
- if (profile == null)
- return result;
-
- Double basalRate = profile.getBasal(profile.secondsFromMidnight(time));
-
- if (basalRate == null)
- return result;
-
- int realDuration = getRealDuration();
-
- if (realDuration > 0) {
- Double netBasalRate = 0d;
- Double tempBolusSize = 0.05;
-
- if (isExtended) {
- netBasalRate = this.absolute;
- } else {
- if (this.isAbsolute) {
- netBasalRate = this.absolute - basalRate;
- } else {
- netBasalRate = (this.percent - 100) / 100d * basalRate;
- }
- }
-
- result.netRatio = netBasalRate;
- Double netBasalAmount = Math.round(netBasalRate * realDuration * 10 / 6) / 100d;
- result.netInsulin = netBasalAmount;
- if (netBasalAmount < 0.1) {
- tempBolusSize = 0.01;
- }
- if (netBasalRate < 0) {
- tempBolusSize = -tempBolusSize;
- }
- Long tempBolusCount = Math.round(netBasalAmount / tempBolusSize);
- if (tempBolusCount > 0) {
- Long tempBolusSpacing = realDuration / tempBolusCount;
- for (Long j = 0l; j < tempBolusCount; j++) {
- Treatment tempBolusPart = new Treatment();
- tempBolusPart.insulin = tempBolusSize;
- Long date = this.timeStart.getTime() + j * tempBolusSpacing * 60 * 1000;
- tempBolusPart.created_at = new Date(date);
-
- Iob aIOB = tempBolusPart.iobCalc(time, profile.getDia());
- result.basaliob += aIOB.iobContrib;
- result.activity += aIOB.activityContrib;
- Double dia_ago = time.getTime() - profile.getDia() * 60 * 60 * 1000;
- if (date > dia_ago && date <= time.getTime()) {
- result.netbasalinsulin += tempBolusPart.insulin;
- if (tempBolusPart.insulin > 0) {
- result.hightempinsulin += tempBolusPart.insulin;
- }
- }
- }
- }
- }
- return result;
- }
-
- // Determine end of basal
- public Date getTimeEnd() {
- Date tempBasalTimePlannedEnd = getPlannedTimeEnd();
- Date now = new Date();
-
- if (timeEnd != null && timeEnd.getTime() < tempBasalTimePlannedEnd.getTime()) {
- tempBasalTimePlannedEnd = timeEnd;
- }
-
- if (now.getTime() < tempBasalTimePlannedEnd.getTime())
- tempBasalTimePlannedEnd = now;
-
- return tempBasalTimePlannedEnd;
- }
-
- public Date getPlannedTimeEnd() {
- return new Date(timeStart.getTime() + 60 * 1_000 * duration);
- }
-
- public int getRealDuration() {
- Long msecs = getTimeEnd().getTime() - timeStart.getTime();
- return Math.round(msecs / 60f / 1000);
- }
-
- public long getMillisecondsFromStart() {
- return new Date().getTime() - timeStart.getTime();
- }
-
- public int getPlannedRemainingMinutes() {
- if (timeEnd != null) return 0;
- float remainingMin = (getPlannedTimeEnd().getTime() - new Date().getTime()) / 1000f / 60;
- return (remainingMin < 0) ? 0 : Math.round(remainingMin);
- }
-
- public boolean isInProgress() {
- return isInProgress(new Date());
- }
-
- public double tempBasalConvertedToAbsolute(Date time) {
- if (isExtended) {
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- double absval = profile.getBasal(NSProfile.secondsFromMidnight(time)) + absolute;
- return absval;
- } else {
- if (isAbsolute) return absolute;
- else {
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- double absval = profile.getBasal(NSProfile.secondsFromMidnight(time)) * percent / 100;
- return absval;
- }
- }
- }
-
- public boolean isInProgress(Date time) {
- if (timeStart.getTime() > time.getTime()) return false; // in the future
- if (timeEnd == null) { // open end
- if (timeStart.getTime() < time.getTime() && getPlannedTimeEnd().getTime() > time.getTime())
- return true; // in interval
- return false;
- }
- // closed end
- if (timeStart.getTime() < time.getTime() && timeEnd.getTime() > time.getTime()) return true; // in interval
- return false;
- }
-
- public String log() {
- return "TempBasal{" +
- "timeIndex=" + timeIndex +
- ", timeStart=" + timeStart +
- ", timeEnd=" + timeEnd +
- ", percent=" + percent +
- ", absolute=" + absolute +
- ", duration=" + duration +
- ", isAbsolute=" + isAbsolute +
- ", isExtended=" + isExtended +
- '}';
- }
-
- public String toString() {
- String extended = isExtended ? "E " : "";
-
- if (isAbsolute) {
- return extended + DecimalFormatter.to2Decimal(absolute) + "U/h @" +
- DateUtil.timeString(timeStart) +
- " " + getRealDuration() + "/" + duration + "min";
- } else { // percent
- return percent + "% @" +
- DateUtil.timeString(timeStart) +
- " " + getRealDuration() + "/" + duration + "min";
- }
- }
-
- public String toStringShort() {
- String extended = isExtended ? "E" : "";
-
- if (isAbsolute) {
- return extended + DecimalFormatter.to2Decimal(absolute) + "U/h ";
- } else { // percent
- return percent + "% ";
- }
- }
-
- public String toStringMedium() {
- String extended = isExtended ? "E" : "";
-
- if (isAbsolute) {
- return extended + DecimalFormatter.to2Decimal(absolute) + "U/h ("
- + getRealDuration() + "/" + duration + ") ";
- } else { // percent
- return percent + "% (" + getRealDuration() + "/" + duration + ") ";
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
index 051a1d3d40..7afe994437 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
@@ -7,29 +7,27 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
+import java.util.Objects;
import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
+import info.nightscout.androidaps.interfaces.Interval;
+import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS)
-public class TempTarget {
+public class TempTarget implements Interval {
private static Logger log = LoggerFactory.getLogger(TempTarget.class);
- public long getTimeIndex() {
- return timeStart.getTime() - timeStart.getTime() % 1000;
- }
-
- public void setTimeIndex(long timeIndex) {
- this.timeIndex = timeIndex;
- }
-
- @DatabaseField(id = true, useGetSet = true)
- public long timeIndex;
+ @DatabaseField(id = true)
+ public long date;
@DatabaseField
- public Date timeStart;
+ public boolean isValid = true;
+
+ @DatabaseField
+ public int source = Source.NONE;
+ @DatabaseField
+ public String _id = null; // NS _id
@DatabaseField
public double low; // in mgdl
@@ -41,15 +39,92 @@ public class TempTarget {
public String reason;
@DatabaseField
- public int duration; // in minutes
+ public int durationInMinutes;
- @DatabaseField
- public String _id; // NS _id
-
- public Date getPlannedTimeEnd() {
- return new Date(timeStart.getTime() + 60 * 1_000 * duration);
+ public boolean isEqual(TempTarget other) {
+ if (date != other.date) {
+ return false;
+ }
+ if (durationInMinutes != other.durationInMinutes)
+ return false;
+ if (low != other.low)
+ return false;
+ if (high != other.high)
+ return false;
+ if (reason != other.reason)
+ return false;
+ if (!Objects.equals(_id, other._id))
+ return false;
+ return true;
}
+ public void copyFrom(TempTarget t) {
+ date = t.date;
+ _id = t._id;
+ durationInMinutes = t.durationInMinutes;
+ low = t.low;
+ high = t.high;
+ reason = t.reason;
+ }
+
+ // -------- Interval interface ---------
+
+ Long cuttedEnd = null;
+
+ public long durationInMsec() {
+ return durationInMinutes * 60 * 1000L;
+ }
+
+ public long start() {
+ return date;
+ }
+
+ // planned end time at time of creation
+ public long originalEnd() {
+ return date + durationInMinutes * 60 * 1000L;
+ }
+
+ // end time after cut
+ public long end() {
+ if (cuttedEnd != null)
+ return cuttedEnd;
+ return originalEnd();
+ }
+
+ public void cutEndTo(long end) {
+ cuttedEnd = end;
+ }
+
+ public boolean match(long time) {
+ if (start() <= time && end() >= time)
+ return true;
+ return false;
+ }
+
+ public boolean before(long time) {
+ if (end() < time)
+ return true;
+ return false;
+ }
+
+ public boolean after(long time) {
+ if (start() > time)
+ return true;
+ return false;
+ }
+
+ @Override
+ public boolean isInProgress() {
+ return match(new Date().getTime());
+ }
+
+ @Override
+ public boolean isEndingEvent() {
+ return durationInMinutes == 0;
+ }
+
+ // -------- Interval interface end ---------
+
public String lowValueToUnitsToString(String units) {
if (units.equals(Constants.MGDL)) return DecimalFormatter.to0Decimal(low);
else return DecimalFormatter.to1Decimal(low * Constants.MGDL_TO_MMOLL);
@@ -60,15 +135,12 @@ public class TempTarget {
else return DecimalFormatter.to1Decimal(low * Constants.MGDL_TO_MMOLL);
}
- public boolean isInProgress() {
- return ((TempTargetRangePlugin) MainApp.getSpecificPlugin(TempTargetRangePlugin.class)).getTempTargetInProgress(new Date().getTime()) == this;
- }
-
- public String log() {
- return "TempTarget{" +
- "timeIndex=" + timeIndex +
- ", timeStart=" + timeStart +
- ", duration=" + duration +
+ public String toString() {
+ return "TemporaryTarget{" +
+ "date=" + date +
+ "date=" + DateUtil.dateAndTimeString(date) +
+ ", isValid=" + isValid +
+ ", duration=" + durationInMinutes +
", reason=" + reason +
", low=" + low +
", high=" + high +
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
new file mode 100644
index 0000000000..4bf668411d
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
@@ -0,0 +1,289 @@
+package info.nightscout.androidaps.db;
+
+import com.j256.ormlite.field.DatabaseField;
+import com.j256.ormlite.table.DatabaseTable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Date;
+import java.util.Objects;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
+import info.nightscout.androidaps.interfaces.Interval;
+import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.DecimalFormatter;
+
+/**
+ * Created by mike on 21.05.2017.
+ */
+
+@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS)
+public class TemporaryBasal implements Interval {
+ private static Logger log = LoggerFactory.getLogger(TemporaryBasal.class);
+
+ @DatabaseField(id = true)
+ public long date;
+
+ @DatabaseField
+ public boolean isValid = true;
+
+ @DatabaseField(index = true)
+ public long pumpId = 0;
+
+ @DatabaseField
+ public int source = Source.NONE;
+ @DatabaseField
+ public String _id = null; // NS _id
+
+ @DatabaseField
+ public int durationInMinutes = 0; // duration == 0 means end of temp basal
+ @DatabaseField
+ public boolean isAbsolute = false;
+ @DatabaseField
+ public int percentRate = 0;
+ @DatabaseField
+ public double absoluteRate = 0d;
+
+ public TemporaryBasal() {
+ }
+
+ public TemporaryBasal(long date) {
+ this.date = date;
+ }
+
+ public TemporaryBasal(ExtendedBolus extendedBolus) {
+ double basal = MainApp.getConfigBuilder().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
+ this.date = extendedBolus.date;
+ this.isValid = extendedBolus.isValid;
+ this.source = extendedBolus.source;
+ this._id = extendedBolus._id;
+ this.durationInMinutes = extendedBolus.durationInMinutes;
+ this.isAbsolute = true;
+ this.absoluteRate = basal + extendedBolus.absoluteRate();
+ }
+
+ public TemporaryBasal clone() {
+ TemporaryBasal t = new TemporaryBasal();
+ t.date = date;
+ t.isValid = isValid;
+ t.source = source;
+ t._id = _id;
+ t.pumpId = pumpId;
+ t.durationInMinutes = durationInMinutes;
+ t.isAbsolute = isAbsolute;
+ t.percentRate = percentRate;
+ t.absoluteRate = absoluteRate;
+ return t;
+ }
+
+ public boolean isEqual(TemporaryBasal other) {
+ if (date != other.date) {
+ return false;
+ }
+ if (durationInMinutes != other.durationInMinutes)
+ return false;
+ if (isAbsolute != other.isAbsolute)
+ return false;
+ if (percentRate != other.percentRate)
+ return false;
+ if (absoluteRate != other.absoluteRate)
+ return false;
+ if (pumpId != other.pumpId)
+ return false;
+ if (!Objects.equals(_id, other._id))
+ return false;
+ return true;
+ }
+
+ public void copyFrom(TemporaryBasal t) {
+ date = t.date;
+ _id = t._id;
+ durationInMinutes = t.durationInMinutes;
+ isAbsolute = t.isAbsolute;
+ percentRate = t.percentRate;
+ absoluteRate = t.absoluteRate;
+ pumpId = t.pumpId;
+ }
+
+ // -------- Interval interface ---------
+
+ Long cuttedEnd = null;
+
+ public long durationInMsec() {
+ return durationInMinutes * 60 * 1000L;
+ }
+
+ public long start() {
+ return date;
+ }
+
+ // planned end time at time of creation
+ public long originalEnd() {
+ return date + durationInMinutes * 60 * 1000L;
+ }
+
+ // end time after cut
+ public long end() {
+ if (cuttedEnd != null)
+ return cuttedEnd;
+ return originalEnd();
+ }
+
+ public void cutEndTo(long end) {
+ cuttedEnd = end;
+ }
+
+ public boolean match(long time) {
+ if (start() <= time && end() >= time)
+ return true;
+ return false;
+ }
+
+ public boolean before(long time) {
+ if (end() < time)
+ return true;
+ return false;
+ }
+
+ public boolean after(long time) {
+ if (start() > time)
+ return true;
+ return false;
+ }
+
+ @Override
+ public boolean isInProgress() {
+ return match(new Date().getTime());
+ }
+
+ @Override
+ public boolean isEndingEvent() {
+ return durationInMinutes == 0;
+ }
+
+ // -------- Interval interface end ---------
+
+ public IobTotal iobCalc(long time) {
+ IobTotal result = new IobTotal(time);
+ Profile profile = MainApp.getConfigBuilder().getProfile(time);
+ InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
+
+ int realDuration = getDurationToTime(time);
+ Double netBasalAmount = 0d;
+
+ if (realDuration > 0) {
+ Double netBasalRate = 0d;
+
+ Double dia_ago = time - profile.getDia() * 60 * 60 * 1000;
+ int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
+ double tempBolusSpacing = realDuration / aboutFiveMinIntervals;
+
+ for (Long j = 0L; j < aboutFiveMinIntervals; j++) {
+ // find middle of the interval
+ Long calcdate = (long) (date + j * tempBolusSpacing * 60 * 1000 + 0.5d * tempBolusSpacing * 60 * 1000);
+
+ Double basalRate = profile.getBasal(calcdate);
+
+ if (basalRate == null)
+ continue;
+ if (isAbsolute) {
+ netBasalRate = absoluteRate - basalRate;
+ } else {
+ netBasalRate = (percentRate - 100) / 100d * basalRate;
+ }
+
+ if (calcdate > dia_ago && calcdate <= time) {
+ double tempBolusSize = netBasalRate * tempBolusSpacing / 60d;
+ netBasalAmount += tempBolusSize;
+
+ Treatment tempBolusPart = new Treatment(insulinInterface);
+ tempBolusPart.insulin = tempBolusSize;
+ tempBolusPart.date = calcdate;
+
+ Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, profile.getDia());
+ result.basaliob += aIOB.iobContrib;
+ result.activity += aIOB.activityContrib;
+ result.netbasalinsulin += tempBolusPart.insulin;
+ if (tempBolusPart.insulin > 0) {
+ result.hightempinsulin += tempBolusPart.insulin;
+ }
+ }
+ result.netRatio = netBasalRate; // ratio at the end of interval
+ }
+ }
+ result.netInsulin = netBasalAmount;
+ return result;
+ }
+
+ public int getRealDuration() {
+ return getDurationToTime(new Date().getTime());
+ }
+
+ private int getDurationToTime(long time) {
+ long endTime = Math.min(time, end());
+ long msecs = endTime - date;
+ return Math.round(msecs / 60f / 1000);
+ }
+
+ public int getPlannedRemainingMinutes() {
+ float remainingMin = (end() - new Date().getTime()) / 1000f / 60;
+ return (remainingMin < 0) ? 0 : Math.round(remainingMin);
+ }
+
+ public double tempBasalConvertedToAbsolute(long time) {
+ if (isAbsolute) return absoluteRate;
+ else {
+ return MainApp.getConfigBuilder().getProfile(time).getBasal(time) * percentRate / 100;
+ }
+ }
+
+ public String toString() {
+ return "TemporaryBasal{" +
+ "date=" + date +
+ ", date=" + DateUtil.dateAndTimeString(date) +
+ ", isValid=" + isValid +
+ ", pumpId=" + pumpId +
+ ", _id=" + _id +
+ ", percentRate=" + percentRate +
+ ", absoluteRate=" + absoluteRate +
+ ", durationInMinutes=" + durationInMinutes +
+ ", isAbsolute=" + isAbsolute +
+ '}';
+ }
+
+ public String toStringFull() {
+ if (isAbsolute) {
+ return DecimalFormatter.to2Decimal(absoluteRate) + "U/h @" +
+ DateUtil.timeString(date) +
+ " " + getRealDuration() + "/" + durationInMinutes + "min";
+ } else { // percent
+ return percentRate + "% @" +
+ DateUtil.timeString(date) +
+ " " + getRealDuration() + "/" + durationInMinutes + "min";
+ }
+ }
+
+ public String toStringShort() {
+ if (isAbsolute) {
+ return DecimalFormatter.to2Decimal(absoluteRate) + "U/h ";
+ } else { // percent
+ return percentRate + "% ";
+ }
+ }
+
+ public String toStringMedium() {
+ if (isAbsolute) {
+ return DecimalFormatter.to2Decimal(absoluteRate) + "U/h ("
+ + getRealDuration() + "/" + durationInMinutes + ") ";
+ } else { // percent
+ return percentRate + "% (" + getRealDuration() + "/" + durationInMinutes + ") ";
+ }
+ }
+
+}
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 a8afacd767..e386a195b8 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java
@@ -1,21 +1,25 @@
package info.nightscout.androidaps.db;
+import android.graphics.Color;
+
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
-import org.json.JSONException;
-import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
+import java.util.Objects;
+import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@@ -23,85 +27,102 @@ import info.nightscout.utils.DecimalFormatter;
public class Treatment implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(Treatment.class);
- public long getTimeIndex() {
- return created_at.getTime();
- }
+ @DatabaseField(id = true)
+ public long date;
- public void setTimeIndex(long timeIndex) {
- this.timeIndex = timeIndex;
- }
+ @DatabaseField
+ public boolean isValid = true;
- @DatabaseField(id = true, useGetSet = true)
- public long timeIndex;
+ @DatabaseField(index = true)
+ public long pumpId = 0;
+ @DatabaseField
+ public int source = Source.NONE;
@DatabaseField
public String _id;
@DatabaseField
- public Date created_at;
-
+ public double insulin = 0d;
@DatabaseField
- public Double insulin = 0d;
-
- @DatabaseField
- public Double carbs = 0d;
-
+ public double carbs = 0d;
@DatabaseField
public boolean mealBolus = true; // true for meal bolus , false for correction bolus
- public void copyFrom(Treatment t) {
- this._id = t._id;
- this.created_at = t.created_at;
- this.insulin = t.insulin;
- this.carbs = t.carbs;
- this.mealBolus = t.mealBolus;
+ @DatabaseField
+ public int insulinInterfaceID = InsulinInterface.FASTACTINGINSULIN;
+ @DatabaseField
+ public double dia = Constants.defaultDIA;
+
+ public Treatment() {
}
- public Iob iobCalc(Date time, Double dia) {
- Iob result = new Iob();
+ public Treatment(long date) {
+ this.date = date;
+ }
- Double scaleFactor = 3.0 / dia;
- Double peak = 75d;
- Double end = 180d;
-
- if (this.insulin != 0d) {
- Long bolusTime = this.created_at.getTime();
- Double minAgo = scaleFactor * (time.getTime() - bolusTime) / 1000d / 60d;
-
- if (minAgo < peak) {
- Double x1 = minAgo / 5d + 1;
- result.iobContrib = this.insulin * (1 - 0.001852 * x1 * x1 + 0.001852 * x1);
- // units: BG (mg/dL) = (BG/U) * U insulin * scalar
- result.activityContrib = this.insulin * (2 / dia / 60 / peak) * minAgo;
-
- } else if (minAgo < end) {
- Double x2 = (minAgo - 75) / 5;
- result.iobContrib = this.insulin * (0.001323 * x2 * x2 - 0.054233 * x2 + 0.55556);
- result.activityContrib = this.insulin * (2 / dia / 60 - (minAgo - peak) * 2 / dia / 60 / (60 * 3 - peak));
- }
- }
- return result;
+ public Treatment(InsulinInterface insulin) {
+ insulinInterfaceID = insulin.getId();
+ dia = insulin.getDia();
}
public long getMillisecondsFromStart() {
- return new Date().getTime() - created_at.getTime();
+ return new Date().getTime() - date;
}
- public String log() {
+ public String toString() {
return "Treatment{" +
- "timeIndex: " + timeIndex +
- ", _id: " + _id +
- ", insulin: " + insulin +
- ", carbs: " + carbs +
- ", mealBolus: " + mealBolus +
- ", created_at: " +
+ "date= " + date +
+ ", date= " + DateUtil.dateAndTimeString(date) +
+ ", isValid= " + isValid +
+ ", _id= " + _id +
+ ", pumpId= " + pumpId +
+ ", insulin= " + insulin +
+ ", carbs= " + carbs +
+ ", mealBolus= " + mealBolus +
"}";
}
- // DataPointInterface
+ public boolean isDataChanging(Treatment other) {
+ if (date != other.date) {
+ return true;
+ }
+ if (insulin != other.insulin)
+ return true;
+ if (carbs != other.carbs)
+ return true;
+ return false;
+ }
+
+ public boolean isEqual(Treatment other) {
+ if (date != other.date) {
+ return false;
+ }
+ if (insulin != other.insulin)
+ return false;
+ if (carbs != other.carbs)
+ return false;
+ if (mealBolus != other.mealBolus)
+ return false;
+ if (pumpId != other.pumpId)
+ return false;
+ if (!Objects.equals(_id, other._id))
+ return false;
+ return true;
+ }
+
+ public void copyFrom(Treatment t) {
+ date = t.date;
+ _id = t._id;
+ insulin = t.insulin;
+ carbs = t.carbs;
+ mealBolus = t.mealBolus;
+ pumpId = t.pumpId;
+ }
+
+ // ----------------- DataPointInterface --------------------
@Override
public double getX() {
- return timeIndex;
+ return date;
}
// default when no sgv around available
@@ -117,36 +138,42 @@ public class Treatment implements DataPointWithLabelInterface {
String label = "";
if (insulin > 0) label += DecimalFormatter.to2Decimal(insulin) + "U";
if (carbs > 0)
- label += (label.equals("") ? "" : " ") + DecimalFormatter.to0Decimal(carbs) + "g";
+ label += "~" + DecimalFormatter.to0Decimal(carbs) + "g";
return label;
}
- public void setYValue(List bgReadingsArray) {
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- if (profile == null) return;
- for (int r = bgReadingsArray.size() - 1; r >= 0; r--) {
- BgReading reading = bgReadingsArray.get(r);
- if (reading.timeIndex > timeIndex) continue;
- yValue = NSProfile.fromMgdlToUnits(reading.value, profile.getUnits());
- break;
- }
+ @Override
+ public long getDuration() {
+ return 0;
}
- public void sendToNSClient() {
- JSONObject data = new JSONObject();
- try {
- if (mealBolus)
- data.put("eventType", "Meal Bolus");
- else
- data.put("eventType", "Correction Bolus");
- if (insulin != 0d) data.put("insulin", insulin);
- if (carbs != 0d) data.put("carbs", carbs.intValue());
- data.put("created_at", DateUtil.toISOString(created_at));
- data.put("timeIndex", timeIndex);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- ConfigBuilderPlugin.uploadCareportalEntryToNS(data);
+ @Override
+ public PointsWithLabelGraphSeries.Shape getShape() {
+ return PointsWithLabelGraphSeries.Shape.BOLUS;
}
+ @Override
+ public float getSize() {
+ return 10;
+ }
+
+ @Override
+ public int getColor() {
+ return Color.CYAN;
+ }
+
+ @Override
+ public void setY(double y) {
+ yValue = y;
+ }
+
+ // ----------------- DataPointInterface end --------------------
+
+ public Iob iobCalc(long time, double dia) {
+ InsulinInterface insulinInterface = MainApp.getInsulinIterfaceById(insulinInterfaceID);
+ if (insulinInterface == null)
+ insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
+
+ return insulinInterface.iobCalcForTreatment(this, time, dia);
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java
new file mode 100644
index 0000000000..d86fe679fb
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 25.05.2017.
+ */
+
+public class EventCareportalEventChange {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java
new file mode 100644
index 0000000000..78dee60388
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 15.05.2017.
+ */
+
+public class EventExtendedBolusChange {
+}
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 3e270e8a1b..1309625b98 100644
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java
@@ -1,14 +1,7 @@
package info.nightscout.androidaps.events;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
-
/**
* Created by mike on 04.06.2016.
*/
public class EventNewBasalProfile {
- public NSProfile newNSProfile = null;
-
- public EventNewBasalProfile(NSProfile newProfile) {
- newNSProfile = newProfile;
- }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java
new file mode 100644
index 0000000000..476a571d70
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 02.06.2017.
+ */
+
+public class EventProfileSwitchChange {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java
new file mode 100644
index 0000000000..38b1b86186
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 29.05.2017.
+ */
+
+public class EventReloadTempBasalData {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java
new file mode 100644
index 0000000000..a488a9c7a4
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 29.05.2017.
+ */
+
+public class EventReloadTreatmentData {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java
new file mode 100644
index 0000000000..d0ef42d830
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 13.01.2017.
+ */
+
+public class EventTempTargetChange {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/FragmentBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/FragmentBase.java
deleted file mode 100644
index 79bfc75154..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/FragmentBase.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package info.nightscout.androidaps.interfaces;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public interface FragmentBase {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
new file mode 100644
index 0000000000..20c563dede
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
@@ -0,0 +1,21 @@
+package info.nightscout.androidaps.interfaces;
+
+import java.util.Date;
+
+import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.db.Treatment;
+
+/**
+ * Created by mike on 17.04.2017.
+ */
+
+public interface InsulinInterface {
+ final int FASTACTINGINSULIN = 0;
+ final int FASTACTINGINSULINPROLONGED = 1;
+
+ int getId();
+ String getFriendlyName();
+ String getComment();
+ double getDia();
+ public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia);
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java b/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java
new file mode 100644
index 0000000000..f3b4111642
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/Interval.java
@@ -0,0 +1,24 @@
+package info.nightscout.androidaps.interfaces;
+
+/**
+ * Created by mike on 21.05.2017.
+ */
+
+public interface Interval {
+ long durationInMsec();
+ long start();
+
+ // planned end time at time of creation
+ long originalEnd();
+
+ // end time after cut
+ long end();
+
+ void cutEndTo(long end);
+ boolean match(long time);
+ boolean before(long time);
+ boolean after(long time);
+
+ boolean isInProgress();
+ boolean isEndingEvent();
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
index 4442b83041..ba4faf4ba6 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
@@ -8,14 +8,15 @@ import java.util.Date;
public interface PluginBase {
int GENERAL = 1;
int TREATMENT = 2;
- int TEMPBASAL = 3;
+ //int TEMPBASAL = 3;
int PROFILE = 4;
int APS = 5;
int PUMP = 6;
int CONSTRAINTS = 7;
int LOOP = 8;
int BGSOURCE = 9;
- int LAST = 10; // keep always highest number
+ int INSULIN = 10;
+ int LAST = 11; // keep always highest number
int getType();
String getFragmentClass();
@@ -25,6 +26,8 @@ public interface PluginBase {
boolean isEnabled(int type);
boolean isVisibleInTabs(int type);
boolean canBeHidden(int type);
+ boolean hasFragment();
+ boolean showInList(int type);
void setFragmentEnabled(int type, boolean fragmentEnabled);
void setFragmentVisible(int type, boolean fragmentVisible);
}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java
index 0924723776..64fffa3e57 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java
@@ -2,12 +2,13 @@ package info.nightscout.androidaps.interfaces;
import android.support.annotation.Nullable;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.ProfileStore;
/**
* Created by mike on 14.06.2016.
*/
public interface ProfileInterface {
@Nullable
- NSProfile getProfile();
+ ProfileStore getProfile();
+ String getProfileName();
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
index 78a111d468..d37693d494 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
@@ -6,29 +6,29 @@ package info.nightscout.androidaps.interfaces;
public class PumpDescription {
public static final int NONE = 0;
- public static final int PERCENT = 1;
- public static final int ABSOLUTE = 2;
- public static final int EXTENDED = 4;
+ public static final int PERCENT = 0x01;
+ public static final int ABSOLUTE = 0x02;
public boolean isBolusCapable = true;
public double bolusStep = 0.1d;
public boolean isExtendedBolusCapable = true;
public double extendedBolusStep = 0.1d;
+ public double extendedBolusDurationStep = 30;
+ public double extendedBolusMaxDuration = 12 * 60;
public boolean isTempBasalCapable = true;
- public int lowTempBasalStyle = PERCENT;
- public int highTempBasalStyle = PERCENT;
- public double maxHighTempPercent = 200;
- public double maxHighTempAbsolute = 0; // zero = no limit
- public double lowTempPercentStep = 10;
- public double lowTempAbsoluteStep = 0.05d;
- public int lowTempPercentDuration = 30;
- public int lowTempAbsoluteDuration = 30;
- public double highTempPercentStep = 10;
- public double highTempAbsoluteStep = 0.05d;
- public int highTempPercentDuration = 30;
- public int highTempAbsoluteDuration = 30;
+ public int tempBasalStyle = PERCENT;
+
+ public int maxTempPercent = 200;
+ public int tempPercentStep = 10;
+
+ public double maxTempAbsolute = 10;
+ public double tempAbsoluteStep = 0.05d;
+
+ public int tempDurationStep = 60;
+ public int tempMaxDuration = 12 * 60;
+
public boolean isSetBasalProfileCapable = true;
public double basalStep = 0.01d;
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 6b6d8e856f..dbbdec2ce1 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
@@ -1,14 +1,12 @@
package info.nightscout.androidaps.interfaces;
-import android.content.Context;
-
import org.json.JSONObject;
import java.util.Date;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
-import info.nightscout.androidaps.db.TempBasal;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.Profile;
/**
* Created by mike on 04.06.2016.
@@ -19,27 +17,19 @@ public interface PumpInterface {
boolean isSuspended();
boolean isBusy();
- boolean isTempBasalInProgress();
- boolean isExtendedBoluslInProgress();
-
// Upload to pump new basal profile
int SUCCESS = 0;
int FAILED = 1;
int NOT_NEEDED = 2;
- int setNewBasalProfile(NSProfile profile);
- boolean isThisProfileSet(NSProfile profile);
+ int setNewBasalProfile(Profile profile);
+ boolean isThisProfileSet(Profile profile);
Date lastDataTime();
void refreshDataFromPump(String reason);
double getBaseBasalRate(); // base basal rate, not temp basal
- double getTempBasalAbsoluteRate();
- double getTempBasalRemainingMinutes();
- TempBasal getTempBasal(Date time);
- TempBasal getTempBasal();
- TempBasal getExtendedBolus();
- PumpEnactResult deliverTreatment(Double insulin, Integer carbs, Context context);
+ PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo);
void stopBolusDelivering();
PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes);
PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes);
@@ -56,4 +46,6 @@ public interface PumpInterface {
// Short info for SMS, Wear etc
String shortStatus(boolean veryShort);
+
+ boolean isFakingTempsByExtendedBoluses();
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java
deleted file mode 100644
index aa01d77adb..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package info.nightscout.androidaps.interfaces;
-
-import java.util.Date;
-
-import info.nightscout.androidaps.db.TempBasal;
-import info.nightscout.androidaps.data.IobTotal;
-
-/**
- * Created by mike on 14.06.2016.
- */
-public interface TempBasalsInterface {
- void updateTotalIOB();
- IobTotal getLastCalculation();
- IobTotal getCalculationToTime(long time);
-
- TempBasal getTempBasal (Date time);
- TempBasal getExtendedBolus (Date time);
-
- long oldestDataAvaialable();
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
index efb5f85fd0..d9e3742c70 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
@@ -2,18 +2,63 @@ package info.nightscout.androidaps.interfaces;
import java.util.List;
-import info.nightscout.androidaps.data.MealData;
-import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.MealData;
+import info.nightscout.androidaps.db.ExtendedBolus;
+import info.nightscout.androidaps.db.ProfileSwitch;
+import info.nightscout.androidaps.db.TempTarget;
+import info.nightscout.androidaps.db.TemporaryBasal;
+import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.data.OverlappingIntervals;
+import info.nightscout.androidaps.data.ProfileIntervals;
/**
* Created by mike on 14.06.2016.
*/
public interface TreatmentsInterface {
- void updateTotalIOB();
- IobTotal getLastCalculation();
- IobTotal getCalculationToTime(long time);
+ void updateTotalIOBTreatments();
+ void updateTotalIOBTempBasals();
+
+ IobTotal getLastCalculationTreatments();
+ IobTotal getCalculationToTimeTreatments(long time);
+ IobTotal getLastCalculationTempBasals();
+ IobTotal getCalculationToTimeTempBasals(long time);
+
MealData getMealData();
- List getTreatments();
+
+ List getTreatmentsFromHistory();
+ List getTreatments5MinBackFromHistory(long time);
+
+ // real basals (not faked by extended bolus)
+ boolean isInHistoryRealTempBasalInProgress();
+ TemporaryBasal getRealTempBasalFromHistory(long time);
+
+ boolean addToHistoryTempBasal(TemporaryBasal tempBasal);
+
+ // basal that can be faked by extended boluses
+ boolean isTempBasalInProgress();
+ TemporaryBasal getTempBasalFromHistory(long time);
+ double getTempBasalAbsoluteRateHistory();
+ double getTempBasalRemainingMinutesFromHistory();
+ OverlappingIntervals getTemporaryBasalsFromHistory();
+
+ boolean isInHistoryExtendedBoluslInProgress();
+ ExtendedBolus getExtendedBolusFromHistory(long time);
+ OverlappingIntervals getExtendedBolusesFromHistory();
+
+ boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus);
+
+ boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo);
+
+ TempTarget getTempTargetFromHistory(long time);
+ OverlappingIntervals getTempTargetsFromHistory();
+
+ ProfileSwitch getProfileSwitchFromHistory(long time);
+ ProfileIntervals getProfileSwitchesFromHistory();
+ void addToHistoryProfileSwitch(ProfileSwitch profileSwitch);
+
+ long oldestDataAvailable();
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
index c3ea14dc79..77e5b40250 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
@@ -3,6 +3,8 @@ package info.nightscout.androidaps.plugins.Actions;
import android.app.Activity;
import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
@@ -10,24 +12,32 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
+import com.crashlytics.android.answers.Answers;
+import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
+import java.util.Date;
+
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.db.ExtendedBolus;
+import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshGui;
-import info.nightscout.androidaps.interfaces.FragmentBase;
+import info.nightscout.androidaps.events.EventTempBasalChange;
+import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog;
-import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
-import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Actions.dialogs.NewExtendedBolusDialog;
import info.nightscout.androidaps.plugins.Actions.dialogs.NewTempBasalDialog;
+import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
+import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
+import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
/**
* A simple {@link Fragment} subclass.
*/
-public class ActionsFragment extends Fragment implements FragmentBase, View.OnClickListener {
+public class ActionsFragment extends Fragment implements View.OnClickListener {
static ActionsPlugin actionsPlugin = new ActionsPlugin();
@@ -38,10 +48,20 @@ public class ActionsFragment extends Fragment implements FragmentBase, View.OnCl
Button profileSwitch;
Button tempTarget;
Button extendedBolus;
+ Button extendedBolusCancel;
Button tempBasal;
Button fill;
+ private static Handler sHandler;
+ private static HandlerThread sHandlerThread;
+
public ActionsFragment() {
+ super();
+ if (sHandlerThread == null) {
+ sHandlerThread = new HandlerThread(ActionsFragment.class.getSimpleName());
+ sHandlerThread.start();
+ sHandler = new Handler(sHandlerThread.getLooper());
+ }
}
@@ -53,12 +73,14 @@ public class ActionsFragment extends Fragment implements FragmentBase, View.OnCl
profileSwitch = (Button) view.findViewById(R.id.actions_profileswitch);
tempTarget = (Button) view.findViewById(R.id.actions_temptarget);
extendedBolus = (Button) view.findViewById(R.id.actions_extendedbolus);
+ extendedBolusCancel = (Button) view.findViewById(R.id.actions_extendedbolus_cancel);
tempBasal = (Button) view.findViewById(R.id.actions_settempbasal);
fill = (Button) view.findViewById(R.id.actions_fill);
profileSwitch.setOnClickListener(this);
tempTarget.setOnClickListener(this);
extendedBolus.setOnClickListener(this);
+ extendedBolusCancel.setOnClickListener(this);
tempBasal.setOnClickListener(this);
fill.setOnClickListener(this);
@@ -88,21 +110,42 @@ public class ActionsFragment extends Fragment implements FragmentBase, View.OnCl
updateGUIIfVisible();
}
+ @Subscribe
+ public void onStatusEvent(final EventExtendedBolusChange ev) {
+ updateGUIIfVisible();
+ }
+
+ @Subscribe
+ public void onStatusEvent(final EventTempBasalChange ev) {
+ updateGUIIfVisible();
+ }
+
void updateGUIIfVisible() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
- if (!MainApp.getConfigBuilder().getPumpDescription().isSetBasalProfileCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended())
+ if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() == null)
+ return;
+ boolean allowProfileSwitch = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getProfileList().size() > 1;
+ if (!MainApp.getConfigBuilder().getPumpDescription().isSetBasalProfileCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || !allowProfileSwitch)
profileSwitch.setVisibility(View.GONE);
else
profileSwitch.setVisibility(View.VISIBLE);
- if (!MainApp.getConfigBuilder().getPumpDescription().isExtendedBolusCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended())
+ if (!MainApp.getConfigBuilder().getPumpDescription().isExtendedBolusCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress() || MainApp.getConfigBuilder().isFakingTempsByExtendedBoluses())
extendedBolus.setVisibility(View.GONE);
- else
+ else {
extendedBolus.setVisibility(View.VISIBLE);
- if (!MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended())
+ }
+ if (!MainApp.getConfigBuilder().getPumpDescription().isExtendedBolusCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || !MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress() || MainApp.getConfigBuilder().isFakingTempsByExtendedBoluses())
+ extendedBolusCancel.setVisibility(View.GONE);
+ else {
+ extendedBolusCancel.setVisibility(View.VISIBLE);
+ ExtendedBolus running = MainApp.getConfigBuilder().getExtendedBolusFromHistory(new Date().getTime());
+ extendedBolusCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + running.toString());
+ }
+ if (!MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || MainApp.getConfigBuilder().isTempBasalInProgress())
tempBasal.setVisibility(View.GONE);
else
tempBasal.setVisibility(View.VISIBLE);
@@ -122,6 +165,7 @@ public class ActionsFragment extends Fragment implements FragmentBase, View.OnCl
@Override
public void onClick(View view) {
FragmentManager manager = getFragmentManager();
+ final PumpInterface pump = MainApp.getConfigBuilder();
switch (view.getId()) {
case R.id.actions_profileswitch:
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
@@ -141,6 +185,17 @@ public class ActionsFragment extends Fragment implements FragmentBase, View.OnCl
NewExtendedBolusDialog newExtendedDialog = new NewExtendedBolusDialog();
newExtendedDialog.show(manager, "NewExtendedDialog");
break;
+ case R.id.actions_extendedbolus_cancel:
+ if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) {
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ pump.cancelExtendedBolus();
+ Answers.getInstance().logCustom(new CustomEvent("CancelExtended"));
+ }
+ });
+ }
+ break;
case R.id.actions_settempbasal:
NewTempBasalDialog newTempDialog = new NewTempBasalDialog();
newTempDialog.show(manager, "NewTempDialog");
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
index eedd0e4baf..d6ef13b29d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
@@ -54,6 +54,16 @@ public class ActionsPlugin implements PluginBase {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
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 8f50ac28e0..834206ca34 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
@@ -26,7 +26,9 @@ import java.text.DecimalFormat;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
+import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.DecimalFormatter;
@@ -159,7 +161,12 @@ public class FillDialog extends DialogFragment implements OnClickListener {
mHandler.post(new Runnable() {
@Override
public void run() {
- PumpEnactResult result = pump.deliverTreatment(finalInsulinAfterConstraints, 0, context, false);
+ DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
+ detailedBolusInfo.insulin = finalInsulinAfterConstraints;
+ detailedBolusInfo.context = context;
+ detailedBolusInfo.addToTreatments = false;
+ detailedBolusInfo.source = Source.NONE;
+ PumpEnactResult result = pump.deliverTreatment(detailedBolusInfo);
if (!result.success) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java
index ee726efb4d..c85d5c4540 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java
@@ -29,15 +29,8 @@ import info.nightscout.utils.SafeParse;
public class NewExtendedBolusDialog extends DialogFragment implements View.OnClickListener {
- Button okButton;
- EditText insulinEdit;
- RadioButton h05Radio;
- RadioButton h10Radio;
- RadioButton h20Radio;
- RadioButton h30Radio;
- RadioButton h40Radio;
-
PlusMinusEditText editInsulin;
+ PlusMinusEditText editDuration;
Handler mHandler;
public static HandlerThread mHandlerThread;
@@ -54,18 +47,16 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
getDialog().setTitle(getString(R.string.overview_extendedbolus_button));
View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false);
- okButton = (Button) view.findViewById(R.id.overview_newextendedbolus_okbutton);
- insulinEdit = (EditText) view.findViewById(R.id.overview_newextendedbolus_insulin);
- h05Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_05h);
- h10Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_1h);
- h20Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_2h);
- h30Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_3h);
- h40Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_4h);
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
editInsulin = new PlusMinusEditText(view, R.id.overview_newextendedbolus_insulin, R.id.overview_newextendedbolus_insulin_plus, R.id.overview_newextendedbolus_insulin_minus, 0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false);
- okButton.setOnClickListener(this);
+ double extendedDurationStep = MainApp.getConfigBuilder().getPumpDescription().extendedBolusDurationStep;
+ double extendedMaxDuration = MainApp.getConfigBuilder().getPumpDescription().extendedBolusMaxDuration;
+ editDuration = new PlusMinusEditText(view, R.id.overview_newextendedbolus_duration, R.id.overview_newextendedbolus_duration_plus, R.id.overview_newextendedbolus_duration_minus, extendedDurationStep, extendedDurationStep, extendedMaxDuration, extendedDurationStep, new DecimalFormat("0"), false);
+
+ view.findViewById(R.id.ok).setOnClickListener(this);
+ view.findViewById(R.id.cancel).setOnClickListener(this);
return view;
}
@@ -79,14 +70,10 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
@Override
public void onClick(View view) {
switch (view.getId()) {
- case R.id.overview_newextendedbolus_okbutton:
+ case R.id.ok:
try {
- Double insulin = SafeParse.stringToDouble(insulinEdit.getText().toString());
- int durationInMinutes = 30;
- if (h10Radio.isChecked()) durationInMinutes = 60;
- if (h20Radio.isChecked()) durationInMinutes = 120;
- if (h30Radio.isChecked()) durationInMinutes = 180;
- if (h40Radio.isChecked()) durationInMinutes = 240;
+ Double insulin = SafeParse.stringToDouble(editInsulin.getText());
+ int durationInMinutes = SafeParse.stringToInt(editDuration.getText());
String confirmMessage = getString(R.string.setextendedbolusquestion);
@@ -130,6 +117,10 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
} catch (Exception e) {
e.printStackTrace();
}
+ break;
+ case R.id.cancel:
+ dismiss();
+ break;
}
}
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 2d5a4580c4..51effccb86 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.Actions.dialogs;
+import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
@@ -10,45 +11,38 @@ import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
+import android.widget.RelativeLayout;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import java.text.DecimalFormat;
-import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult;
+import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SafeParse;
public class NewTempBasalDialog extends DialogFragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
- Button okButton;
- EditText basalPercentEdit;
- EditText basalAbsoluteEdit;
RadioButton percentRadio;
RadioButton absoluteRadio;
RadioGroup basalTypeRadioGroup;
- RadioButton h05Radio;
- RadioButton h10Radio;
- RadioButton h20Radio;
- RadioButton h30Radio;
- RadioButton h40Radio;
+ RelativeLayout typeSelectorLayout;
LinearLayout percentLayout;
LinearLayout absoluteLayout;
- PlusMinusEditText basalPercentPM;
- PlusMinusEditText basalAbsolutePM;
+ PlusMinusEditText basalPercent;
+ PlusMinusEditText basalAbsolute;
+ PlusMinusEditText duration;
Handler mHandler;
public static HandlerThread mHandlerThread;
@@ -65,31 +59,50 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
getDialog().setTitle(getString(R.string.overview_tempbasal_button));
View view = inflater.inflate(R.layout.overview_newtempbasal_dialog, container, false);
- okButton = (Button) view.findViewById(R.id.overview_newtempbasal_okbutton);
- basalPercentEdit = (EditText) view.findViewById(R.id.overview_newtempbasal_basalpercentinput);
- basalAbsoluteEdit = (EditText) view.findViewById(R.id.overview_newtempbasal_basalabsoluteinput);
+
percentLayout = (LinearLayout) view.findViewById(R.id.overview_newtempbasal_percent_layout);
absoluteLayout = (LinearLayout) view.findViewById(R.id.overview_newtempbasal_absolute_layout);
percentRadio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_percent_radio);
basalTypeRadioGroup = (RadioGroup) view.findViewById(R.id.overview_newtempbasal_radiogroup);
absoluteRadio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_absolute_radio);
- h05Radio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_05h);
- h10Radio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_1h);
- h20Radio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_2h);
- h30Radio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_3h);
- h40Radio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_4h);
+ typeSelectorLayout = (RelativeLayout) view.findViewById(R.id.overview_newtempbasal_typeselector_layout);
- Integer maxPercent = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalPercentOnlyForCheckLimit);
- basalPercentPM = new PlusMinusEditText(view, R.id.overview_newtempbasal_basalpercentinput, R.id.overview_newtempbasal_basalpercent_plus, R.id.overview_newtempbasal_basalpercent_minus, 100d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true);
+ PumpDescription pumpDescription = MainApp.getConfigBuilder().getPumpDescription();
- Double maxAbsolute = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalAbsoluteOnlyForCheckLimit);
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- Double currentBasal = 0d;
- if (profile != null) currentBasal = profile.getBasal(NSProfile.secondsFromMidnight());
- basalAbsolutePM = new PlusMinusEditText(view, R.id.overview_newtempbasal_basalabsoluteinput, R.id.overview_newtempbasal_basalabsolute_plus, R.id.overview_newtempbasal_basalabsolute_minus, currentBasal, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true);
+ basalPercent = new PlusMinusEditText(view, R.id.overview_newtempbasal_basalpercentinput, R.id.overview_newtempbasal_basalpercent_plus, R.id.overview_newtempbasal_basalpercent_minus,
+ 100d, 0d, (double) pumpDescription.maxTempPercent, (double) pumpDescription.tempPercentStep, new DecimalFormat("0"), true);
- absoluteLayout.setVisibility(View.GONE);
- okButton.setOnClickListener(this);
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ Double currentBasal = profile.getBasal();
+ basalAbsolute = new PlusMinusEditText(view, R.id.overview_newtempbasal_basalabsoluteinput, R.id.overview_newtempbasal_basalabsolute_plus, R.id.overview_newtempbasal_basalabsolute_minus,
+ currentBasal, 0d, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, new DecimalFormat("0.00"), true);
+
+ double tempDurationStep = MainApp.getConfigBuilder().getPumpDescription().tempDurationStep;
+ double tempMaxDuration = MainApp.getConfigBuilder().getPumpDescription().tempMaxDuration;
+ duration = new PlusMinusEditText(view, R.id.overview_newtempbasal_duration, R.id.overview_newtempbasal_duration_plus, R.id.overview_newtempbasal_duration_minus,
+ tempDurationStep, tempDurationStep, tempMaxDuration, tempDurationStep, new DecimalFormat("0"), false);
+
+ if ((pumpDescription.tempBasalStyle & PumpDescription.PERCENT) == PumpDescription.PERCENT && (pumpDescription.tempBasalStyle & PumpDescription.ABSOLUTE) == PumpDescription.ABSOLUTE) {
+ // Both allowed
+ typeSelectorLayout.setVisibility(View.VISIBLE);
+ } else {
+ typeSelectorLayout.setVisibility(View.GONE);
+ }
+
+ if ((pumpDescription.tempBasalStyle & PumpDescription.PERCENT) == PumpDescription.PERCENT) {
+ percentRadio.setChecked(true);
+ absoluteRadio.setChecked(false);
+ percentLayout.setVisibility(View.VISIBLE);
+ absoluteLayout.setVisibility(View.GONE);
+ } else if ((pumpDescription.tempBasalStyle & PumpDescription.ABSOLUTE) == PumpDescription.ABSOLUTE) {
+ percentRadio.setChecked(false);
+ absoluteRadio.setChecked(true);
+ percentLayout.setVisibility(View.GONE);
+ absoluteLayout.setVisibility(View.VISIBLE);
+ }
+
+ view.findViewById(R.id.ok).setOnClickListener(this);
+ view.findViewById(R.id.cancel).setOnClickListener(this);
basalTypeRadioGroup.setOnCheckedChangeListener(this);
return view;
}
@@ -104,36 +117,32 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
@Override
public void onClick(View view) {
switch (view.getId()) {
- case R.id.overview_newtempbasal_okbutton:
+ case R.id.ok:
try {
- int basalPercent = 0;
- Double basalAbsolute = 0d;
+ int percent = 0;
+ Double absolute = 0d;
final boolean setAsPercent = percentRadio.isChecked();
- int durationInMinutes = 30;
- if (h10Radio.isChecked()) durationInMinutes = 60;
- if (h20Radio.isChecked()) durationInMinutes = 120;
- if (h30Radio.isChecked()) durationInMinutes = 180;
- if (h40Radio.isChecked()) durationInMinutes = 240;
+ int durationInMinutes = SafeParse.stringToInt(duration.getText());
String confirmMessage = getString(R.string.setbasalquestion);
if (setAsPercent) {
- int basalPercentInput = SafeParse.stringToDouble(basalPercentEdit.getText().toString()).intValue();
- basalPercent = MainApp.getConfigBuilder().applyBasalConstraints(basalPercentInput);
- confirmMessage += "\n" + basalPercent + "% ";
+ int basalPercentInput = SafeParse.stringToInt(basalPercent.getText());
+ percent = MainApp.getConfigBuilder().applyBasalConstraints(basalPercentInput);
+ confirmMessage += "\n" + percent + "% ";
confirmMessage += "\n" + getString(R.string.duration) + " " + durationInMinutes + "min ?";
- if (basalPercent != basalPercentInput)
+ if (percent != basalPercentInput)
confirmMessage += "\n" + getString(R.string.constraintapllied);
} else {
- Double basalAbsoluteInput = SafeParse.stringToDouble(basalAbsoluteEdit.getText().toString());
- basalAbsolute = MainApp.getConfigBuilder().applyBasalConstraints(basalAbsoluteInput);
- confirmMessage += "\n" + basalAbsolute + " U/h ";
+ Double basalAbsoluteInput = SafeParse.stringToDouble(basalAbsolute.getText());
+ absolute = MainApp.getConfigBuilder().applyBasalConstraints(basalAbsoluteInput);
+ confirmMessage += "\n" + absolute + " U/h ";
confirmMessage += "\n" + getString(R.string.duration) + " " + durationInMinutes + "min ?";
- if (basalAbsolute - basalAbsoluteInput != 0d)
+ if (absolute - basalAbsoluteInput != 0d)
confirmMessage += "\n" + getString(R.string.constraintapllied);
}
- final int finalBasalPercent = basalPercent;
- final Double finalBasal = basalAbsolute;
+ final int finalBasalPercent = percent;
+ final Double finalBasal = absolute;
final int finalDurationInMinutes = durationInMinutes;
final Context context = getContext();
@@ -153,6 +162,12 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
result = pump.setTempBasalAbsolute(finalBasal, finalDurationInMinutes);
}
if (!result.success) {
+ if (context instanceof Activity) {
+ Activity activity = (Activity) context;
+ if (activity.isFinishing()) {
+ return;
+ }
+ }
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
builder.setMessage(result.comment);
@@ -171,6 +186,10 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
} catch (Exception e) {
e.printStackTrace();
}
+ break;
+ case R.id.cancel:
+ dismiss();
+ break;
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java
index 69db12c29b..c016f5ec61 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java
@@ -1,21 +1,32 @@
package info.nightscout.androidaps.plugins.Careportal;
+import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
+import android.widget.TextView;
+import com.squareup.otto.Subscribe;
+
+import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.FragmentBase;
+import info.nightscout.androidaps.db.CareportalEvent;
+import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
-public class CareportalFragment extends Fragment implements FragmentBase, View.OnClickListener {
+public class CareportalFragment extends Fragment implements View.OnClickListener {
static CareportalPlugin careportalPlugin;
+ TextView iage;
+ TextView cage;
+ TextView sage;
+ TextView pbage;
+
static public CareportalPlugin getPlugin() {
if (careportalPlugin == null) {
careportalPlugin = new CareportalPlugin();
@@ -24,25 +35,26 @@ public class CareportalFragment extends Fragment implements FragmentBase, View.O
}
// bg,insulin,carbs,prebolus,duration,percent,absolute,profile,split,temptarget
- final OptionsToShow bgcheck = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck, true, true, true, false, false, false, false, false, false, false);
- final OptionsToShow snackbolus = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus, true, true, true, true, false, false, false, false, false, false);
- final OptionsToShow mealbolus = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus, true, true, true, true, false, false, false, false, false, false);
- final OptionsToShow correctionbolus = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus, true, true, true, true, false, false, false, false, false, false);
- final OptionsToShow carbcorrection = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection, true, false, true, false, false, false, false, false, false, false);
- final OptionsToShow combobolus = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus, true, true, true, true, true, false, false, false, true, false);
- final OptionsToShow announcement = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement, true, false, false, false, false, false, false, false, false, false);
- final OptionsToShow note = new OptionsToShow(R.id.careportal_note, R.string.careportal_note, true, false, false, false, true, false, false, false, false, false);
- final OptionsToShow question = new OptionsToShow(R.id.careportal_question, R.string.careportal_question, true, false, false, false, false, false, false, false, false, false);
- final OptionsToShow exercise = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise, false, false, false, false, true, false, false, false, false, false);
- final OptionsToShow sitechange = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange, true, true, false, false, false, false, false, false, false, false);
- final OptionsToShow sensorstart = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart, true, false, false, false, false, false, false, false, false, false);
- final OptionsToShow sensorchange = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert, true, false, false, false, false, false, false, false, false, false);
- final OptionsToShow insulinchange = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange, true, false, false, false, false, false, false, false, false, false);
- final OptionsToShow tempbasalstart = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart, true, false, false, false, true, true, true, false, false, false);
- final OptionsToShow tempbasalend = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend, true, false, false, false, false, false, false, false, false, false);
- final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, false, false, false, true, false, false);
- final OptionsToShow openapsoffline = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline, false, false, false, false, true, false, false, false, false, false);
- final OptionsToShow temptarget = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget, false, false, false, false, true, false, false, false, false, true);
+ static final OptionsToShow bgcheck = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck, true, true, true, false, false, false, false, false, false, false);
+ static final OptionsToShow snackbolus = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus, true, true, true, true, false, false, false, false, false, false);
+ static final OptionsToShow mealbolus = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus, true, true, true, true, false, false, false, false, false, false);
+ static final OptionsToShow correctionbolus = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus, true, true, true, true, false, false, false, false, false, false);
+ static final OptionsToShow carbcorrection = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection, true, false, true, false, false, false, false, false, false, false);
+ static final OptionsToShow combobolus = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus, true, true, true, true, true, false, false, false, true, false);
+ static final OptionsToShow announcement = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow note = new OptionsToShow(R.id.careportal_note, R.string.careportal_note, true, false, false, false, true, false, false, false, false, false);
+ static final OptionsToShow question = new OptionsToShow(R.id.careportal_question, R.string.careportal_question, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow exercise = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise, false, false, false, false, true, false, false, false, false, false);
+ static final OptionsToShow sitechange = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange, true, true, false, false, false, false, false, false, false, false);
+ static final OptionsToShow sensorstart = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow sensorchange = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow insulinchange = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow pumpbatterychange = new OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow tempbasalstart = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart, true, false, false, false, true, true, true, false, false, false);
+ static final OptionsToShow tempbasalend = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend, true, false, false, false, false, false, false, false, false, false);
+ static final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, true, false, false, true, false, false);
+ static final OptionsToShow openapsoffline = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline, false, false, false, false, true, false, false, false, false, false);
+ static final OptionsToShow temptarget = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget, false, false, false, false, true, false, false, false, false, true);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
@@ -58,6 +70,7 @@ public class CareportalFragment extends Fragment implements FragmentBase, View.O
view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this);
view.findViewById(R.id.careportal_exercise).setOnClickListener(this);
view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this);
+ view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this);
view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this);
view.findViewById(R.id.careportal_note).setOnClickListener(this);
view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this);
@@ -68,14 +81,24 @@ public class CareportalFragment extends Fragment implements FragmentBase, View.O
view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this);
view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this);
view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this);
+
+ iage = (TextView) view.findViewById(R.id.careportal_insulinage);
+ cage = (TextView) view.findViewById(R.id.careportal_canulaage);
+ sage = (TextView) view.findViewById(R.id.careportal_sensorage);
+ pbage = (TextView) view.findViewById(R.id.careportal_pbage);
+
+ updateGUI();
return view;
}
@Override
public void onClick(View view) {
- FragmentManager manager = getFragmentManager();
+ action(view.getId(), getFragmentManager());
+ }
+
+ public static void action(int id, FragmentManager manager) {
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
- switch (view.getId()) {
+ switch (id) {
case R.id.careportal_bgcheck:
newDialog.setOptions(bgcheck);
break;
@@ -103,6 +126,9 @@ public class CareportalFragment extends Fragment implements FragmentBase, View.O
case R.id.careportal_insulincartridgechange:
newDialog.setOptions(insulinchange);
break;
+ case R.id.careportal_pumpbatterychange:
+ newDialog.setOptions(pumpbatterychange);
+ break;
case R.id.careportal_mealbolus:
newDialog.setOptions(mealbolus);
break;
@@ -140,4 +166,55 @@ public class CareportalFragment extends Fragment implements FragmentBase, View.O
newDialog.show(manager, "NewNSTreatmentDialog");
}
+ @Override
+ public void onPause() {
+ super.onPause();
+ MainApp.bus().unregister(this);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ MainApp.bus().register(this);
+ }
+
+ @Subscribe
+ public void onStatusEvent(final EventCareportalEventChange c) {
+ updateGUI();
+ }
+
+ void updateGUI() {
+ Activity activity = getActivity();
+ updateAge(activity, sage, iage, cage, pbage);
+ }
+
+ public static void updateAge(Activity activity, final TextView sage, final TextView iage, final TextView cage, final TextView pbage) {
+ if (activity != null) {
+ activity.runOnUiThread(
+ new Runnable() {
+ @Override
+ public void run() {
+ CareportalEvent careportalEvent;
+ if (sage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
+ sage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
+ }
+ if (iage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
+ iage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
+ }
+ if (cage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SITECHANGE);
+ cage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
+ }
+ if (pbage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.PUMPBATTERYCHANGE);
+ pbage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
+ }
+ }
+ }
+ );
+ }
+ }
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java
index 9fd4cbca85..fed3ff1a43 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.Careportal;
+import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
@@ -50,6 +51,16 @@ public class CareportalPlugin implements PluginBase {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return !Config.NSCLIENT;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
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 68d24b7dda..f1e5f09ebd 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
@@ -7,7 +7,6 @@ import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment;
-import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
@@ -21,12 +20,12 @@ import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
+import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
-import com.j256.ormlite.dao.Dao;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
@@ -36,7 +35,6 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
@@ -46,45 +44,50 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
+import info.nightscout.androidaps.db.CareportalEvent;
+import info.nightscout.androidaps.db.ProfileSwitch;
+import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
-import info.nightscout.androidaps.plugins.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.androidaps.data.Profile;
+import info.nightscout.androidaps.data.ProfileStore;
+import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin;
import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
-import info.nightscout.utils.ToastUtils;
import info.nightscout.utils.Translator;
public class NewNSTreatmentDialog extends DialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
private static Logger log = LoggerFactory.getLogger(NewNSTreatmentDialog.class);
- private FragmentActivity context;
+ private Activity context;
private static OptionsToShow options;
- NSProfile profile;
+ Profile profile;
+ ProfileStore profileStore;
String units;
- LinearLayout layoutBg;
+ RelativeLayout layoutBg;
LinearLayout layoutBgSource;
- LinearLayout layoutInsulin;
- LinearLayout layoutCarbs;
- LinearLayout layoutSplit;
- LinearLayout layoutDuration;
- LinearLayout layoutPercent;
- LinearLayout layoutAbsolute;
- LinearLayout layoutCarbTime;
- LinearLayout layoutProfile;
+ RelativeLayout layoutInsulin;
+ RelativeLayout layoutCarbs;
+ RelativeLayout layoutSplit;
+ RelativeLayout layoutDuration;
+ RelativeLayout layoutPercent;
+ RelativeLayout layoutAbsolute;
+ RelativeLayout layoutCarbTime;
+ RelativeLayout layoutProfile;
LinearLayout layoutTempTarget;
Button dateButton;
Button timeButton;
Button okButton;
+ Button cancelButton;
TextView bgUnitsView;
RadioButton meterRadioButton;
@@ -134,7 +137,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
@Override
public void onAttach(Activity activity) {
- context = (FragmentActivity) activity;
+ context = activity;
super.onAttach(activity);
}
@@ -142,18 +145,19 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle(getString(options.eventName));
+ setStyle(DialogFragment.STYLE_NORMAL, getTheme());
View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false);
- layoutBg = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_bg_layout);
+ layoutBg = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_bg_layout);
layoutBgSource = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_bgsource_layout);
- layoutInsulin = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_insulin_layout);
- layoutCarbs = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_carbs_layout);
- layoutSplit = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_split_layout);
- layoutDuration = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_duration_layout);
- layoutPercent = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_percent_layout);
- layoutAbsolute = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_absolute_layout);
- layoutCarbTime = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_carbtime_layout);
- layoutProfile = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_profile_layout);
+ layoutInsulin = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_insulin_layout);
+ layoutCarbs = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_carbs_layout);
+ layoutSplit = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_split_layout);
+ layoutDuration = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_duration_layout);
+ layoutPercent = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_percent_layout);
+ layoutAbsolute = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_absolute_layout);
+ layoutCarbTime = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_carbtime_layout);
+ layoutProfile = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_profile_layout);
layoutTempTarget = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_temptarget_layout);
bgUnitsView = (TextView) view.findViewById(R.id.careportal_newnstreatment_bgunits);
@@ -218,30 +222,25 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
dateButton.setOnClickListener(this);
timeButton.setOnClickListener(this);
- okButton = (Button) view.findViewById(R.id.careportal_newnstreatment_ok);
+ okButton = (Button) view.findViewById(R.id.ok);
okButton.setOnClickListener(this);
+ cancelButton = (Button) view.findViewById(R.id.cancel);
+ cancelButton.setOnClickListener(this);
// profile
- profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
+ profile = MainApp.getConfigBuilder().getProfile();
+ profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
ArrayList profileList;
units = Constants.MGDL;
- if (profile == null) {
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), context.getString(R.string.noprofile));
- profileList = new ArrayList();
- } else {
- units = profile.getUnits();
- profileList = profile.getProfileList();
- }
+ units = profile.getUnits();
+ profileList = profileStore.getProfileList();
ArrayAdapter adapter = new ArrayAdapter(getContext(),
- android.R.layout.simple_spinner_item, profileList);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ R.layout.spinner_centered, profileList);
profileSpinner.setAdapter(adapter);
- if (profile != null) {
- // set selected to actual profile
- for (int p = 0; p < profileList.size(); p++) {
- if (profileList.get(p).equals(profile.getActiveProfile()))
- profileSpinner.setSelection(p);
- }
+ // set selected to actual profile
+ for (int p = 0; p < profileList.size(); p++) {
+ if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName()))
+ profileSpinner.setSelection(p);
}
// temp target
@@ -250,8 +249,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
reasonList.add(MainApp.sResources.getString(R.string.activity));
reasonList.add(MainApp.sResources.getString(R.string.manual));
ArrayAdapter adapterReason = new ArrayAdapter(getContext(),
- android.R.layout.simple_spinner_item, reasonList);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ R.layout.spinner_centered, reasonList);
reasonSpinner.setAdapter(adapterReason);
// bg
@@ -267,7 +265,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
// meterRadioButton.setChecked(true);
// }
- Double bg = NSProfile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL);
+ Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL);
if (profile == null)
editBg = new PlusMinusEditText(view, R.id.careportal_newnstreatment_bginput, R.id.careportal_newnstreatment_bg_plus, R.id.careportal_newnstreatment_bg_minus, bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
else if (profile.getUnits().equals(Constants.MMOL))
@@ -276,9 +274,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editBg = new PlusMinusEditText(view, R.id.careportal_newnstreatment_bginput, R.id.careportal_newnstreatment_bg_plus, R.id.careportal_newnstreatment_bg_minus, bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
bgInputEdit.addTextChangedListener(new TextWatcher() {
- public void afterTextChanged(Editable s) {}
+ public void afterTextChanged(Editable s) {
+ }
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true);
@@ -287,9 +287,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
- if (profile == null) return;
- Double bg = NSProfile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
+ Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
editBg.setValue(bg);
}
});
@@ -361,14 +359,17 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
tpd.dismissOnPause(true);
tpd.show(context.getFragmentManager(), "Timepickerdialog");
break;
- case R.id.careportal_newnstreatment_ok:
+ case R.id.ok:
createNSTreatment();
dismiss();
break;
+ case R.id.cancel:
+ dismiss();
+ break;
}
}
- private void showOrHide(LinearLayout layout, boolean visible) {
+ private void showOrHide(ViewGroup layout, boolean visible) {
if (visible) layout.setVisibility(View.VISIBLE);
else layout.setVisibility(View.GONE);
}
@@ -398,14 +399,14 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
data.put("created_at", DateUtil.toISOString(eventTime));
switch (options.eventType) {
case R.id.careportal_bgcheck:
- data.put("eventType", "BG Check");
+ data.put("eventType", CareportalEvent.BGCHECK);
break;
case R.id.careportal_announcement:
- data.put("eventType", "Announcement");
+ data.put("eventType", CareportalEvent.ANNOUNCEMENT);
data.put("isAnnouncement", true);
break;
case R.id.careportal_cgmsensorinsert:
- data.put("eventType", "Sensor Change");
+ data.put("eventType", CareportalEvent.SENSORCHANGE);
break;
case R.id.careportal_cgmsensorstart:
data.put("eventType", "Sensor Start");
@@ -413,7 +414,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
case R.id.careportal_combobolus:
data.put("splitNow", SafeParse.stringToDouble(splitEdit.getText().toString()));
data.put("splitExt", 100 - SafeParse.stringToDouble(splitEdit.getText().toString()));
- data.put("eventType", "Combo Bolus");
+ data.put("eventType", CareportalEvent.COMBOBOLUS);
break;
case R.id.careportal_correctionbolus:
data.put("eventType", "Correction Bolus");
@@ -422,40 +423,44 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
data.put("eventType", "Carb Correction");
break;
case R.id.careportal_exercise:
- data.put("eventType", "Exercise");
+ data.put("eventType", CareportalEvent.EXERCISE);
break;
case R.id.careportal_insulincartridgechange:
- data.put("eventType", "Insulin Change");
+ data.put("eventType", CareportalEvent.INSULINCHANGE);
+ break;
+ case R.id.careportal_pumpbatterychange:
+ data.put("eventType", CareportalEvent.PUMPBATTERYCHANGE);
break;
case R.id.careportal_mealbolus:
data.put("eventType", "Meal Bolus");
break;
case R.id.careportal_note:
- data.put("eventType", "Note");
+ data.put("eventType", CareportalEvent.NOTE);
break;
case R.id.careportal_profileswitch:
- data.put("eventType", "Profile Switch");
+ data.put("eventType", CareportalEvent.PROFILESWITCH);
+ allowZeroDuration = true;
break;
case R.id.careportal_pumpsitechange:
- data.put("eventType", "Site Change");
+ data.put("eventType", CareportalEvent.SITECHANGE);
break;
case R.id.careportal_question:
- data.put("eventType", "Question");
+ data.put("eventType", CareportalEvent.QUESTION);
break;
case R.id.careportal_snackbolus:
data.put("eventType", "Snack Bolus");
break;
case R.id.careportal_tempbasalstart:
- data.put("eventType", "Temp Basal");
+ data.put("eventType", CareportalEvent.TEMPBASAL);
break;
case R.id.careportal_tempbasalend:
- data.put("eventType", "Temp Basal");
+ data.put("eventType", CareportalEvent.TEMPBASAL);
break;
case R.id.careportal_openapsoffline:
- data.put("eventType", "OpenAPS Offline");
+ data.put("eventType", CareportalEvent.OPENAPSOFFLINE);
break;
case R.id.careportal_temporarytarget:
- data.put("eventType", "Temporary Target");
+ data.put("eventType", CareportalEvent.TEMPORARYTARGET);
if (!reasonSpinner.getSelectedItem().toString().equals(""))
data.put("reason", reasonSpinner.getSelectedItem().toString());
if (SafeParse.stringToDouble(low.getText().toString()) != 0d)
@@ -611,24 +616,30 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
@Override
public void run() {
try {
- String profile = data.getString("profile");
- NSProfile nsProfile = ConfigBuilderPlugin.getActiveProfile().getProfile();
- nsProfile.setActiveProfile(profile);
+ String profileName = data.getString("profile");
+ ProfileSwitch profileSwitch = new ProfileSwitch();
+ profileSwitch.date = new Date().getTime();
+ profileSwitch.source = Source.PUMP;
+ profileSwitch.profileName = profileName;
+ profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).toString();
+ profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName();
+ profileSwitch.durationInMinutes = data.getInt("duration");
+ if (ConfigBuilderPlugin.getActiveProfileInterface() instanceof CircadianPercentageProfilePlugin) {
+ CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) MainApp.getConfigBuilder().getActiveProfileInterface();
+ profileSwitch.isCPP = true;
+ profileSwitch.timeshift = cpp.timeshift;
+ profileSwitch.percentage = cpp.percentage;
+ }
+ MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
+
PumpInterface pump = MainApp.getConfigBuilder();
if (pump != null) {
- pump.setNewBasalProfile(nsProfile);
+ pump.setNewBasalProfile(profileStore.getSpecificProfile(profileName));
log.debug("Setting new profile: " + profile);
- MainApp.bus().post(new EventNewBasalProfile(nsProfile));
+ MainApp.bus().post(new EventNewBasalProfile());
} else {
log.error("No active pump selected");
}
- if (ConfigBuilderPlugin.getActiveProfile() instanceof CircadianPercentageProfilePlugin) {
- CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) ConfigBuilderPlugin.getActiveProfile();
- data.put("CircadianPercentageProfile", true);
- data.put("timeshift", cpp.timeshift);
- data.put("percentage", cpp.percentage);
- }
- ConfigBuilderPlugin.uploadCareportalEntryToNS(data);
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} catch (JSONException e) {
e.printStackTrace();
@@ -638,30 +649,28 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
}
} else if (options.executeTempTarget) {
try {
- if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration")&& data.getInt("duration") == 0)) {
+ if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration") && data.getInt("duration") == 0)) {
sHandler.post(new Runnable() {
@Override
public void run() {
try {
TempTarget tempTarget = new TempTarget();
- tempTarget.timeStart = eventTime;
- tempTarget.duration = data.getInt("duration");
+ tempTarget.date = eventTime.getTime();
+ tempTarget.durationInMinutes = data.getInt("duration");
tempTarget.reason = data.getString("reason");
- if(tempTarget.duration != 0) {
- tempTarget.low = NSProfile.toMgdl(data.getDouble("targetBottom"), ConfigBuilderPlugin.getActiveProfile().getProfile().getUnits());
- tempTarget.high = NSProfile.toMgdl(data.getDouble("targetTop"), ConfigBuilderPlugin.getActiveProfile().getProfile().getUnits());
+ tempTarget.source = Source.USER;
+ if (tempTarget.durationInMinutes != 0) {
+ tempTarget.low = Profile.toMgdl(data.getDouble("targetBottom"), profile.getUnits());
+ tempTarget.high = Profile.toMgdl(data.getDouble("targetTop"), profile.getUnits());
} else {
tempTarget.low = 0;
tempTarget.high = 0;
}
- tempTarget.setTimeIndex(tempTarget.getTimeIndex());
- Dao dao = MainApp.getDbHelper().getDaoTempTargets();
- log.debug("Creating new TempTarget db record: " + tempTarget.log());
- dao.createIfNotExists(tempTarget);
- MainApp.bus().post(new EventTempTargetRangeChange());
- ConfigBuilderPlugin.uploadCareportalEntryToNS(data);
+ log.debug("Creating new TempTarget db record: " + tempTarget.toString());
+ MainApp.getDbHelper().createOrUpdate(tempTarget);
+ NSUpload.uploadCareportalEntryToNS(data);
Answers.getInstance().logCustom(new CustomEvent("TempTarget"));
- } catch (JSONException | SQLException e) {
+ } catch (JSONException e) {
e.printStackTrace();
}
}
@@ -671,7 +680,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
e.printStackTrace();
}
} else {
- ConfigBuilderPlugin.uploadCareportalEntryToNS(data);
+ NSUpload.uploadCareportalEntryToNS(data);
Answers.getInstance().logCustom(new CustomEvent("NSTreatment"));
}
}
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 6436441890..2445f262df 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
@@ -5,6 +5,7 @@ import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
+import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -21,6 +22,7 @@ import com.crashlytics.android.answers.CustomEvent;
import java.util.ArrayList;
+import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
@@ -28,16 +30,17 @@ import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
-import info.nightscout.androidaps.interfaces.FragmentBase;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.NSProfile.NSProfilePlugin;
-import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.InsulinFastacting.InsulinFastactingPlugin;
+import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
+import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.utils.PasswordProtection;
-public class ConfigBuilderFragment extends Fragment implements FragmentBase {
+public class ConfigBuilderFragment extends Fragment {
static ConfigBuilderPlugin configBuilderPlugin = new ConfigBuilderPlugin();
@@ -45,15 +48,17 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
return configBuilderPlugin;
}
+ ListView insulinListView;
ListView bgsourceListView;
+ TextView bgsourceLabel;
ListView pumpListView;
TextView pumpLabel;
ListView loopListView;
TextView loopLabel;
ListView treatmentsListView;
- ListView tempsListView;
- TextView tempsLabel;
+ TextView treatmentsLabel;
ListView profileListView;
+ TextView profileLabel;
ListView apsListView;
TextView apsLabel;
ListView constraintsListView;
@@ -62,18 +67,20 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
TextView nsclientVerView;
TextView nightscoutVerView;
+ LinearLayout mainLayout;
+ Button unlock;
+
+ PluginCustomAdapter insulinDataAdapter = null;
PluginCustomAdapter bgsourceDataAdapter = null;
PluginCustomAdapter pumpDataAdapter = null;
PluginCustomAdapter loopDataAdapter = null;
PluginCustomAdapter treatmentsDataAdapter = null;
- PluginCustomAdapter tempsDataAdapter = null;
PluginCustomAdapter profileDataAdapter = null;
PluginCustomAdapter apsDataAdapter = null;
PluginCustomAdapter constraintsDataAdapter = null;
PluginCustomAdapter generalDataAdapter = null;
- LinearLayout mainLayout;
- Button unlock;
+ boolean smallWidth;
// TODO: sorting
@@ -81,15 +88,24 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
+
+ //check screen width
+ final DisplayMetrics dm = new DisplayMetrics();
+ getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
+ int screen_width = dm.widthPixels;
+ smallWidth = screen_width < Constants.SMALL_WIDTH;
+
+ insulinListView = (ListView) view.findViewById(R.id.configbuilder_insulinlistview);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
+ bgsourceLabel = (TextView) view.findViewById(R.id.configbuilder_bgsourcelabel);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
pumpLabel = (TextView) view.findViewById(R.id.configbuilder_pumplabel);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
- tempsListView = (ListView) view.findViewById(R.id.configbuilder_tempslistview);
- tempsLabel = (TextView) view.findViewById(R.id.configbuilder_tempslabel);
+ treatmentsLabel = (TextView) view.findViewById(R.id.configbuilder_treatmentslabel);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
+ profileLabel = (TextView) view.findViewById(R.id.configbuilder_profilelabel);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
@@ -98,6 +114,9 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
nsclientVerView = (TextView) view.findViewById(R.id.configbuilder_nsclientversion);
nightscoutVerView = (TextView) view.findViewById(R.id.configbuilder_nightscoutversion);
+ mainLayout = (LinearLayout) view.findViewById(R.id.configbuilder_mainlayout);
+ unlock = (Button) view.findViewById(R.id.configbuilder_unlock);
+
nsclientVerView.setText(ConfigBuilderPlugin.nsClientVersionName);
nightscoutVerView.setText(ConfigBuilderPlugin.nightscoutVersionName);
if (ConfigBuilderPlugin.nsClientVersionCode < 117) nsclientVerView.setTextColor(Color.RED);
@@ -105,9 +124,6 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
nightscoutVerView.setTextColor(Color.RED);
setViews();
- unlock = (Button) view.findViewById(R.id.configbuilder_unlock);
- mainLayout = (LinearLayout) view.findViewById(R.id.configbuilder_mainlayout);
-
if (PasswordProtection.isLocked("settings_password")) {
mainLayout.setVisibility(View.GONE);
unlock.setOnClickListener(new View.OnClickListener() {
@@ -129,41 +145,45 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
}
void setViews() {
- bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class), PluginBase.BGSOURCE);
+ insulinDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface.class, PluginBase.INSULIN), PluginBase.INSULIN);
+ insulinListView.setAdapter(insulinDataAdapter);
+ setListViewHeightBasedOnChildren(insulinListView);
+ bgsourceDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginBase.BGSOURCE), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.BGSOURCE).size() == 0)
+ bgsourceLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(bgsourceListView);
- pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.PUMP), PluginBase.PUMP);
+ pumpDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
- if (MainApp.getSpecificPluginsList(PluginBase.PUMP).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP).size() == 0)
pumpLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(pumpListView);
- loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.LOOP), PluginBase.LOOP);
+ loopDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP), PluginBase.LOOP);
loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView);
- if (MainApp.getSpecificPluginsList(PluginBase.LOOP).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE);
- treatmentsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TREATMENT), PluginBase.TREATMENT);
+ treatmentsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter);
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT).size() == 0)
+ treatmentsLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(treatmentsListView);
- tempsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL), PluginBase.TEMPBASAL);
- tempsListView.setAdapter(tempsDataAdapter);
- setListViewHeightBasedOnChildren(tempsListView);
- if (MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL).size() == 0)
- tempsLabel.setVisibility(View.GONE);
- profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ProfileInterface.class), PluginBase.PROFILE);
+ profileDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.BGSOURCE), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter);
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PROFILE).size() == 0)
+ profileLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(profileListView);
- apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.APS), PluginBase.APS);
+ apsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView);
- if (MainApp.getSpecificPluginsList(PluginBase.APS).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.APS).size() == 0)
apsLabel.setVisibility(View.GONE);
- constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class), PluginBase.CONSTRAINTS);
+ constraintsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginBase.BGSOURCE), PluginBase.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView);
- if (MainApp.getSpecificPluginsList(PluginBase.CONSTRAINTS).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginBase.CONSTRAINTS).size() == 0)
constraintsLabel.setVisibility(View.GONE);
- generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.GENERAL), PluginBase.GENERAL);
+ generalDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.GENERAL), PluginBase.GENERAL);
generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView);
@@ -193,18 +213,18 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
}
@Override
- public View getView(int position, View convertView, ViewGroup parent) {
+ public View getView(int position, View view, ViewGroup parent) {
PluginViewHolder holder = null;
- if (convertView == null) {
- convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.configbuilder_simpleitem, null);
+ if (view == null) {
+ view = LayoutInflater.from(parent.getContext()).inflate(smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, null);
holder = new PluginViewHolder();
- holder.name = (TextView) convertView.findViewById(R.id.configbuilder_simpleitem_name);
- holder.checkboxEnabled = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
- holder.checkboxVisible = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
- convertView.setTag(holder);
+ holder.name = (TextView) view.findViewById(R.id.configbuilder_simpleitem_name);
+ holder.checkboxEnabled = (CheckBox) view.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
+ holder.checkboxVisible = (CheckBox) view.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
+ view.setTag(holder);
holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
@@ -232,7 +252,7 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
}
});
} else {
- holder = (PluginViewHolder) convertView.getTag();
+ holder = (PluginViewHolder) view.getTag();
}
PluginBase plugin = pluginList.get(position);
@@ -252,8 +272,12 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
holder.checkboxVisible.setEnabled(false);
}
+ if (!plugin.hasFragment()) {
+ holder.checkboxVisible.setVisibility(View.INVISIBLE);
+ }
+
// Hide enabled control and force enabled plugin if there is only one plugin available
- if (type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.TEMPBASAL || type == PluginBase.PROFILE)
+ if (type == PluginBase.INSULIN || type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.PROFILE)
if (pluginList.size() < 2) {
holder.checkboxEnabled.setEnabled(false);
plugin.setFragmentEnabled(type, true);
@@ -284,7 +308,7 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
}
}
- return convertView;
+ return view;
}
@@ -299,6 +323,9 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
case PluginBase.LOOP:
break;
// Single selection allowed
+ case PluginBase.INSULIN:
+ pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
+ break;
case PluginBase.APS:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class);
break;
@@ -308,7 +335,6 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
case PluginBase.BGSOURCE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
- case PluginBase.TEMPBASAL:
case PluginBase.TREATMENT:
case PluginBase.PUMP:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(PumpInterface.class);
@@ -328,6 +354,8 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
} else { // enable first plugin in list
if (type == PluginBase.PUMP)
MainApp.getSpecificPlugin(VirtualPumpPlugin.class).setFragmentEnabled(type, true);
+ else if (type == PluginBase.INSULIN)
+ MainApp.getSpecificPlugin(InsulinFastactingPlugin.class).setFragmentEnabled(type, true);
else if (type == PluginBase.PROFILE)
MainApp.getSpecificPlugin(NSProfilePlugin.class).setFragmentEnabled(type, true);
else
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 2c42ffaa41..b476577d06 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java
@@ -1,16 +1,12 @@
package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
-import android.content.Intent;
import android.content.SharedPreferences;
-import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
-import com.squareup.otto.Subscribe;
-
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -18,71 +14,65 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Date;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
+import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.Services.Intents;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
+import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.MealData;
+import info.nightscout.androidaps.data.OverlappingIntervals;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.data.PumpEnactResult;
-import info.nightscout.androidaps.db.TempBasal;
+import info.nightscout.androidaps.db.ExtendedBolus;
+import info.nightscout.androidaps.db.ProfileSwitch;
+import info.nightscout.androidaps.db.TempTarget;
+import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventBolusRequested;
-import info.nightscout.androidaps.events.EventNewBG;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
-import info.nightscout.androidaps.plugins.DanaR.comm.MsgError;
import info.nightscout.androidaps.plugins.Loop.APSResult;
-import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA;
-import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResultMA;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog;
-import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperActivity;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
-import info.nightscout.utils.BatteryLevel;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
+import info.nightscout.utils.NSUpload;
/**
* Created by mike on 05.08.2016.
*/
-public class ConfigBuilderPlugin implements PluginBase, PumpInterface, ConstraintsInterface {
+public class ConfigBuilderPlugin implements PluginBase, PumpInterface, ConstraintsInterface, TreatmentsInterface {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class);
- static BgSourceInterface activeBgSource;
- static PumpInterface activePump;
- static ProfileInterface activeProfile;
- static TreatmentsInterface activeTreatments;
- static TempBasalsInterface activeTempBasals;
- static APSInterface activeAPS;
- static LoopPlugin activeLoop;
+ private static BgSourceInterface activeBgSource;
+ private static PumpInterface activePump;
+ private static ProfileInterface activeProfile;
+ private static TreatmentsInterface activeTreatments;
+ private static APSInterface activeAPS;
+ private static LoopPlugin activeLoop;
+ private static InsulinInterface activeInsulin;
static public String nightscoutVersionName = "";
static public Integer nightscoutVersionCode = 0;
static public String nsClientVersionName = "";
static public Integer nsClientVersionCode = 0;
- static ArrayList pluginList;
+ private static ArrayList pluginList;
- PowerManager.WakeLock mWakeLock;
+ private PowerManager.WakeLock mWakeLock;
public ConfigBuilderPlugin() {
MainApp.bus().register(this);
@@ -119,12 +109,12 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
@Override
public boolean isEnabled(int type) {
- return type == GENERAL && true;
+ return type == GENERAL;
}
@Override
public boolean isVisibleInTabs(int type) {
- return type == GENERAL && true;
+ return type == GENERAL;
}
@Override
@@ -132,6 +122,16 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return false;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return false;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
// Always enabled
@@ -179,7 +179,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
if (SP.contains(settingEnabled))
p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
if (SP.contains(settingVisible))
- p.setFragmentVisible(type, SP.getBoolean(settingVisible, true));
+ p.setFragmentVisible(type, SP.getBoolean(settingVisible, true) && SP.getBoolean(settingEnabled, true));
} catch (Exception e) {
e.printStackTrace();
}
@@ -192,17 +192,12 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return activeBgSource;
}
- @Nullable
- public static ProfileInterface getActiveProfile() {
+ public static ProfileInterface getActiveProfileInterface() {
return activeProfile;
}
- public static TreatmentsInterface getActiveTreatments() {
- return activeTreatments;
- }
-
- public static TempBasalsInterface getActiveTempBasals() {
- return activeTempBasals;
+ public static InsulinInterface getActiveInsulin() {
+ return activeInsulin;
}
public static APSInterface getActiveAPS() {
@@ -213,18 +208,18 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return activeLoop;
}
- public void logPluginStatus() {
+ void logPluginStatus() {
for (PluginBase p : pluginList) {
log.debug(p.getName() + ":" +
(p.isEnabled(1) ? " GENERAL" : "") +
(p.isEnabled(2) ? " TREATMENT" : "") +
- (p.isEnabled(3) ? " TEMPBASAL" : "") +
(p.isEnabled(4) ? " PROFILE" : "") +
(p.isEnabled(5) ? " APS" : "") +
(p.isEnabled(6) ? " PUMP" : "") +
(p.isEnabled(7) ? " CONSTRAINTS" : "") +
(p.isEnabled(8) ? " LOOP" : "") +
- (p.isEnabled(9) ? " BGSOURCE" : "")
+ (p.isEnabled(9) ? " BGSOURCE" : "") +
+ (p.isEnabled(10) ? " INSULIN" : "")
);
}
}
@@ -245,6 +240,17 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
}
+ // PluginBase.INSULIN
+ pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
+ activeInsulin = (InsulinInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.INSULIN);
+ if (Config.logConfigBuilder)
+ log.debug("Selected insulin interface: " + ((PluginBase) activeInsulin).getName());
+ for (PluginBase p : pluginsInCategory) {
+ if (!p.getName().equals(((PluginBase) activeInsulin).getName())) {
+ p.setFragmentVisible(PluginBase.INSULIN, false);
+ }
+ }
+
// PluginBase.PROFILE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
@@ -270,7 +276,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
// PluginBase.PUMP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
- if (Config.logConfigBuilder && activePump != null)
+ if (activePump == null)
+ activePump = VirtualPumpPlugin.getInstance(); // for NSClient build
+ if (Config.logConfigBuilder)
log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activePump).getName())) {
@@ -291,17 +299,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
}
- // PluginBase.TEMPBASAL
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL);
- activeTempBasals = (TempBasalsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TEMPBASAL);
- if (Config.logConfigBuilder && activeTempBasals != null)
- log.debug("Selected tempbasal interface: " + ((PluginBase) activeTempBasals).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeTempBasals).getName())) {
- p.setFragmentVisible(PluginBase.TEMPBASAL, false);
- }
- }
-
// PluginBase.TREATMENT
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TREATMENT);
activeTreatments = (TreatmentsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TREATMENT);
@@ -358,23 +355,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
- public boolean isTempBasalInProgress() {
- if (activePump != null)
- return activePump.isTempBasalInProgress();
- else return false;
- }
-
- @Override
- public boolean isExtendedBoluslInProgress() {
- if (activePump != null)
- return activePump.isExtendedBoluslInProgress();
- else return false;
- }
-
- @Override
- public int setNewBasalProfile(NSProfile profile) {
+ public int setNewBasalProfile(Profile profile) {
// Compare with pump limits
- NSProfile.BasalValue[] basalValues = profile.getBasalValues();
+ Profile.BasalValue[] basalValues = profile.getBasalValues();
for (int index = 0; index < basalValues.length; index++) {
if (basalValues[index].value < getPumpDescription().basalMinimumRate) {
@@ -396,7 +379,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
@Override
- public boolean isThisProfileSet(NSProfile profile) {
+ public boolean isThisProfileSet(Profile profile) {
if (activePump != null)
return activePump.isThisProfileSet(profile);
else return true;
@@ -423,50 +406,10 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return 0d;
}
- @Override
- public double getTempBasalAbsoluteRate() {
- if (activePump != null)
- return activePump.getTempBasalAbsoluteRate();
- else
- return 0d;
- }
-
- @Override
- public double getTempBasalRemainingMinutes() {
- if (activePump != null)
- return activePump.getTempBasalRemainingMinutes();
- else
- return 0d;
- }
-
- @Override
- public TempBasal getTempBasal(Date time) {
- if (activePump != null)
- return activePump.getTempBasal(time);
- else
- return null;
- }
-
- @Override
- public TempBasal getTempBasal() {
- if (activePump != null)
- return activePump.getTempBasal();
- else
- return null;
- }
-
- @Override
- public TempBasal getExtendedBolus() {
- if (activePump != null)
- return activePump.getExtendedBolus();
- else
- return null;
- }
-
- public PumpEnactResult deliverTreatmentFromBolusWizard(Context context, Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
- mWakeLock.acquire();
- PumpEnactResult result;
- if (activePump != null) {
+ /*
+ public PumpEnactResult deliverTreatmentFromBolusWizard(InsulinInterface insulinType, Context context, Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
+ mWakeLock.acquire();
+ PumpEnactResult result;
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
@@ -479,53 +422,61 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
MainApp.bus().post(new EventBolusRequested(insulin));
- result = activePump.deliverTreatment(insulin, carbs, context);
+ result = activePump.deliverTreatment(insulinType, insulin, carbs, context);
BolusProgressDialog.bolusEnded = true;
MainApp.bus().post(new EventDismissBolusprogressIfRunning(result));
if (result.success) {
- Treatment t = new Treatment();
+ Treatment t = new Treatment(insulinType);
t.insulin = result.bolusDelivered;
if (carbTime == 0)
t.carbs = (double) result.carbsDelivered; // with different carbTime record will come back from nightscout
- t.created_at = new Date();
+ t.date = new Date().getTime();
t.mealBolus = result.carbsDelivered > 0;
- MainApp.getDbHelper().create(t);
- t.setTimeIndex(t.getTimeIndex());
+ addToHistoryTreatment(t);
t.carbs = (double) result.carbsDelivered;
- uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
+ NSUpload.uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
}
- } else {
- if (Config.logCongigBuilderActions)
- log.debug("Creating treatment: " + insulin + " carbs: " + carbs);
- Treatment t = new Treatment();
- t.insulin = insulin;
- t.carbs = (double) carbs;
- t.created_at = new Date();
- t.mealBolus = t.carbs > 0;
- MainApp.getDbHelper().create(t);
- t.setTimeIndex(t.getTimeIndex());
- t.sendToNSClient();
- result = new PumpEnactResult();
- result.success = true;
- result.bolusDelivered = insulin;
- result.carbsDelivered = carbs;
+ mWakeLock.release();
+ return result;
}
+ */
+ @Override
+ public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
+ mWakeLock.acquire();
+ PumpEnactResult result;
+ detailedBolusInfo.insulin = applyBolusConstraints(detailedBolusInfo.insulin);
+ detailedBolusInfo.carbs = applyCarbsConstraints((int) detailedBolusInfo.carbs);
+
+ BolusProgressDialog bolusProgressDialog = null;
+ if (detailedBolusInfo.context != null) {
+ bolusProgressDialog = new BolusProgressDialog();
+ bolusProgressDialog.setInsulin(detailedBolusInfo.insulin);
+ bolusProgressDialog.show(((AppCompatActivity) detailedBolusInfo.context).getSupportFragmentManager(), "BolusProgress");
+ }
+
+ MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin));
+
+ result = activePump.deliverTreatment(detailedBolusInfo);
+
+ BolusProgressDialog.bolusEnded = true;
+ MainApp.bus().post(new EventDismissBolusprogressIfRunning(result));
+
mWakeLock.release();
return result;
}
- @Override
- public PumpEnactResult deliverTreatment(Double insulin, Integer carbs, Context context) {
- return deliverTreatment(insulin, carbs, context, true);
- }
+ /*
+ @Override
+ public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context) {
+ return deliverTreatment(insulinType, insulin, carbs, context, true);
+ }
- public PumpEnactResult deliverTreatment(Double insulin, Integer carbs, Context context, boolean createTreatment) {
- mWakeLock.acquire();
- PumpEnactResult result;
- if (activePump != null) {
+ public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context, boolean createTreatment) {
+ mWakeLock.acquire();
+ PumpEnactResult result;
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
@@ -544,7 +495,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
MainApp.bus().post(new EventBolusRequested(insulin));
- result = activePump.deliverTreatment(insulin, carbs, context);
+ result = activePump.deliverTreatment(insulinType, insulin, carbs, context);
BolusProgressDialog.bolusEnded = true;
@@ -554,36 +505,19 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success && createTreatment) {
- Treatment t = new Treatment();
+ Treatment t = new Treatment(insulinType);
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
- t.created_at = new Date();
+ t.date = new Date().getTime();
t.mealBolus = t.carbs > 0;
- MainApp.getDbHelper().create(t);
- t.setTimeIndex(t.getTimeIndex());
- t.sendToNSClient();
+ addToHistoryTreatment(t);
+ NSUpload.uploadTreatment(t);
}
- } else {
- if (Config.logCongigBuilderActions)
- log.debug("Creating treatment: " + insulin + " carbs: " + carbs);
- Treatment t = new Treatment();
- t.insulin = insulin;
- t.carbs = (double) carbs;
- t.created_at = new Date();
- t.mealBolus = t.carbs > 0;
- MainApp.getDbHelper().create(t);
- t.setTimeIndex(t.getTimeIndex());
- t.sendToNSClient();
- result = new PumpEnactResult();
- result.success = true;
- result.bolusDelivered = insulin;
- result.carbsDelivered = carbs;
+ mWakeLock.release();
+ return result;
}
- mWakeLock.release();
- return result;
- }
-
+ */
@Override
public void stopBolusDelivering() {
activePump.stopBolusDelivering();
@@ -602,14 +536,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
- if (result.enacted && result.success) {
- if (result.isPercent) {
- uploadTempBasalStartPercent(result.percent, result.duration);
- } else {
- uploadTempBasalStartAbsolute(result.absolute, result.duration);
- }
- MainApp.bus().post(new EventTempBasalChange());
- }
return result;
}
@@ -626,10 +552,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
- if (result.enacted && result.success) {
- uploadTempBasalStartPercent(result.percent, result.duration);
- MainApp.bus().post(new EventTempBasalChange());
- }
return result;
}
@@ -639,10 +561,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
- if (result.enacted && result.success) {
- uploadExtendedBolus(result.bolusDelivered, result.duration);
- MainApp.bus().post(new EventTreatmentChange());
- }
return result;
}
@@ -651,10 +569,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
PumpEnactResult result = activePump.cancelTempBasal();
if (Config.logCongigBuilderActions)
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
- if (result.enacted && result.success) {
- uploadTempBasalEnd();
- MainApp.bus().post(new EventTempBasalChange());
- }
return result;
}
@@ -672,6 +586,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
* @param request
* @return
*/
+
public PumpEnactResult applyAPSRequest(APSResult request) {
request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result;
@@ -711,10 +626,10 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
}
- } else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRate()) < 0.05) {
+ } else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRateHistory()) < 0.05) {
result = new PumpEnactResult();
- result.absolute = getTempBasalAbsoluteRate();
- result.duration = activePump.getTempBasal().getPlannedRemainingMinutes();
+ result.absolute = getTempBasalAbsoluteRateHistory();
+ result.duration = getTempBasalFromHistory(new Date().getTime()).getPlannedRemainingMinutes();
result.enacted = false;
result.comment = "Temp basal set correctly";
result.success = true;
@@ -767,6 +682,13 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
}
}
+ @Override
+ public boolean isFakingTempsByExtendedBoluses() {
+ if (Config.NSCLIENT)
+ return false;
+ return activePump.isFakingTempsByExtendedBoluses();
+ }
+
/**
* Constraints interface
**/
@@ -883,272 +805,243 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return maxIobAfterConstrain;
}
- public void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes) {
- try {
- Context context = MainApp.instance().getApplicationContext();
- JSONObject data = new JSONObject();
- data.put("eventType", "Temp Basal");
- data.put("duration", durationInMinutes);
- data.put("absolute", absolute);
- data.put("created_at", DateUtil.toISOString(new Date()));
- data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
- data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + absolute + "u/h " + durationInMinutes + " min"); // ECOR
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class);
- } catch (JSONException e) {
- e.printStackTrace();
- }
+ // ****** Treatments interface *****
+ @Override
+ public void updateTotalIOBTreatments() {
+ activeTreatments.updateTotalIOBTreatments();
}
- public void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) {
- try {
- SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
- boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
- if (useAbsolute) {
- double absolute = getBaseBasalRate() * percent / 100d;
- uploadTempBasalStartAbsolute(absolute, durationInMinutes);
+ @Override
+ public void updateTotalIOBTempBasals() {
+ activeTreatments.updateTotalIOBTempBasals();
+ }
+
+ @Override
+ public IobTotal getLastCalculationTreatments() {
+ return activeTreatments.getLastCalculationTreatments();
+ }
+
+ @Override
+ public IobTotal getCalculationToTimeTreatments(long time) {
+ return activeTreatments.getCalculationToTimeTreatments(time);
+ }
+
+ @Override
+ public IobTotal getLastCalculationTempBasals() {
+ return activeTreatments.getLastCalculationTempBasals();
+ }
+
+ @Override
+ public IobTotal getCalculationToTimeTempBasals(long time) {
+ return activeTreatments.getCalculationToTimeTempBasals(time);
+ }
+
+ @Override
+ public MealData getMealData() {
+ return activeTreatments.getMealData();
+ }
+
+ @Override
+ public List getTreatmentsFromHistory() {
+ return activeTreatments.getTreatmentsFromHistory();
+ }
+
+ @Override
+ public List getTreatments5MinBackFromHistory(long time) {
+ return activeTreatments.getTreatments5MinBackFromHistory(time);
+ }
+
+ @Override
+ public boolean isInHistoryRealTempBasalInProgress() {
+ return activeTreatments.isInHistoryRealTempBasalInProgress();
+ }
+
+ @Override
+ @Nullable
+ public TemporaryBasal getRealTempBasalFromHistory(long time) {
+ return activeTreatments.getRealTempBasalFromHistory(time);
+ }
+
+ @Override
+ public boolean isTempBasalInProgress() {
+ return activeTreatments.isTempBasalInProgress();
+ }
+
+ @Override
+ @Nullable
+ public TemporaryBasal getTempBasalFromHistory(long time) {
+ return activeTreatments.getTempBasalFromHistory(time);
+ }
+
+ @Override
+ public double getTempBasalAbsoluteRateHistory() {
+ return activeTreatments.getTempBasalAbsoluteRateHistory();
+ }
+
+ @Override
+ public double getTempBasalRemainingMinutesFromHistory() {
+ return activeTreatments.getTempBasalRemainingMinutesFromHistory();
+ }
+
+ @Override
+ public OverlappingIntervals getTemporaryBasalsFromHistory() {
+ return activeTreatments.getTemporaryBasalsFromHistory();
+ }
+
+ @Override
+ public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) {
+ boolean newRecordCreated = activeTreatments.addToHistoryTempBasal(tempBasal);
+ if (newRecordCreated) {
+ if (tempBasal.durationInMinutes == 0)
+ NSUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId);
+ else if (tempBasal.isAbsolute)
+ NSUpload.uploadTempBasalStartAbsolute(tempBasal, null);
+ else
+ NSUpload.uploadTempBasalStartPercent(tempBasal);
+ }
+ return newRecordCreated;
+ }
+
+ @Override
+ public boolean isInHistoryExtendedBoluslInProgress() {
+ return activeTreatments.isInHistoryExtendedBoluslInProgress();
+ }
+
+ @Override
+ @Nullable
+ public ExtendedBolus getExtendedBolusFromHistory(long time) {
+ return activeTreatments.getExtendedBolusFromHistory(time);
+ }
+
+ @Override
+ public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) {
+ boolean newRecordCreated = activeTreatments.addToHistoryExtendedBolus(extendedBolus);
+ if (newRecordCreated) {
+ if (extendedBolus.durationInMinutes == 0) {
+ if (activePump.isFakingTempsByExtendedBoluses())
+ NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId);
+ else
+ NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId);
+ } else if (activePump.isFakingTempsByExtendedBoluses())
+ NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin);
+ else
+ NSUpload.uploadExtendedBolus(extendedBolus);
+ }
+ return newRecordCreated;
+ }
+
+ @Override
+ public OverlappingIntervals getExtendedBolusesFromHistory() {
+ return activeTreatments.getExtendedBolusesFromHistory();
+ }
+
+ @Override
+ // return true if new record is created
+ public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo) {
+ if (!detailedBolusInfo.addToTreatments)
+ return false;
+ boolean newRecordCreated = activeTreatments.addToHistoryTreatment(detailedBolusInfo);
+ if (newRecordCreated)
+ NSUpload.uploadBolusWizardRecord(detailedBolusInfo);
+ return newRecordCreated;
+ }
+
+ @Override
+ @Nullable
+ public TempTarget getTempTargetFromHistory(long time) {
+ return activeTreatments.getTempTargetFromHistory(time);
+ }
+
+ @Override
+ public OverlappingIntervals getTempTargetsFromHistory() {
+ return activeTreatments.getTempTargetsFromHistory();
+ }
+
+ @Override
+ @Nullable
+ public ProfileSwitch getProfileSwitchFromHistory(long time) {
+ return activeTreatments.getProfileSwitchFromHistory(time);
+ }
+
+ @Override
+ public ProfileIntervals getProfileSwitchesFromHistory() {
+ return activeTreatments.getProfileSwitchesFromHistory();
+ }
+
+ @Override
+ public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) {
+ activeTreatments.addToHistoryProfileSwitch(profileSwitch);
+ NSUpload.uploadProfileSwitch(profileSwitch);
+ }
+
+ @Override
+ public long oldestDataAvailable() {
+ return activeTreatments.oldestDataAvailable();
+ }
+
+ public String getProfileName() {
+ return getProfileName(new Date().getTime());
+ }
+
+ public String getProfileName(long time) {
+ ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time);
+ if (profileSwitch != null) {
+ if (profileSwitch.profileJson != null) {
+ return profileSwitch.profileName;
} else {
- Context context = MainApp.instance().getApplicationContext();
- JSONObject data = new JSONObject();
- data.put("eventType", "Temp Basal");
- data.put("duration", durationInMinutes);
- data.put("percent", percent - 100);
- data.put("created_at", DateUtil.toISOString(new Date()));
- data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
- data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + percent + "% " + durationInMinutes + " min"); // ECOR
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class);
+ Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
+ if (profile != null)
+ return profileSwitch.profileName;
}
- } catch (JSONException e) {
- e.printStackTrace();
}
+ // Unable to determine profile, failover to default
+ String defaultProfile = activeProfile.getProfile().getDefaultProfileName();
+ if (defaultProfile != null)
+ return defaultProfile;
+ // If default from plugin fails .... create empty
+ return "Default";
}
- public void uploadTempBasalEnd() {
- try {
- Context context = MainApp.instance().getApplicationContext();
- JSONObject data = new JSONObject();
- data.put("eventType", "Temp Basal");
- data.put("created_at", DateUtil.toISOString(new Date()));
- data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
- data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalendnote)); // ECOR
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class);
- } catch (JSONException e) {
- e.printStackTrace();
- }
+ public Profile getProfile() {
+ return getProfile(new Date().getTime());
}
- public void uploadExtendedBolus(Double insulin, double durationInMinutes) {
- try {
- Context context = MainApp.instance().getApplicationContext();
- JSONObject data = new JSONObject();
- data.put("eventType", "Combo Bolus");
- data.put("duration", durationInMinutes);
- data.put("splitNow", 0);
- data.put("splitExt", 100);
- data.put("enteredinsulin", insulin);
- data.put("relative", insulin);
- data.put("created_at", DateUtil.toISOString(new Date()));
- data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- public void uploadDeviceStatus() {
- DeviceStatus deviceStatus = new DeviceStatus();
- try {
- LoopPlugin.LastRun lastRun = LoopPlugin.lastRun;
- if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 300 * 1000L) {
- // do not send if result is older than 1 min
- APSResult apsResult = lastRun.request;
- apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun));
- deviceStatus.suggested = apsResult.json();
-
- if (lastRun.request instanceof DetermineBasalResultMA) {
- DetermineBasalResultMA result = (DetermineBasalResultMA) lastRun.request;
- deviceStatus.iob = result.iob.json();
- deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun));
- }
-
- if (lastRun.request instanceof DetermineBasalResultAMA) {
- DetermineBasalResultAMA result = (DetermineBasalResultAMA) lastRun.request;
- deviceStatus.iob = result.iob.json();
- deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun));
- }
-
- if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted
- deviceStatus.enacted = lastRun.request.json();
- deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate"));
- deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration"));
- deviceStatus.enacted.put("recieved", true);
- JSONObject requested = new JSONObject();
- requested.put("duration", lastRun.request.duration);
- requested.put("rate", lastRun.request.rate);
- requested.put("temp", "absolute");
- deviceStatus.enacted.put("requested", requested);
+ public Profile getProfile(long time) {
+ //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
+ ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time);
+ if (profileSwitch != null) {
+ if (profileSwitch.profileJson != null) {
+ try {
+ return new Profile(new JSONObject(profileSwitch.profileJson));
+ } catch (JSONException e) {
+ e.printStackTrace();
}
} else {
- log.debug("OpenAPS data too old to upload");
+ Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
+ if (profile != null)
+ return profile;
}
- if (activePump != null) {
- deviceStatus.device = "openaps://" + deviceID();
- JSONObject pumpstatus = getJSONStatus();
- if (pumpstatus != null) {
- deviceStatus.pump = pumpstatus;
- }
- }
-
- int batteryLevel = BatteryLevel.getBatteryLevel();
- deviceStatus.uploaderBattery = batteryLevel;
-
- deviceStatus.created_at = DateUtil.toISOString(new Date());
- deviceStatus.sendToNSClient();
+ }
+ // Unable to determine profile, failover to default
+ if (activeProfile.getProfile() == null)
+ return null; //app not initialized
+ Profile defaultProfile = activeProfile.getProfile().getDefaultProfile();
+ if (defaultProfile != null)
+ return defaultProfile;
+ // If default from plugin fails .... create empty
+ try {
+ Notification noisf = new Notification(Notification.ISF_MISSING, MainApp.sResources.getString(R.string.isfmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(noisf));
+ Notification noic = new Notification(Notification.IC_MISSING, MainApp.sResources.getString(R.string.icmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(noic));
+ Notification nobasal = new Notification(Notification.BASAL_MISSING, MainApp.sResources.getString(R.string.basalmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(nobasal));
+ Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
+ MainApp.bus().post(new EventNewNotification(notarget));
+ return new Profile(new JSONObject("{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"6\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"8\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}}"));
} catch (JSONException e) {
e.printStackTrace();
}
+ return null;
}
-
- public void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
- JSONObject data = new JSONObject();
- try {
- data.put("eventType", "Bolus Wizard");
- if (t.insulin != 0d) data.put("insulin", t.insulin);
- if (t.carbs != 0d) data.put("carbs", t.carbs.intValue());
- data.put("created_at", DateUtil.toISOString(t.created_at));
- data.put("timeIndex", t.timeIndex);
- if (glucose != 0d) data.put("glucose", glucose);
- data.put("glucoseType", glucoseType);
- data.put("boluscalc", boluscalc);
- if (carbTime != 0) data.put("preBolus", carbTime);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- uploadCareportalEntryToNS(data);
- }
-
- public static void uploadCareportalEntryToNS(JSONObject data) {
- try {
- if (data.has("preBolus") && data.has("carbs")) {
- JSONObject prebolus = new JSONObject();
- prebolus.put("carbs", data.get("carbs"));
- data.remove("carbs");
- prebolus.put("eventType", data.get("eventType"));
- if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy"));
- if (data.has("notes")) prebolus.put("notes", data.get("notes"));
- long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime();
- Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L);
- prebolus.put("created_at", DateUtil.toISOString(preBolusDate));
- uploadCareportalEntryToNS(prebolus);
- }
- Context context = MainApp.instance().getApplicationContext();
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- public static void removeCareportalEntryFromNS(String _id) {
- try {
- Context context = MainApp.instance().getApplicationContext();
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbRemove");
- bundle.putString("collection", "treatments");
- bundle.putString("_id", _id);
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbRemove(intent, _id, ConfigBuilderPlugin.class);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- public void uploadError(String error) {
- Context context = MainApp.instance().getApplicationContext();
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- JSONObject data = new JSONObject();
- try {
- data.put("eventType", "Announcement");
- data.put("created_at", DateUtil.toISOString(new Date()));
- data.put("notes", error);
- data.put("isAnnouncement", true);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), MsgError.class);
- }
-
- public void uploadAppStart() {
- if (SP.getBoolean(R.string.key_ns_logappstartedevent, true)) {
- Context context = MainApp.instance().getApplicationContext();
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "treatments");
- JSONObject data = new JSONObject();
- try {
- data.put("eventType", "Note");
- data.put("created_at", DateUtil.toISOString(new Date()));
- data.put("notes", MainApp.sResources.getString(R.string.androidaps_start));
- } catch (JSONException e) {
- e.printStackTrace();
- }
- bundle.putString("data", data.toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class);
- }
- }
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java
similarity index 94%
rename from app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java
index 2321d8a955..3334267057 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.Objectives;
+package info.nightscout.androidaps.plugins.ConstraintsObjectives;
import android.app.Activity;
import android.content.Context;
@@ -7,7 +7,6 @@ import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
-import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -24,9 +23,8 @@ import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.FragmentBase;
-public class ObjectivesFragment extends Fragment implements View.OnClickListener, FragmentBase {
+public class ObjectivesFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class);
private static ObjectivesPlugin objectivesPlugin;
@@ -44,15 +42,6 @@ public class ObjectivesFragment extends Fragment implements View.OnClickListener
LinearLayout fake_layout;
TextView reset;
- @Override
- public void onClick(View v) {
- int id = v.getId();
- switch (id) {
- default:
- break;
- }
- }
-
public class RecyclerViewAdapter extends RecyclerView.Adapter {
List objectives;
@@ -237,16 +226,4 @@ public class ObjectivesFragment extends Fragment implements View.OnClickListener
});
}
- @Override
- public void onPause() {
- super.onPause();
- MainApp.bus().unregister(this);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- MainApp.bus().register(this);
- }
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java
similarity index 97%
rename from app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java
index 86cea210b4..b6f4e57acd 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.Objectives;
+package info.nightscout.androidaps.plugins.ConstraintsObjectives;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
@@ -17,7 +17,6 @@ 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;
/**
* Created by mike on 05.08.2016.
@@ -77,6 +76,16 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyFragment.java
similarity index 63%
rename from app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyFragment.java
index 5742249206..07583e7622 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyFragment.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.SafetyFragment;
+package info.nightscout.androidaps.plugins.ConstraintsSafety;
import android.support.v4.app.Fragment;
@@ -6,9 +6,7 @@ import android.support.v4.app.Fragment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.interfaces.FragmentBase;
-
-public class SafetyFragment extends Fragment implements FragmentBase{
+public class SafetyFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(SafetyFragment.class);
private static SafetyPlugin safetyPlugin = new SafetyPlugin();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java
similarity index 91%
rename from app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java
index 83ace20c71..213bba47fa 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.SafetyFragment;
+package info.nightscout.androidaps.plugins.ConstraintsSafety;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -10,7 +10,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.HardLimits;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
@@ -57,6 +57,16 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return false;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return false;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
@@ -95,7 +105,7 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
Double origAbsoluteRate = absoluteRate;
Double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
+ Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return absoluteRate;
if (absoluteRate < 0) absoluteRate = 0d;
@@ -108,8 +118,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasal preference to " + absoluteRate + "U/h");
}
- if (absoluteRate > maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight())) {
- absoluteRate = Math.floor(maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight()) * 100) / 100;
+ if (absoluteRate > maxBasalMult * profile.getBasal()) {
+ absoluteRate = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100;
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasalMult to " + absoluteRate + "U/h");
}
@@ -126,9 +136,9 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
Integer origPercentRate = percentRate;
Double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
+ Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) return percentRate;
- Double currentBasal = profile.getBasal(profile.secondsFromMidnight());
+ Double currentBasal = profile.getBasal();
Double absoluteRate = currentBasal * ((double) percentRate / 100);
@@ -146,8 +156,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
if (Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasal preference to " + absoluteRate + "U/h");
}
- if (absoluteRate > maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight())) {
- absoluteRate = Math.floor(maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight()) * 100) / 100;
+ if (absoluteRate > maxBasalMult * profile.getBasal()) {
+ absoluteRate = Math.floor(maxBasalMult * profile.getBasal() * 100) / 100;
if (Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit)
log.debug("Limiting rate " + origRate + " by maxBasalMult to " + absoluteRate + "U/h");
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingGlucose.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingGlucose.java
deleted file mode 100644
index 1327445b19..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingGlucose.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingGlucose extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingGlucose.class);
-
- public MsgSettingGlucose() {
- SetCommand(0x3209);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRPlugin.getDanaRPump().units = intFromBuff(bytes, 0, 1);
- DanaRPlugin.getDanaRPump().easyBasalMode = intFromBuff(bytes, 1, 1);
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units: " + (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Easy basal mode: " + DanaRPlugin.getDanaRPump().easyBasalMode);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingMaxValues.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingMaxValues.java
deleted file mode 100644
index b5ced45f67..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingMaxValues.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingMaxValues extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingMaxValues.class);
-
- public MsgSettingMaxValues() {
- SetCommand(0x3205);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRPlugin.getDanaRPump().maxBolus = intFromBuff(bytes, 0, 2) / 100d;
- DanaRPlugin.getDanaRPump().maxBasal = intFromBuff(bytes, 2, 2) / 100d;
- DanaRPlugin.getDanaRPump().maxDailyTotalUnits = intFromBuff(bytes, 4, 2) / 100;
-
- if (Config.logDanaMessageDetail) {
- log.debug("Max bolus: " + DanaRPlugin.getDanaRPump().maxBolus);
- log.debug("Max basal: " + DanaRPlugin.getDanaRPump().maxBasal);
- log.debug("Total daily max units: " + DanaRPlugin.getDanaRPump().maxDailyTotalUnits);
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingMeal.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingMeal.java
deleted file mode 100644
index a588479869..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingMeal.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-/**
- * Created by mike on 13.12.2016.
- */
-
-public class MsgSettingMeal extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingMeal.class);
-
- public MsgSettingMeal() {
- SetCommand(0x3203);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRPump pump = DanaRPlugin.getDanaRPump();
- pump.basalStep = intFromBuff(bytes, 0, 1) / 100d;
- pump.bolusStep = intFromBuff(bytes, 1, 1) / 100d;
- boolean bolusEnabled = intFromBuff(bytes, 2, 1) == 1;
- int melodyTime = intFromBuff(bytes, 3, 1);
- int blockTime = intFromBuff(bytes, 4, 1);
- pump.isConfigUD = intFromBuff(bytes, 5, 1) == 1;
-
- if (Config.logDanaMessageDetail) {
- log.debug("Basal step: " + pump.basalStep);
- log.debug("Bolus step: " + pump.bolusStep);
- log.debug("Bolus enabled: " + bolusEnabled);
- log.debug("Melody time: " + melodyTime);
- log.debug("Block time: " + blockTime);
- log.debug("Is Config U/d: " + pump.isConfigUD);
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingProfileRatios.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingProfileRatios.java
deleted file mode 100644
index 56e7d6c6cb..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingProfileRatios.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingProfileRatios extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatios.class);
-
- public MsgSettingProfileRatios() {
- SetCommand(0x3204);
- }
-
- public void handleMessage(byte[] bytes) {
- if (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL) {
- DanaRPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2);
- DanaRPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2);
- DanaRPlugin.getDanaRPump().currentAIDR = intFromBuff(bytes, 8, 1);
- } else {
- DanaRPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentAIDR = intFromBuff(bytes, 8, 1);
- }
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units (saved): " + (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Current pump CIR: " + DanaRPlugin.getDanaRPump().currentCIR);
- log.debug("Current pump CF: " + DanaRPlugin.getDanaRPump().currentCF);
- log.debug("Current pump AI: " + DanaRPlugin.getDanaRPump().currentAI);
- log.debug("Current pump target: " + DanaRPlugin.getDanaRPump().currentTarget);
- log.debug("Current pump AIDR: " + DanaRPlugin.getDanaRPump().currentAIDR);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingProfileRatiosAll.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingProfileRatiosAll.java
deleted file mode 100644
index 09b386ab11..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgSettingProfileRatiosAll.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingProfileRatiosAll extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatiosAll.class);
-
- public MsgSettingProfileRatiosAll() {
- SetCommand(0x320D);
- }
-
- public void handleMessage(byte[] bytes) {
- if (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL) {
- DanaRPlugin.getDanaRPump().morningCIR = intFromBuff(bytes, 0, 2);
- DanaRPlugin.getDanaRPump().morningCF = intFromBuff(bytes, 2, 2);
- DanaRPlugin.getDanaRPump().afternoonCIR = intFromBuff(bytes, 4, 2);
- DanaRPlugin.getDanaRPump().afternoonCF = intFromBuff(bytes, 6, 2);
- DanaRPlugin.getDanaRPump().eveningCIR = intFromBuff(bytes, 8, 2);
- DanaRPlugin.getDanaRPump().eveningCF = intFromBuff(bytes, 10, 2);
- DanaRPlugin.getDanaRPump().nightCIR = intFromBuff(bytes, 12, 2);
- DanaRPlugin.getDanaRPump().nightCF = intFromBuff(bytes, 14, 2);
- } else {
- DanaRPlugin.getDanaRPump().morningCIR = intFromBuff(bytes, 0, 2);
- DanaRPlugin.getDanaRPump().morningCF = intFromBuff(bytes, 2, 2) / 100d;
- DanaRPlugin.getDanaRPump().afternoonCIR = intFromBuff(bytes, 4, 2);
- DanaRPlugin.getDanaRPump().afternoonCF = intFromBuff(bytes, 6, 2) / 100d;
- DanaRPlugin.getDanaRPump().eveningCIR = intFromBuff(bytes, 8, 2);
- DanaRPlugin.getDanaRPump().eveningCF = intFromBuff(bytes, 10, 2) / 100d;
- DanaRPlugin.getDanaRPump().nightCIR = intFromBuff(bytes, 12, 2);
- DanaRPlugin.getDanaRPump().nightCF = intFromBuff(bytes, 14, 2) / 100d;
- }
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units: " + (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Current pump morning CIR: " + DanaRPlugin.getDanaRPump().morningCIR);
- log.debug("Current pump morning CF: " + DanaRPlugin.getDanaRPump().morningCF);
- log.debug("Current pump afternoon CIR: " + DanaRPlugin.getDanaRPump().afternoonCIR);
- log.debug("Current pump afternoon CF: " + DanaRPlugin.getDanaRPump().afternoonCF);
- log.debug("Current pump evening CIR: " + DanaRPlugin.getDanaRPump().eveningCIR);
- log.debug("Current pump evening CF: " + DanaRPlugin.getDanaRPump().eveningCF);
- log.debug("Current pump night CIR: " + DanaRPlugin.getDanaRPump().nightCIR);
- log.debug("Current pump night CF: " + DanaRPlugin.getDanaRPump().nightCF);
- }
-
- DanaRPlugin.getDanaRPump().createConvertedProfile();
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatus.java
deleted file mode 100644
index e7f5472feb..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatus.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-
-public class MsgStatus extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatus.class);
-
- public MsgStatus() {
- SetCommand(0x020B);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRPlugin.getDanaRPump().dailyTotalUnits = intFromBuff(bytes, 0, 3) / 750d;
- DanaRPlugin.getDanaRPump().isExtendedInProgress = intFromBuff(bytes, 3, 1) == 1;
- DanaRPlugin.getDanaRPump().extendedBolusMinutes = intFromBuff(bytes, 4, 2);
- DanaRPlugin.getDanaRPump().extendedBolusAmount = intFromBuff(bytes, 6, 2) / 100d;
- Double lastBolusAmount = intFromBuff(bytes, 13, 2) / 100d;
- if (lastBolusAmount != 0d) {
- DanaRPlugin.getDanaRPump().lastBolusTime = dateTimeFromBuff(bytes, 8);
- DanaRPlugin.getDanaRPump().lastBolusAmount = lastBolusAmount;
- }
- DanaRPlugin.getDanaRPump().iob = intFromBuff(bytes, 15, 2) / 100d;
-
- if (Config.logDanaMessageDetail) {
- log.debug("Daily total: " + DanaRPlugin.getDanaRPump().dailyTotalUnits);
- log.debug("Is extended bolus running: " + DanaRPlugin.getDanaRPump().isExtendedInProgress);
- log.debug("Extended bolus min: " + DanaRPlugin.getDanaRPump().extendedBolusMinutes);
- log.debug("Extended bolus amount: " + DanaRPlugin.getDanaRPump().extendedBolusAmount);
- log.debug("Last bolus time: " + DanaRPlugin.getDanaRPump().lastBolusTime);
- log.debug("Last bolus amount: " + DanaRPlugin.getDanaRPump().lastBolusAmount);
- log.debug("IOB: " + DanaRPlugin.getDanaRPump().iob);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusBolusExtended.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusBolusExtended.java
deleted file mode 100644
index 3ffef7862f..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusBolusExtended.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import android.support.annotation.NonNull;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.SQLException;
-import java.util.Date;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.db.TempBasal;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-public class MsgStatusBolusExtended extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended.class);
-
- public MsgStatusBolusExtended() {
- SetCommand(0x0207);
- }
-
- public void handleMessage(byte[] bytes) {
- boolean isExtendedInProgress = intFromBuff(bytes, 0, 1) == 1;
- int extendedBolusHalfHours = intFromBuff(bytes, 1, 1);
- int extendedBolusMinutes = extendedBolusHalfHours * 30;
-
- double extendedBolusAmount = intFromBuff(bytes, 2, 2) / 100d;
- int extendedBolusSoFarInSecs = intFromBuff(bytes, 4, 3);
-
- int extendedBolusSoFarInMinutes = extendedBolusSoFarInSecs / 60;
- double extendedBolusAbsoluteRate = isExtendedInProgress ? extendedBolusAmount / extendedBolusMinutes * 60 : 0d;
- Date extendedBolusStart = isExtendedInProgress ? getDateFromSecAgo(extendedBolusSoFarInSecs) : new Date(0);
- int extendedBolusRemainingMinutes = extendedBolusMinutes - extendedBolusSoFarInMinutes;
-
- DanaRPlugin.getDanaRPump().isExtendedInProgress = isExtendedInProgress;
- DanaRPlugin.getDanaRPump().extendedBolusMinutes = extendedBolusMinutes;
- DanaRPlugin.getDanaRPump().extendedBolusAmount = extendedBolusAmount;
- DanaRPlugin.getDanaRPump().extendedBolusSoFarInMinutes = extendedBolusSoFarInMinutes;
- DanaRPlugin.getDanaRPump().extendedBolusAbsoluteRate = extendedBolusAbsoluteRate;
- DanaRPlugin.getDanaRPump().extendedBolusStart = extendedBolusStart;
- DanaRPlugin.getDanaRPump().extendedBolusRemainingMinutes = extendedBolusRemainingMinutes;
-
- updateExtendedBolusInDB();
-
- if (Config.logDanaMessageDetail) {
- log.debug("Is extended bolus running: " + isExtendedInProgress);
- log.debug("Extended bolus min: " + extendedBolusMinutes);
- log.debug("Extended bolus amount: " + extendedBolusAmount);
- log.debug("Extended bolus so far in minutes: " + extendedBolusSoFarInMinutes);
- log.debug("Extended bolus absolute rate: " + extendedBolusAbsoluteRate);
- log.debug("Extended bolus start: " + extendedBolusStart);
- log.debug("Extended bolus remaining minutes: " + extendedBolusRemainingMinutes);
- }
- }
-
- @NonNull
- private Date getDateFromSecAgo(int tempBasalAgoSecs) {
- return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000);
- }
-
- public static void updateExtendedBolusInDB() {
- DanaRPlugin DanaRPlugin = (DanaRPlugin) MainApp.getSpecificPlugin(DanaRPlugin.class);
- DanaRPump danaRPump = DanaRPlugin.getDanaRPump();
- Date now = new Date();
-
- try {
-
- if (DanaRPlugin.isExtendedBoluslInProgress()) {
- TempBasal extendedBolus = DanaRPlugin.getExtendedBolus();
- if (danaRPump.isExtendedInProgress) {
- if (extendedBolus.absolute != danaRPump.extendedBolusAbsoluteRate) {
- // Close current extended
- extendedBolus.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(extendedBolus);
- // Create new
- TempBasal newExtended = new TempBasal();
- newExtended.timeStart = now;
- newExtended.absolute = danaRPump.extendedBolusAbsoluteRate;
- newExtended.isAbsolute = true;
- newExtended.duration = danaRPump.extendedBolusMinutes;
- newExtended.isExtended = true;
- MainApp.getDbHelper().getDaoTempBasals().create(newExtended);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- // Close curent temp basal
- extendedBolus.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(extendedBolus);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- if (danaRPump.isExtendedInProgress) {
- // Create new
- TempBasal newExtended = new TempBasal();
- newExtended.timeStart = now;
- newExtended.absolute = danaRPump.extendedBolusAbsoluteRate;
- newExtended.isAbsolute = true;
- newExtended.duration = danaRPump.extendedBolusMinutes;
- newExtended.isExtended = true;
- MainApp.getDbHelper().getDaoTempBasals().create(newExtended);
- MainApp.bus().post(new EventTempBasalChange());
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusProfile.java
deleted file mode 100644
index 5006a7b1ea..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusProfile.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgStatusProfile extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatusProfile.class);
-
- public MsgStatusProfile() {
- SetCommand(0x0204);
- }
-
- public void handleMessage(byte[] bytes) {
- if (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL) {
- DanaRPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2);
- DanaRPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2);
- } else {
- DanaRPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2) / 100d;
- }
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units (saved): " + (DanaRPlugin.getDanaRPump().units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Current pump CIR: " + DanaRPlugin.getDanaRPump().currentCIR);
- log.debug("Current pump CF: " + DanaRPlugin.getDanaRPump().currentCF);
- log.debug("Current pump AI: " + DanaRPlugin.getDanaRPump().currentAI);
- log.debug("Current pump target: " + DanaRPlugin.getDanaRPump().currentTarget);
- log.debug("Current pump AIDR: " + DanaRPlugin.getDanaRPump().currentAIDR);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusTempBasal.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusTempBasal.java
deleted file mode 100644
index cdcac0c365..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaR/comm/MsgStatusTempBasal.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaR.comm;
-
-import android.support.annotation.NonNull;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.SQLException;
-import java.util.Date;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.db.TempBasal;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
-
-public class MsgStatusTempBasal extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal.class);
-
- public MsgStatusTempBasal() {
- SetCommand(0x0205);
- }
-
- public void handleMessage(byte[] bytes) {
- boolean isTempBasalInProgress = intFromBuff(bytes, 0, 1) == 1;
- int tempBasalPercent = intFromBuff(bytes, 1, 1);
- int tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60;
- int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3);
- int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60;
- Date tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : new Date(0);
-
- DanaRPlugin.getDanaRPump().isTempBasalInProgress = isTempBasalInProgress;
- DanaRPlugin.getDanaRPump().tempBasalPercent = tempBasalPercent;
- DanaRPlugin.getDanaRPump().tempBasalRemainingMin = tempBasalRemainingMin;
- DanaRPlugin.getDanaRPump().tempBasalTotalSec = tempBasalTotalSec;
- DanaRPlugin.getDanaRPump().tempBasalStart = tempBasalStart;
-
- updateTempBasalInDB();
-
- if (Config.logDanaMessageDetail) {
- log.debug("Is temp basal running: " + isTempBasalInProgress);
- log.debug("Current temp basal percent: " + tempBasalPercent);
- log.debug("Current temp basal remaining min: " + tempBasalRemainingMin);
- log.debug("Current temp basal total sec: " + tempBasalTotalSec);
- log.debug("Current temp basal start: " + tempBasalStart);
- }
- }
-
- @NonNull
- private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
- return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000);
- }
-
- public static void updateTempBasalInDB() {
- DanaRPlugin DanaRPlugin = (DanaRPlugin) MainApp.getSpecificPlugin(DanaRPlugin.class);
- DanaRPump danaRPump = DanaRPlugin.getDanaRPump();
- Date now = new Date();
-
- try {
-
- if (DanaRPlugin.isRealTempBasalInProgress()) {
- TempBasal tempBasal = DanaRPlugin.getRealTempBasal();
- if (danaRPump.isTempBasalInProgress) {
- if (tempBasal.percent != danaRPump.tempBasalPercent) {
- // Close current temp basal
- tempBasal.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(tempBasal);
- // Create new
- TempBasal newTempBasal = new TempBasal();
- newTempBasal.timeStart = now;
- newTempBasal.percent = danaRPump.tempBasalPercent;
- newTempBasal.isAbsolute = false;
- newTempBasal.duration = danaRPump.tempBasalTotalSec / 60;
- newTempBasal.isExtended = false;
- MainApp.getDbHelper().getDaoTempBasals().create(newTempBasal);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- // Close current temp basal
- tempBasal.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(tempBasal);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- if (danaRPump.isTempBasalInProgress) {
- // Create new
- TempBasal newTempBasal = new TempBasal();
- newTempBasal.timeStart = now;
- newTempBasal.percent = danaRPump.tempBasalPercent;
- newTempBasal.isAbsolute = false;
- newTempBasal.duration = danaRPump.tempBasalTotalSec / 60;
- newTempBasal.isExtended = false;
- MainApp.getDbHelper().getDaoTempBasals().create(newTempBasal);
- MainApp.bus().post(new EventTempBasalChange());
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-}
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
deleted file mode 100644
index 6786cc4c2e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/DanaRKoreanPump.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.text.DecimalFormat;
-import java.util.Date;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
-import info.nightscout.utils.SP;
-
-/**
- * Created by mike on 04.07.2016.
- */
-public class DanaRKoreanPump {
- public static final int UNITS_MGDL = 0;
- public static final int UNITS_MMOL = 1;
-
- public static final int DELIVERY_PRIME = 0x01;
- public static final int DELIVERY_STEP_BOLUS = 0x02;
- public static final int DELIVERY_BASAL = 0x04;
- public static final int DELIVERY_EXT_BOLUS = 0x08;
-
- public static final String PROFILE_PREFIX = "DanaR-";
-
- public Date lastConnection = new Date(0);
- public Date lastSettingsRead = new Date(0);
-
- // Info
- public String serialNumber = "";
- public Date shippingDate = new Date(0);
- public String shippingCountry = "";
- public boolean isNewPump = true;
- public int password = -1;
- public Date pumpTime = new Date(0);
-
- public static final int DOMESTIC_MODEL = 0x01;
- public static final int EXPORT_MODEL = 0x03;
- public int model;
- public int protocol;
- public int productCode;
-
- public boolean pumpSuspended;
-
- public boolean isConfigUD;
- public boolean isExtendedBolusEnabled;
- public boolean isEasyModeEnabled;
-
- // Status
- public double dailyTotalUnits;
- public int maxDailyTotalUnits;
-
- public double bolusStep;
- public double basalStep;
-
- public double iob;
-
- public double reservoirRemainingUnits;
- public int batteryRemaining;
-
- public double currentBasal;
-
- public boolean isTempBasalInProgress;
- public int tempBasalPercent;
- public int tempBasalRemainingMin;
- public int tempBasalTotalSec;
- public Date tempBasalStart;
-
- public boolean isExtendedInProgress;
- public int extendedBolusMinutes;
- public double extendedBolusAmount;
- public double extendedBolusAbsoluteRate;
- public int extendedBolusSoFarInMinutes;
- public Date extendedBolusStart;
- public int extendedBolusRemainingMinutes;
-
- // Profile
- public int units;
- public int easyBasalMode;
- public boolean basal48Enable = false;
- public int currentCIR;
- public double currentCF;
- public double currentAI;
- public double currentTarget;
- public int currentAIDR;
-
- public int morningCIR;
- public double morningCF;
- public int afternoonCIR;
- public double afternoonCF;
- public int eveningCIR;
- public double eveningCF;
- public int nightCIR;
- public double nightCF;
-
-
- public int activeProfile = 0;
- public double[][] pumpProfiles = null;
-
- //Limits
- public double maxBolus;
- public double maxBasal;
-
- public NSProfile createConvertedProfile() {
- JSONObject json = new JSONObject();
- JSONObject store = new JSONObject();
- JSONObject profile = new JSONObject();
-
-// Morning / 6:00–10:59
-// Afternoon / 11:00–16:59
-// Evening / 17:00–21:59
-// Night / 22:00–5:59
-
- double dia = SP.getDouble(R.string.key_danarprofile_dia, 3d);
-
- try {
- json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1));
- json.put("store", store);
- profile.put("dia", dia);
-
- JSONArray carbratios = new JSONArray();
- carbratios.put(new JSONObject().put("time", "00:00").put("timeAsSeconds", 0).put("value", nightCIR));
- carbratios.put(new JSONObject().put("time", "06:00").put("timeAsSeconds", 6 * 3600).put("value", morningCIR));
- carbratios.put(new JSONObject().put("time", "11:00").put("timeAsSeconds", 11 * 3600).put("value", afternoonCIR));
- carbratios.put(new JSONObject().put("time", "14:00").put("timeAsSeconds", 17 * 3600).put("value", eveningCIR));
- carbratios.put(new JSONObject().put("time", "22:00").put("timeAsSeconds", 22 * 3600).put("value", nightCIR));
- profile.put("carbratio", carbratios);
-
- JSONArray sens = new JSONArray();
- sens.put(new JSONObject().put("time", "00:00").put("timeAsSeconds", 0).put("value", nightCF));
- sens.put(new JSONObject().put("time", "06:00").put("timeAsSeconds", 6 * 3600).put("value", morningCF));
- sens.put(new JSONObject().put("time", "11:00").put("timeAsSeconds", 11 * 3600).put("value", afternoonCF));
- sens.put(new JSONObject().put("time", "17:00").put("timeAsSeconds", 17 * 3600).put("value", eveningCF));
- sens.put(new JSONObject().put("time", "22:00").put("timeAsSeconds", 22 * 3600).put("value", nightCF));
- profile.put("sens", sens);
-
- JSONArray basals = new JSONArray();
- int basalValues = basal48Enable ? 48 : 24;
- int basalIncrement = basal48Enable ? 30 * 60 : 60 * 60;
- for (int h = 0; h < basalValues; h++) {
- String time;
- DecimalFormat df = new DecimalFormat("00");
- if (basal48Enable) {
- time = df.format((long) h / 2) + ":" + df.format(30 * (h % 2));
- } else {
- time = df.format(h) + ":00";
- }
- basals.put(new JSONObject().put("time", time).put("timeAsSeconds", h * basalIncrement).put("value", pumpProfiles[activeProfile][h]));
- }
- profile.put("basal", basals);
-
- profile.put("target_low", new JSONArray().put(new JSONObject().put("time", "00:00").put("timeAsSeconds", 0).put("value", currentTarget)));
- profile.put("target_high", new JSONArray().put(new JSONObject().put("time", "00:00").put("timeAsSeconds", 0).put("value", currentTarget)));
- profile.put("units", units == UNITS_MGDL ? Constants.MGDL : Constants.MMOL);
- store.put(PROFILE_PREFIX + (activeProfile + 1), profile);
- } catch (JSONException e) {
- e.printStackTrace();
- } catch (Exception e) {
- return null;
- }
- return new NSProfile(json, PROFILE_PREFIX + (activeProfile + 1));
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingGlucose.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingGlucose.java
deleted file mode 100644
index 8ebc972495..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingGlucose.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingGlucose extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingGlucose.class);
-
- public MsgSettingGlucose() {
- SetCommand(0x3209);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRKoreanPlugin.getDanaRPump().units = intFromBuff(bytes, 0, 1);
- DanaRKoreanPlugin.getDanaRPump().easyBasalMode = intFromBuff(bytes, 1, 1);
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units: " + (DanaRKoreanPlugin.getDanaRPump().units == DanaRKoreanPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Easy basal mode: " + DanaRKoreanPlugin.getDanaRPump().easyBasalMode);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingMaxValues.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingMaxValues.java
deleted file mode 100644
index 428881e715..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingMaxValues.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingMaxValues extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingMaxValues.class);
-
- public MsgSettingMaxValues() {
- SetCommand(0x3205);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRKoreanPlugin.getDanaRPump().maxBolus = intFromBuff(bytes, 0, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().maxBasal = intFromBuff(bytes, 2, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().maxDailyTotalUnits = intFromBuff(bytes, 4, 2) / 100;
-
- if (Config.logDanaMessageDetail) {
- log.debug("Max bolus: " + DanaRKoreanPlugin.getDanaRPump().maxBolus);
- log.debug("Max basal: " + DanaRKoreanPlugin.getDanaRPump().maxBasal);
- log.debug("Total daily max units: " + DanaRKoreanPlugin.getDanaRPump().maxDailyTotalUnits);
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingProfileRatios.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingProfileRatios.java
deleted file mode 100644
index e023c1bb5b..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingProfileRatios.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingProfileRatios extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatios.class);
-
- public MsgSettingProfileRatios() {
- SetCommand(0x3204);
- }
-
- public void handleMessage(byte[] bytes) {
- if (DanaRKoreanPlugin.getDanaRPump().units == DanaRKoreanPump.UNITS_MGDL) {
- DanaRKoreanPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRKoreanPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2);
- DanaRKoreanPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2);
- DanaRKoreanPlugin.getDanaRPump().currentAIDR = intFromBuff(bytes, 8, 1);
- } else {
- DanaRKoreanPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRKoreanPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentAIDR = intFromBuff(bytes, 8, 1);
- }
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units (saved): " + (DanaRKoreanPlugin.getDanaRPump().units == DanaRKoreanPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Current pump CIR: " + DanaRKoreanPlugin.getDanaRPump().currentCIR);
- log.debug("Current pump CF: " + DanaRKoreanPlugin.getDanaRPump().currentCF);
- log.debug("Current pump AI: " + DanaRKoreanPlugin.getDanaRPump().currentAI);
- log.debug("Current pump target: " + DanaRKoreanPlugin.getDanaRPump().currentTarget);
- log.debug("Current pump AIDR: " + DanaRKoreanPlugin.getDanaRPump().currentAIDR);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingPumpTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingPumpTime.java
deleted file mode 100644
index 359ffb924e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingPumpTime.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Date;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-
-public class MsgSettingPumpTime extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingPumpTime.class);
-
- public MsgSettingPumpTime() {
- SetCommand(0x320A);
- }
-
- public void handleMessage(byte[] bytes) {
- Date time =
- new Date(
- 100 + intFromBuff(bytes, 5, 1),
- intFromBuff(bytes, 4, 1) - 1,
- intFromBuff(bytes, 3, 1),
- intFromBuff(bytes, 2, 1),
- intFromBuff(bytes, 1, 1),
- intFromBuff(bytes, 0, 1)
- );
-
- if (Config.logDanaMessageDetail)
- log.debug("Pump time: " + time);
-
- DanaRKoreanPlugin.getDanaRPump().pumpTime = time;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingShippingInfo.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingShippingInfo.java
deleted file mode 100644
index f222d86cbf..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgSettingShippingInfo.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Date;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgSettingShippingInfo extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgSettingShippingInfo.class);
-
- public MsgSettingShippingInfo() {
- SetCommand(0x3207);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRKoreanPump pump = DanaRKoreanPlugin.getDanaRPump();
- pump.serialNumber = stringFromBuff(bytes, 0, 10);
- pump.shippingDate = dateFromBuff(bytes, 10);
- pump.shippingCountry = asciiStringFromBuff(bytes, 13, 3);
- if (Config.logDanaMessageDetail) {
- log.debug("Serial number: " + pump.serialNumber);
- log.debug("Shipping date: " + pump.shippingDate);
- log.debug("Shipping country: " + pump.shippingCountry);
- }
- }
-}
-
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatus.java
deleted file mode 100644
index bb4adaa58e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatus.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-
-public class MsgStatus extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatus.class);
-
- public MsgStatus() {
- SetCommand(0x020B);
- }
-
- public void handleMessage(byte[] bytes) {
- DanaRKoreanPlugin.getDanaRPump().dailyTotalUnits = intFromBuff(bytes, 0, 3) / 750d;
- DanaRKoreanPlugin.getDanaRPump().isExtendedInProgress = intFromBuff(bytes, 3, 1) == 1;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusMinutes = intFromBuff(bytes, 4, 2);
- DanaRKoreanPlugin.getDanaRPump().extendedBolusAmount = intFromBuff(bytes, 6, 2) / 100d;
- Double lastBolusAmount = intFromBuff(bytes, 13, 2) / 100d;
-// if (lastBolusAmount != 0d) {
-// DanaRKoreanPlugin.getDanaRPump().lastBolusTime = dateTimeFromBuff(bytes, 8);
-// DanaRKoreanPlugin.getDanaRPump().lastBolusAmount = lastBolusAmount;
-// }
- DanaRKoreanPlugin.getDanaRPump().iob = intFromBuff(bytes, 15, 2) / 100d;
-
- if (Config.logDanaMessageDetail) {
- log.debug("Daily total: " + DanaRKoreanPlugin.getDanaRPump().dailyTotalUnits);
- log.debug("Is extended bolus running: " + DanaRKoreanPlugin.getDanaRPump().isExtendedInProgress);
- log.debug("Extended bolus min: " + DanaRKoreanPlugin.getDanaRPump().extendedBolusMinutes);
- log.debug("Extended bolus amount: " + DanaRKoreanPlugin.getDanaRPump().extendedBolusAmount);
-// log.debug("Last bolus time: " + DanaRKoreanPlugin.getDanaRPump().lastBolusTime);
-// log.debug("Last bolus amount: " + DanaRKoreanPlugin.getDanaRPump().lastBolusAmount);
- log.debug("IOB: " + DanaRKoreanPlugin.getDanaRPump().iob);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusBolusExtended.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusBolusExtended.java
deleted file mode 100644
index 1c740fd960..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusBolusExtended.java
+++ /dev/null
@@ -1,114 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import android.support.annotation.NonNull;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.SQLException;
-import java.util.Date;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.db.TempBasal;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
-
-public class MsgStatusBolusExtended extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended.class);
-
- public MsgStatusBolusExtended() {
- SetCommand(0x0207);
- }
-
- public void handleMessage(byte[] bytes) {
- boolean isExtendedInProgress = intFromBuff(bytes, 0, 1) == 1;
- int extendedBolusHalfHours = intFromBuff(bytes, 1, 1);
- int extendedBolusMinutes = extendedBolusHalfHours * 30;
-
- double extendedBolusAmount = intFromBuff(bytes, 2, 2) / 100d;
- int extendedBolusSoFarInSecs = intFromBuff(bytes, 4, 3);
- int extendedBolusDeliveryPulse = intFromBuff(bytes, 7, 2);
- int isEasyUIUserSleep = intFromBuff(bytes, 9, 1);
-
- int extendedBolusSoFarInMinutes = extendedBolusSoFarInSecs / 60;
- double extendedBolusAbsoluteRate = isExtendedInProgress ? extendedBolusAmount / extendedBolusMinutes * 60 : 0d;
- Date extendedBolusStart = isExtendedInProgress ? getDateFromSecAgo(extendedBolusSoFarInSecs) : new Date(0);
- int extendedBolusRemainingMinutes = extendedBolusMinutes - extendedBolusSoFarInMinutes;
-
- DanaRKoreanPlugin.getDanaRPump().isExtendedInProgress = isExtendedInProgress;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusMinutes = extendedBolusMinutes;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusAmount = extendedBolusAmount;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusSoFarInMinutes = extendedBolusSoFarInMinutes;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusAbsoluteRate = extendedBolusAbsoluteRate;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusStart = extendedBolusStart;
- DanaRKoreanPlugin.getDanaRPump().extendedBolusRemainingMinutes = extendedBolusRemainingMinutes;
-
- updateExtendedBolusInDB();
-
- if (Config.logDanaMessageDetail) {
- log.debug("Is extended bolus running: " + isExtendedInProgress);
- log.debug("Extended bolus min: " + extendedBolusMinutes);
- log.debug("Extended bolus amount: " + extendedBolusAmount);
- log.debug("Extended bolus so far in minutes: " + extendedBolusSoFarInMinutes);
- log.debug("Extended bolus absolute rate: " + extendedBolusAbsoluteRate);
- log.debug("Extended bolus start: " + extendedBolusStart);
- log.debug("Extended bolus remaining minutes: " + extendedBolusRemainingMinutes);
- }
- }
-
- @NonNull
- private Date getDateFromSecAgo(int tempBasalAgoSecs) {
- return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000);
- }
-
- public static void updateExtendedBolusInDB() {
- DanaRKoreanPlugin DanaRKoreanPlugin = (DanaRKoreanPlugin) MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
- DanaRKoreanPump danaRKoreanPump = DanaRKoreanPlugin.getDanaRPump();
- Date now = new Date();
-
- try {
-
- if (DanaRKoreanPlugin.isExtendedBoluslInProgress()) {
- TempBasal extendedBolus = DanaRKoreanPlugin.getExtendedBolus();
- if (danaRKoreanPump.isExtendedInProgress) {
- if (extendedBolus.absolute != danaRKoreanPump.extendedBolusAbsoluteRate) {
- // Close current extended
- extendedBolus.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(extendedBolus);
- // Create new
- TempBasal newExtended = new TempBasal();
- newExtended.timeStart = now;
- newExtended.absolute = danaRKoreanPump.extendedBolusAbsoluteRate;
- newExtended.isAbsolute = true;
- newExtended.duration = danaRKoreanPump.extendedBolusMinutes;
- newExtended.isExtended = true;
- MainApp.getDbHelper().getDaoTempBasals().create(newExtended);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- // Close curent temp basal
- extendedBolus.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(extendedBolus);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- if (danaRKoreanPump.isExtendedInProgress) {
- // Create new
- TempBasal newExtended = new TempBasal();
- newExtended.timeStart = now;
- newExtended.absolute = danaRKoreanPump.extendedBolusAbsoluteRate;
- newExtended.isAbsolute = true;
- newExtended.duration = danaRKoreanPump.extendedBolusMinutes;
- newExtended.isExtended = true;
- MainApp.getDbHelper().getDaoTempBasals().create(newExtended);
- MainApp.bus().post(new EventTempBasalChange());
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusProfile.java
deleted file mode 100644
index 7af3260b3a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusProfile.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
-
-/**
- * Created by mike on 05.07.2016.
- */
-public class MsgStatusProfile extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatusProfile.class);
-
- public MsgStatusProfile() {
- SetCommand(0x0204);
- }
-
- public void handleMessage(byte[] bytes) {
- if (DanaRKoreanPlugin.getDanaRPump().units == DanaRKoreanPump.UNITS_MGDL) {
- DanaRKoreanPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRKoreanPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2);
- DanaRKoreanPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2);
- } else {
- DanaRKoreanPlugin.getDanaRPump().currentCIR = intFromBuff(bytes, 0, 2);
- DanaRKoreanPlugin.getDanaRPump().currentCF = intFromBuff(bytes, 2, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentAI = intFromBuff(bytes, 4, 2) / 100d;
- DanaRKoreanPlugin.getDanaRPump().currentTarget = intFromBuff(bytes, 6, 2) / 100d;
- }
-
- if (Config.logDanaMessageDetail) {
- log.debug("Pump units (saved): " + (DanaRKoreanPlugin.getDanaRPump().units == DanaRKoreanPump.UNITS_MGDL ? "MGDL" : "MMOL"));
- log.debug("Current pump CIR: " + DanaRKoreanPlugin.getDanaRPump().currentCIR);
- log.debug("Current pump CF: " + DanaRKoreanPlugin.getDanaRPump().currentCF);
- log.debug("Current pump AI: " + DanaRKoreanPlugin.getDanaRPump().currentAI);
- log.debug("Current pump target: " + DanaRKoreanPlugin.getDanaRPump().currentTarget);
- log.debug("Current pump AIDR: " + DanaRKoreanPlugin.getDanaRPump().currentAIDR);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusTempBasal.java b/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusTempBasal.java
deleted file mode 100644
index 4506bb944a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/DanaRKorean/comm/MsgStatusTempBasal.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package info.nightscout.androidaps.plugins.DanaRKorean.comm;
-
-import android.support.annotation.NonNull;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.SQLException;
-import java.util.Date;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.db.TempBasal;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
-
-public class MsgStatusTempBasal extends MessageBase {
- private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal.class);
-
- public MsgStatusTempBasal() {
- SetCommand(0x0205);
- }
-
- public void handleMessage(byte[] bytes) {
- boolean isTempBasalInProgress = intFromBuff(bytes, 0, 1) == 1;
- int tempBasalPercent = intFromBuff(bytes, 1, 1);
- int tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60;
- int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3);
- int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60;
- Date tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : new Date(0);
-
- DanaRKoreanPlugin.getDanaRPump().isTempBasalInProgress = isTempBasalInProgress;
- DanaRKoreanPlugin.getDanaRPump().tempBasalPercent = tempBasalPercent;
- DanaRKoreanPlugin.getDanaRPump().tempBasalRemainingMin = tempBasalRemainingMin;
- DanaRKoreanPlugin.getDanaRPump().tempBasalTotalSec = tempBasalTotalSec;
- DanaRKoreanPlugin.getDanaRPump().tempBasalStart = tempBasalStart;
-
- updateTempBasalInDB();
-
- if (Config.logDanaMessageDetail) {
- log.debug("Is temp basal running: " + isTempBasalInProgress);
- log.debug("Current temp basal percent: " + tempBasalPercent);
- log.debug("Current temp basal remaining min: " + tempBasalRemainingMin);
- log.debug("Current temp basal total sec: " + tempBasalTotalSec);
- log.debug("Current temp basal start: " + tempBasalStart);
- }
- }
-
- @NonNull
- private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
- return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000);
- }
-
- public static void updateTempBasalInDB() {
- DanaRKoreanPlugin DanaRKoreanPlugin = (DanaRKoreanPlugin) MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
- DanaRKoreanPump danaRKoreanPump = DanaRKoreanPlugin.getDanaRPump();
- Date now = new Date();
-
- try {
-
- if (DanaRKoreanPlugin.isRealTempBasalInProgress()) {
- TempBasal tempBasal = DanaRKoreanPlugin.getRealTempBasal();
- if (danaRKoreanPump.isTempBasalInProgress) {
- if (tempBasal.percent != danaRKoreanPump.tempBasalPercent) {
- // Close current temp basal
- tempBasal.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(tempBasal);
- // Create new
- TempBasal newTempBasal = new TempBasal();
- newTempBasal.timeStart = now;
- newTempBasal.percent = danaRKoreanPump.tempBasalPercent;
- newTempBasal.isAbsolute = false;
- newTempBasal.duration = danaRKoreanPump.tempBasalTotalSec / 60;
- newTempBasal.isExtended = false;
- MainApp.getDbHelper().getDaoTempBasals().create(newTempBasal);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- // Close current temp basal
- tempBasal.timeEnd = now;
- MainApp.getDbHelper().getDaoTempBasals().update(tempBasal);
- MainApp.bus().post(new EventTempBasalChange());
- }
- } else {
- if (danaRKoreanPump.isTempBasalInProgress) {
- // Create new
- TempBasal newTempBasal = new TempBasal();
- newTempBasal.timeStart = now;
- newTempBasal.percent = danaRKoreanPump.tempBasalPercent;
- newTempBasal.isAbsolute = false;
- newTempBasal.duration = danaRKoreanPump.tempBasalTotalSec / 60;
- newTempBasal.isExtended = false;
- MainApp.getDbHelper().getDaoTempBasals().create(newTempBasal);
- MainApp.bus().post(new EventTempBasalChange());
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/ActivityGraph.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/ActivityGraph.java
new file mode 100644
index 0000000000..2f98e45272
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/ActivityGraph.java
@@ -0,0 +1,76 @@
+package info.nightscout.androidaps.plugins.InsulinFastacting;
+
+import android.content.Context;
+import android.graphics.Color;
+import android.util.AttributeSet;
+
+import com.jjoe64.graphview.GraphView;
+import com.jjoe64.graphview.series.DataPoint;
+import com.jjoe64.graphview.series.LineGraphSeries;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
+
+/**
+ * Created by mike on 21.04.2017.
+ */
+
+public class ActivityGraph extends GraphView {
+
+ Context context;
+
+ public ActivityGraph(Context context) {
+ super(context);
+ this.context = context;
+ }
+
+ public ActivityGraph(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ this.context = context;
+ }
+
+ public void show(InsulinInterface insulin) {
+ double dia = insulin.getDia();
+ int hours = (int) Math.floor(dia + 1);
+
+ Treatment t = new Treatment(insulin);
+ t.date = 0;
+ t.insulin = 1d;
+
+ LineGraphSeries activitySeries = null;
+ LineGraphSeries iobSeries = null;
+ List activityArray = new ArrayList();
+ List iobArray = new ArrayList();
+
+ for (long time = 0; time <= hours * 60 * 60 * 1000; time += 5 * 60 * 1000L) {
+ Iob iob = t.iobCalc(time, dia);
+ activityArray.add(new DataPoint(time / 60 / 1000, iob.activityContrib));
+ iobArray.add(new DataPoint(time / 60 / 1000, iob.iobContrib));
+ }
+
+ DataPoint[] activityDataPoints = new DataPoint[activityArray.size()];
+ activityDataPoints = activityArray.toArray(activityDataPoints);
+ addSeries(activitySeries = new LineGraphSeries(activityDataPoints));
+ activitySeries.setThickness(8);
+
+ getViewport().setXAxisBoundsManual(true);
+ getViewport().setMinX(0);
+ getViewport().setMaxX(hours * 60);
+ getGridLabelRenderer().setNumHorizontalLabels(hours + 1);
+ getGridLabelRenderer().setHorizontalAxisTitle("[min]");
+
+ DataPoint[] iobDataPoints = new DataPoint[iobArray.size()];
+ iobDataPoints = iobArray.toArray(iobDataPoints);
+ getSecondScale().addSeries(iobSeries = new LineGraphSeries(iobDataPoints));
+ iobSeries.setDrawBackground(true);
+ iobSeries.setColor(Color.MAGENTA);
+ iobSeries.setBackgroundColor(Color.argb(70, 255, 0, 255));
+ getSecondScale().setMinY(0);
+ getSecondScale().setMaxY(1);
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingFragment.java
new file mode 100644
index 0000000000..a99e016621
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingFragment.java
@@ -0,0 +1,46 @@
+package info.nightscout.androidaps.plugins.InsulinFastacting;
+
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+
+/**
+ * Created by mike on 17.04.2017.
+ */
+
+public class InsulinFastactingFragment extends Fragment {
+ static InsulinFastactingPlugin insulinFastactingPlugin = new InsulinFastactingPlugin();
+
+ static public InsulinFastactingPlugin getPlugin() {
+ return insulinFastactingPlugin;
+ }
+
+ TextView insulinName;
+ TextView insulinComment;
+ TextView insulinDia;
+ ActivityGraph insulinGraph;
+
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.insulin_fragment, container, false);
+
+ insulinName = (TextView) view.findViewById(R.id.insulin_name);
+ insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
+ insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
+ insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
+
+ insulinName.setText(insulinFastactingPlugin.getFriendlyName());
+ insulinComment.setText(insulinFastactingPlugin.getComment());
+ insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + new Double(insulinFastactingPlugin.getDia()).toString() + "h");
+ insulinGraph.show(insulinFastactingPlugin);
+
+ return view;
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java
new file mode 100644
index 0000000000..c98295ad35
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/InsulinFastactingPlugin.java
@@ -0,0 +1,122 @@
+package info.nightscout.androidaps.plugins.InsulinFastacting;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
+import info.nightscout.androidaps.interfaces.PluginBase;
+
+/**
+ * Created by mike on 17.04.2017.
+ */
+
+public class InsulinFastactingPlugin implements PluginBase, InsulinInterface {
+
+ private static boolean fragmentEnabled = true;
+ private static boolean fragmentVisible = false;
+
+ @Override
+ public int getType() {
+ return INSULIN;
+ }
+
+ @Override
+ public String getFragmentClass() {
+ return InsulinFastactingFragment.class.getName();
+ }
+
+ @Override
+ public String getName() {
+ return MainApp.sResources.getString(R.string.fastactinginsulin);
+ }
+
+ @Override
+ public String getNameShort() {
+ return MainApp.sResources.getString(R.string.insulin_shortname);
+ }
+
+ @Override
+ public boolean isEnabled(int type) {
+ return type == INSULIN && fragmentEnabled;
+ }
+
+ @Override
+ public boolean isVisibleInTabs(int type) {
+ return type == INSULIN && fragmentVisible;
+ }
+
+ @Override
+ public boolean canBeHidden(int type) {
+ return true;
+ }
+
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
+ @Override
+ public void setFragmentEnabled(int type, boolean fragmentEnabled) {
+ if (type == INSULIN) this.fragmentEnabled = fragmentEnabled;
+ }
+
+ @Override
+ public void setFragmentVisible(int type, boolean fragmentVisible) {
+ if (type == INSULIN) this.fragmentVisible = fragmentVisible;
+ }
+
+ // Insulin interface
+ @Override
+ public int getId() {
+ return FASTACTINGINSULIN;
+ }
+
+ @Override
+ public String getFriendlyName() {
+ return MainApp.sResources.getString(R.string.fastactinginsulin);
+ }
+
+ @Override
+ public String getComment() {
+ return MainApp.sResources.getString(R.string.fastactinginsulincomment);
+ }
+
+ @Override
+ public double getDia() {
+ return MainApp.getConfigBuilder().getProfile().getDia();
+ }
+
+ @Override
+ public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) {
+ Iob result = new Iob();
+
+ double scaleFactor = 3.0 / dia;
+ double peak = 75d;
+ double end = 180d;
+
+ if (treatment.insulin != 0d) {
+ long bolusTime = treatment.date;
+ double minAgo = scaleFactor * (time - bolusTime) / 1000d / 60d;
+
+ if (minAgo < peak) {
+ double x1 = minAgo / 5d + 1;
+ result.iobContrib = treatment.insulin * (1 - 0.001852 * x1 * x1 + 0.001852 * x1);
+ // units: BG (mg/dL) = (BG/U) * U insulin * scalar
+ result.activityContrib = treatment.insulin * (2 / dia / 60 / peak) * minAgo;
+
+ } else if (minAgo < end) {
+ double x2 = (minAgo - 75) / 5;
+ result.iobContrib = treatment.insulin * (0.001323 * x2 * x2 - 0.054233 * x2 + 0.55556);
+ result.activityContrib = treatment.insulin * (2 / dia / 60 - (minAgo - peak) * 2 / dia / 60 / (60 * 3 - peak));
+ }
+ }
+ return result;
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedFragment.java
new file mode 100644
index 0000000000..acc915b001
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedFragment.java
@@ -0,0 +1,47 @@
+package info.nightscout.androidaps.plugins.InsulinFastactingProlonged;
+
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.plugins.InsulinFastacting.ActivityGraph;
+
+/**
+ * Created by mike on 17.04.2017.
+ */
+
+public class InsulinFastactingProlongedFragment extends Fragment {
+ static InsulinFastactingProlongedPlugin insulinFastactingProlongedPlugin = new InsulinFastactingProlongedPlugin();
+
+ static public InsulinFastactingProlongedPlugin getPlugin() {
+ return insulinFastactingProlongedPlugin;
+ }
+
+ TextView insulinName;
+ TextView insulinComment;
+ TextView insulinDia;
+ ActivityGraph insulinGraph;
+
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.insulin_fragment, container, false);
+
+ insulinName = (TextView) view.findViewById(R.id.insulin_name);
+ insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
+ insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
+ insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
+
+ insulinName.setText(insulinFastactingProlongedPlugin.getFriendlyName());
+ insulinComment.setText(insulinFastactingProlongedPlugin.getComment());
+ insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + new Double(insulinFastactingProlongedPlugin.getDia()).toString() + "h");
+ insulinGraph.show(insulinFastactingProlongedPlugin);
+
+ return view;
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java
new file mode 100644
index 0000000000..ed5fc0485c
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastactingProlonged/InsulinFastactingProlongedPlugin.java
@@ -0,0 +1,127 @@
+package info.nightscout.androidaps.plugins.InsulinFastactingProlonged;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.Iob;
+import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.interfaces.InsulinInterface;
+import info.nightscout.androidaps.interfaces.PluginBase;
+
+/**
+ * Created by mike on 17.04.2017.
+ */
+
+public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInterface {
+
+ private static boolean fragmentEnabled = false;
+ private static boolean fragmentVisible = false;
+
+ @Override
+ public int getType() {
+ return INSULIN;
+ }
+
+ @Override
+ public String getFragmentClass() {
+ return InsulinFastactingProlongedFragment.class.getName();
+ }
+
+ @Override
+ public String getName() {
+ return MainApp.sResources.getString(R.string.fastactinginsulinprolonged);
+ }
+
+ @Override
+ public String getNameShort() {
+ return MainApp.sResources.getString(R.string.insulin_shortname);
+ }
+
+ @Override
+ public boolean isEnabled(int type) {
+ return type == INSULIN && fragmentEnabled;
+ }
+
+ @Override
+ public boolean isVisibleInTabs(int type) {
+ return type == INSULIN && fragmentVisible;
+ }
+
+ @Override
+ public boolean canBeHidden(int type) {
+ return true;
+ }
+
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
+ @Override
+ public void setFragmentEnabled(int type, boolean fragmentEnabled) {
+ if (type == INSULIN) this.fragmentEnabled = fragmentEnabled;
+ }
+
+ @Override
+ public void setFragmentVisible(int type, boolean fragmentVisible) {
+ if (type == INSULIN) this.fragmentVisible = fragmentVisible;
+ }
+
+ // Insulin interface
+ @Override
+ public int getId() {
+ return FASTACTINGINSULINPROLONGED;
+ }
+
+ @Override
+ public String getFriendlyName() {
+ return MainApp.sResources.getString(R.string.fastactinginsulinprolonged);
+ }
+
+ @Override
+ public String getComment() {
+ return MainApp.sResources.getString(R.string.fastactinginsulincomment);
+ }
+
+ @Override
+ public double getDia() {
+ return MainApp.getConfigBuilder().getProfile().getDia();
+ }
+
+ @Override
+ public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) {
+ Iob result = new Iob();
+
+ //Double scaleFactor = 3.0 / dia;
+ double peak = 75d * dia / 6.0;
+ double tail = 180d * dia / 6.0;
+ double end = 360d * dia / 6.0;
+ double Total = 2 * peak + (tail - peak) * 5 / 2 + (end - tail) / 2;
+
+ if (treatment.insulin != 0d) {
+ long bolusTime = treatment.date;
+ double minAgo = (time - bolusTime) / 1000d / 60d;
+
+ if (minAgo < peak) {
+ double x1 = 6 / dia * minAgo / 5d + 1;
+ result.iobContrib = treatment.insulin * (1 - 0.0012595 * x1 * x1 + 0.0012595 * x1);
+ // units: BG (mg/dL) = (BG/U) * U insulin * scalar
+ result.activityContrib = treatment.insulin * ((2 * peak / Total) * 2 / peak / peak * minAgo);
+ } else if (minAgo < tail) {
+ double x2 = (6 / dia * (minAgo - peak)) / 5;
+ result.iobContrib = treatment.insulin * (0.00074 * x2 * x2 - 0.0403 * x2 + 0.69772);
+ result.activityContrib = treatment.insulin * (-((2 * peak / Total) * 2 / peak * 3 / 4) / (tail - peak) * (minAgo - peak) + (2 * peak / Total) * 2 / peak);
+ } else if (minAgo < end) {
+ double x3 = (6 / dia * (minAgo - tail)) / 5;
+ result.iobContrib = treatment.insulin * (0.0001323 * x3 * x3 - 0.0097 * x3 + 0.17776);
+ result.activityContrib = treatment.insulin * (-((2 * peak / Total) * 2 / peak * 1 / 4) / (end - tail) * (minAgo - tail) + (2 * peak / Total) * 2 / peak / 4);
+ }
+
+ }
+ return result;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java
new file mode 100644
index 0000000000..427ca5d531
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java
@@ -0,0 +1,28 @@
+package info.nightscout.androidaps.plugins.IobCobCalculator;
+
+import java.util.Date;
+
+/**
+ * Created by mike on 25.04.2017.
+ */
+
+public class AutosensData {
+ long time = 0L;
+ public String pastSensitivity = "";
+ public double deviation = 0d;
+ boolean calculateWithDeviation = false;
+ double absorbed = 0d;
+ public double carbsFromBolus = 0d;
+ public double cob = 0;
+ public double bgi = 0d;
+ public double delta = 0d;
+
+ public String log(long time) {
+ return "AutosensData: " + new Date(time).toLocaleString() + " " + pastSensitivity + " Delta=" + delta + " Bgi=" + bgi + " Deviation=" + deviation + " Absorbed=" + absorbed + " CarbsFromBolus=" + carbsFromBolus + " COB=" + cob;
+ }
+
+ public int minOld() {
+ return (int) ((new Date().getTime() - time) / 1000 / 60);
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/AutosensResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java
similarity index 93%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/AutosensResult.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java
index 811fee0f39..1e40005b36 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/AutosensResult.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSAMA;
+package info.nightscout.androidaps.plugins.IobCobCalculator;
import org.json.JSONException;
import org.json.JSONObject;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorFragment.java
new file mode 100644
index 0000000000..db1db95998
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorFragment.java
@@ -0,0 +1,16 @@
+package info.nightscout.androidaps.plugins.IobCobCalculator;
+
+import android.support.v4.app.Fragment;
+
+/**
+ * Created by adrian on 17/11/16.
+ */
+
+public class IobCobCalculatorFragment extends Fragment {
+
+ private static IobCobCalculatorPlugin iobCobCalculatorPlugin = new IobCobCalculatorPlugin();
+
+ public static IobCobCalculatorPlugin getPlugin() {
+ return iobCobCalculatorPlugin;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java
new file mode 100644
index 0000000000..417322a6b4
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java
@@ -0,0 +1,629 @@
+package info.nightscout.androidaps.plugins.IobCobCalculator;
+
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.support.annotation.Nullable;
+import android.support.v4.util.LongSparseArray;
+
+import com.squareup.otto.Subscribe;
+
+import org.json.JSONArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import info.nightscout.androidaps.Config;
+import info.nightscout.androidaps.Constants;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.db.BgReading;
+import info.nightscout.androidaps.db.TemporaryBasal;
+import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.events.EventNewBG;
+import info.nightscout.androidaps.events.EventNewBasalProfile;
+import info.nightscout.androidaps.interfaces.PluginBase;
+import info.nightscout.androidaps.plugins.IobCobCalculator.events.BasalData;
+import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
+import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
+import info.nightscout.utils.Round;
+import info.nightscout.utils.SP;
+import info.nightscout.utils.SafeParse;
+
+/**
+ * Created by mike on 24.04.2017.
+ */
+
+public class IobCobCalculatorPlugin implements PluginBase {
+ private static Logger log = LoggerFactory.getLogger(IobCobCalculatorPlugin.class);
+
+ private static LongSparseArray iobTable = new LongSparseArray<>(); // oldest at index 0
+ private static LongSparseArray autosensDataTable = new LongSparseArray<>(); // oldest at index 0
+ private static LongSparseArray basalDataTable = new LongSparseArray<>(); // oldest at index 0
+
+ private static volatile List bgReadings = null; // newest at index 0
+ private static volatile List bucketed_data = null;
+
+ private static double dia = Constants.defaultDIA;
+
+ private static Handler sHandler = null;
+ private static HandlerThread sHandlerThread = null;
+
+ private static Object dataLock = new Object();
+
+ @Override
+ public int getType() {
+ return GENERAL;
+ }
+
+ @Override
+ public String getFragmentClass() {
+ return IobCobCalculatorFragment.class.getName();
+ }
+
+ @Override
+ public String getName() {
+ return "IOB COB Calculator";
+ }
+
+ @Override
+ public String getNameShort() {
+ return "IOC";
+ }
+
+ @Override
+ public boolean isEnabled(int type) {
+ return type == GENERAL;
+ }
+
+ @Override
+ public boolean isVisibleInTabs(int type) {
+ return false;
+ }
+
+ @Override
+ public boolean canBeHidden(int type) {
+ return false;
+ }
+
+ @Override
+ public boolean hasFragment() {
+ return false;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return false;
+ }
+
+ @Override
+ public void setFragmentEnabled(int type, boolean fragmentEnabled) {
+
+ }
+
+ @Override
+ public void setFragmentVisible(int type, boolean fragmentVisible) {
+
+ }
+
+ public IobCobCalculatorPlugin() {
+ MainApp.bus().register(this);
+ if (sHandlerThread == null) {
+ sHandlerThread = new HandlerThread(IobCobCalculatorPlugin.class.getSimpleName());
+ sHandlerThread.start();
+ sHandler = new Handler(sHandlerThread.getLooper());
+ }
+ onNewBg(new EventNewBG());
+ }
+
+ @Nullable
+ public static List getBucketedData(long fromTime) {
+ //log.debug("Locking getBucketedData");
+ synchronized (dataLock) {
+ if (bucketed_data == null) {
+ log.debug("No bucketed data available");
+ return null;
+ }
+ int index = indexNewerThan(fromTime);
+ if (index > -1) {
+ List part = bucketed_data.subList(0, index);
+ log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size());
+ return part;
+ }
+ }
+ //log.debug("Releasing getBucketedData");
+ return null;
+ }
+
+ private static int indexNewerThan(long time) {
+ for (int index = 0; index < bucketed_data.size(); index++) {
+ if (bucketed_data.get(index).date < time)
+ return index - 1;
+ }
+ return -1;
+ }
+
+ public static long roundUpTime(long time) {
+ if (time % 60000 == 0)
+ return time;
+ long rouded = (time / 60000 + 1) * 60000;
+ return rouded;
+ }
+
+ private void loadBgData() {
+ //log.debug("Locking loadBgData");
+ synchronized (dataLock) {
+ onNewProfile(null);
+ bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia)), false);
+ log.debug("BG data loaded. Size: " + bgReadings.size());
+ }
+ //log.debug("Releasing loadBgData");
+ }
+
+ public void createBucketedData() {
+ //log.debug("Locking createBucketedData");
+ synchronized (dataLock) {
+ if (bgReadings == null || bgReadings.size() < 3) {
+ bucketed_data = null;
+ return;
+ }
+
+ bucketed_data = new ArrayList<>();
+ bucketed_data.add(bgReadings.get(0));
+ int j = 0;
+ for (int i = 1; i < bgReadings.size(); ++i) {
+ long bgTime = bgReadings.get(i).date;
+ long lastbgTime = bgReadings.get(i - 1).date;
+ //log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + bgReadings.get(i).value + " Previous: " + new Date(lastbgTime).toString() + " " + bgReadings.get(i - 1).value);
+ if (bgReadings.get(i).value < 39 || bgReadings.get(i - 1).value < 39) {
+ continue;
+ }
+
+ long elapsed_minutes = (bgTime - lastbgTime) / (60 * 1000);
+ if (Math.abs(elapsed_minutes) > 8) {
+ // interpolate missing data points
+ double lastbg = bgReadings.get(i - 1).value;
+ elapsed_minutes = Math.abs(elapsed_minutes);
+ //console.error(elapsed_minutes);
+ long nextbgTime;
+ while (elapsed_minutes > 5) {
+ nextbgTime = lastbgTime - 5 * 60 * 1000;
+ j++;
+ BgReading newBgreading = new BgReading();
+ newBgreading.date = nextbgTime;
+ double gapDelta = bgReadings.get(i).value - lastbg;
+ //console.error(gapDelta, lastbg, elapsed_minutes);
+ double nextbg = lastbg + (5d / elapsed_minutes * gapDelta);
+ newBgreading.value = Math.round(nextbg);
+ //console.error("Interpolated", bucketed_data[j]);
+ bucketed_data.add(newBgreading);
+ //log.error("******************************************************************************************************* Adding:" + new Date(newBgreading.date).toString() + " " + newBgreading.value);
+
+ elapsed_minutes = elapsed_minutes - 5;
+ lastbg = nextbg;
+ lastbgTime = nextbgTime;
+ }
+ j++;
+ BgReading newBgreading = new BgReading();
+ newBgreading.value = bgReadings.get(i).value;
+ newBgreading.date = bgTime;
+ bucketed_data.add(newBgreading);
+ //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value);
+ } else if (Math.abs(elapsed_minutes) > 2) {
+ j++;
+ BgReading newBgreading = new BgReading();
+ newBgreading.value = bgReadings.get(i).value;
+ newBgreading.date = bgTime;
+ bucketed_data.add(newBgreading);
+ //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value);
+ } else {
+ bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2;
+ //log.error("***** Average");
+ }
+ }
+ log.debug("Bucketed data created. Size: " + bucketed_data.size());
+ }
+ //log.debug("Releasing createBucketedData");
+ }
+
+ public void calculateSensitivityData() {
+ if (MainApp.getConfigBuilder() == null)
+ return; // app still initializing
+ //log.debug("Locking calculateSensitivityData");
+ synchronized (dataLock) {
+
+ if (bucketed_data == null || bucketed_data.size() < 3) {
+ log.debug("calculateSensitivityData: No bucketed data available");
+ return;
+ }
+
+ long prevDataTime = roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date);
+ log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString());
+ AutosensData previous = autosensDataTable.get(prevDataTime);
+ // start from oldest to be able sub cob
+ for (int i = bucketed_data.size() - 4; i >= 0; i--) {
+ // check if data already exists
+ long bgTime = bucketed_data.get(i).date;
+ bgTime = roundUpTime(bgTime);
+ Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
+
+ AutosensData existing;
+ if ((existing = autosensDataTable.get(bgTime)) != null) {
+ previous = existing;
+ continue;
+ }
+
+ double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
+
+ AutosensData autosensData = new AutosensData();
+ autosensData.time = bgTime;
+
+ //console.error(bgTime , bucketed_data[i].glucose);
+ double bg;
+ double avgDelta;
+ double delta;
+ bg = bucketed_data.get(i).value;
+ if (bg < 39 || bucketed_data.get(i + 3).value < 39) {
+ log.error("! value < 39");
+ continue;
+ }
+ delta = (bg - bucketed_data.get(i + 1).value);
+
+ IobTotal iob = calulateFromTreatmentsAndTemps(bgTime);
+
+ double bgi = -iob.activity * sens * 5;
+ double deviation = delta - bgi;
+
+ List recentTreatments = MainApp.getConfigBuilder().getTreatments5MinBackFromHistory(bgTime);
+ for (int ir = 0; ir < recentTreatments.size(); ir++) {
+ autosensData.carbsFromBolus += recentTreatments.get(ir).carbs;
+ }
+
+ // if we are absorbing carbs
+ if (previous != null && previous.cob > 0) {
+ // figure out how many carbs that represents
+ // but always assume at least 3mg/dL/5m (default) absorption
+ double ci = Math.max(deviation, SP.getDouble("openapsama_min_5m_carbimpact", 3.0));
+ autosensData.absorbed = ci * profile.getIc(bgTime) / sens;
+ // and add that to the running total carbsAbsorbed
+ autosensData.cob = Math.max(previous.cob - autosensData.absorbed, 0d);
+ }
+ autosensData.cob += autosensData.carbsFromBolus;
+ autosensData.deviation = deviation;
+ autosensData.bgi = bgi;
+ autosensData.delta = delta;
+
+ // calculate autosens only without COB
+ if (autosensData.cob <= 0) {
+ if (Math.abs(deviation) < Constants.DEVIATION_TO_BE_EQUAL) {
+ autosensData.pastSensitivity += "=";
+ } else if (deviation > 0) {
+ autosensData.pastSensitivity += "+";
+ } else {
+ autosensData.pastSensitivity += "-";
+ }
+ autosensData.calculateWithDeviation = true;
+ } else {
+ autosensData.pastSensitivity += "C";
+ }
+ //log.debug("TIME: " + new Date(bgTime).toString() + " BG: " + bg + " SENS: " + sens + " DELTA: " + delta + " AVGDELTA: " + avgDelta + " IOB: " + iob.iob + " ACTIVITY: " + iob.activity + " BGI: " + bgi + " DEVIATION: " + deviation);
+
+ previous = autosensData;
+ autosensDataTable.put(bgTime, autosensData);
+ if (Config.logAutosensData)
+ log.debug(autosensData.log(bgTime));
+ }
+ }
+ MainApp.bus().post(new EventAutosensCalculationFinished());
+ //log.debug("Releasing calculateSensitivityData");
+ }
+
+ public static IobTotal calulateFromTreatmentsAndTemps(long time) {
+ long now = new Date().getTime();
+ time = roundUpTime(time);
+ if (time < now && iobTable.get(time) != null) {
+ //log.debug(">>> Cache hit");
+ return iobTable.get(time);
+ } else {
+ //log.debug(">>> Cache miss " + new Date(time).toLocaleString());
+ }
+ IobTotal bolusIob = MainApp.getConfigBuilder().getCalculationToTimeTreatments(time).round();
+ IobTotal basalIob = MainApp.getConfigBuilder().getCalculationToTimeTempBasals(time).round();
+/*
+ if (basalIob.basaliob > 0) {
+ log.debug(new Date(time).toLocaleString() + " basaliob: " + basalIob.basaliob );
+ }
+*/
+ IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
+ if (time < new Date().getTime()) {
+ iobTable.put(time, iobTotal);
+ }
+ return iobTotal;
+ }
+
+ private static Long findPreviousTimeFromBucketedData(long time) {
+ if (bucketed_data == null)
+ return null;
+ for (int index = 0; index < bucketed_data.size(); index++) {
+ if (bucketed_data.get(index).date < time)
+ return bucketed_data.get(index).date;
+ }
+ return null;
+ }
+
+ public static BasalData getBasalData(long time) {
+ long now = new Date().getTime();
+ time = roundUpTime(time);
+ BasalData retval = basalDataTable.get(time);
+ if (retval == null) {
+ retval = new BasalData();
+ TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasalFromHistory(time);
+ retval.basal = MainApp.getConfigBuilder().getProfile(time).getBasal(time);
+ if (tb != null) {
+ retval.isTempBasalRunning = true;
+ retval.tempBasalAbsolute = tb.tempBasalConvertedToAbsolute(time);
+ } else {
+ retval.isTempBasalRunning = false;
+ retval.tempBasalAbsolute = retval.basal;
+ }
+ if (time < now) {
+ basalDataTable.append(time, retval);
+ }
+ //log.debug(">>> Cache miss " + new Date(time).toLocaleString());
+ } else {
+ //log.debug(">>> Cache hit " + new Date(time).toLocaleString());
+ }
+ return retval;
+ }
+
+ public static AutosensData getAutosensData(long time) {
+ long now = new Date().getTime();
+ if (time > now)
+ return null;
+ Long previous = findPreviousTimeFromBucketedData(time);
+ if (previous == null)
+ return null;
+ time = roundUpTime(previous);
+ AutosensData data = autosensDataTable.get(time);
+ if (data != null) {
+ //log.debug(">>> Cache hit " + data.log(time));
+ return data;
+ } else {
+ //log.debug(">>> Cache miss " + new Date(time).toLocaleString());
+ return null;
+ }
+ }
+
+ public static AutosensData getLastAutosensData() {
+ if (autosensDataTable.size() < 1)
+ return null;
+ AutosensData data = autosensDataTable.valueAt(autosensDataTable.size() - 1);
+ if (data.time < new Date().getTime() - 5 * 60 * 1000) {
+ return null;
+ } else {
+ return data;
+ }
+ }
+
+ public static IobTotal[] calculateIobArrayInDia() {
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ // predict IOB out to DIA plus 30m
+ long time = new Date().getTime();
+ int len = (int) ((profile.getDia() * 60 + 30) / 5);
+ IobTotal[] array = new IobTotal[len];
+ int pos = 0;
+ for (int i = 0; i < len; i++) {
+ long t = time + i * 5 * 60000;
+ IobTotal iob = calulateFromTreatmentsAndTemps(t);
+ array[pos] = iob;
+ pos++;
+ }
+ return array;
+ }
+
+ public static AutosensResult detectSensitivity(long fromTime) {
+ //log.debug("Locking detectSensitivity");
+ synchronized (dataLock) {
+ if (autosensDataTable == null || autosensDataTable.size() < 4) {
+ log.debug("No autosens data available");
+ return new AutosensResult();
+ }
+
+ AutosensData current = getLastAutosensData();
+ if (current == null) {
+ log.debug("No current autosens data available");
+ return new AutosensResult();
+ }
+
+
+ List deviationsArray = new ArrayList<>();
+ String pastSensitivity = "";
+ int index = 0;
+ while (index < autosensDataTable.size()) {
+ AutosensData autosensData = autosensDataTable.valueAt(index);
+
+ if (autosensData.time < fromTime) {
+ index++;
+ continue;
+ }
+
+ if (autosensData.calculateWithDeviation)
+ deviationsArray.add(autosensData.deviation);
+
+ pastSensitivity += autosensData.pastSensitivity;
+ int secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time);
+ if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) {
+ pastSensitivity += "(" + Math.round(secondsFromMidnight / 3600d) + ")";
+ }
+ index++;
+ }
+
+ Double[] deviations = new Double[deviationsArray.size()];
+ deviations = deviationsArray.toArray(deviations);
+
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+
+ double sens = profile.getIsf();
+
+ double ratio = 1;
+ String ratioLimit = "";
+ String sensResult = "";
+
+ log.debug("Records: " + index + " " + pastSensitivity);
+ Arrays.sort(deviations);
+
+ for (double i = 0.9; i > 0.1; i = i - 0.02) {
+ if (percentile(deviations, (i + 0.02)) >= 0 && percentile(deviations, i) < 0) {
+ log.debug(Math.round(100 * i) + "% of non-meal deviations negative (target 45%-50%)");
+ }
+ }
+ double pSensitive = percentile(deviations, 0.50);
+ double pResistant = percentile(deviations, 0.45);
+
+ double basalOff = 0;
+
+ if (pSensitive < 0) { // sensitive
+ basalOff = pSensitive * (60 / 5) / Profile.toMgdl(sens, profile.getUnits());
+ sensResult = "Excess insulin sensitivity detected";
+ } else if (pResistant > 0) { // resistant
+ basalOff = pResistant * (60 / 5) / Profile.toMgdl(sens, profile.getUnits());
+ sensResult = "Excess insulin resistance detected";
+ } else {
+ sensResult = "Sensitivity normal";
+ }
+ log.debug(sensResult);
+ ratio = 1 + (basalOff / profile.getMaxDailyBasal());
+
+ double rawRatio = ratio;
+ ratio = Math.max(ratio, SafeParse.stringToDouble(SP.getString("openapsama_autosens_min", "0.7")));
+ ratio = Math.min(ratio, SafeParse.stringToDouble(SP.getString("openapsama_autosens_max", "1.2")));
+
+ if (ratio != rawRatio) {
+ ratioLimit = "Ratio limited from " + rawRatio + " to " + ratio;
+ log.debug(ratioLimit);
+ }
+
+ double newisf = Math.round(Profile.toMgdl(sens, profile.getUnits()) / ratio);
+ if (ratio != 1) {
+ log.debug("ISF adjusted from " + Profile.toMgdl(sens, profile.getUnits()) + " to " + newisf);
+ }
+
+ AutosensResult output = new AutosensResult();
+ output.ratio = Round.roundTo(ratio, 0.01);
+ output.carbsAbsorbed = Round.roundTo(current.cob, 0.01);
+ output.pastSensitivity = pastSensitivity;
+ output.ratioLimit = ratioLimit;
+ output.sensResult = sensResult;
+ return output;
+ }
+ //log.debug("Releasing detectSensitivity");
+ }
+
+
+ public static JSONArray convertToJSONArray(IobTotal[] iobArray) {
+ JSONArray array = new JSONArray();
+ for (int i = 0; i < iobArray.length; i++) {
+ array.put(iobArray[i].determineBasalJson());
+ }
+ return array;
+ }
+
+ @Subscribe
+ public void onNewBg(EventNewBG ev) {
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ loadBgData();
+ createBucketedData();
+ calculateSensitivityData();
+ }
+ });
+ }
+
+ @Subscribe
+ public void onNewProfile(EventNewBasalProfile ev) {
+ if (MainApp.getConfigBuilder() == null)
+ return; // app still initializing
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ dia = profile.getDia();
+ if (ev == null) { // on init no need of reset
+ return;
+ }
+ synchronized (dataLock) {
+ log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
+ iobTable = new LongSparseArray<>();
+ autosensDataTable = new LongSparseArray<>();
+ }
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ calculateSensitivityData();
+ }
+ });
+ }
+
+ // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated
+ @Subscribe
+ public void onNewHistoryData(EventNewHistoryData ev) {
+ //log.debug("Locking onNewHistoryData");
+ synchronized (dataLock) {
+ long time = ev.time;
+ log.debug("Invalidating cached data to: " + new Date(time).toLocaleString());
+ for (int index = iobTable.size() - 1; index >= 0; index--) {
+ if (iobTable.keyAt(index) > time) {
+ if (Config.logAutosensData)
+ log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
+ iobTable.removeAt(index);
+ } else {
+ break;
+ }
+ }
+ for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
+ if (autosensDataTable.keyAt(index) > time) {
+ if (Config.logAutosensData)
+ log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString());
+ autosensDataTable.removeAt(index);
+ } else {
+ break;
+ }
+ }
+ for (int index = basalDataTable.size() - 1; index >= 0; index--) {
+ if (basalDataTable.keyAt(index) > time) {
+ if (Config.logAutosensData)
+ log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString());
+ basalDataTable.removeAt(index);
+ } else {
+ break;
+ }
+ }
+ }
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ calculateSensitivityData();
+ }
+ });
+ //log.debug("Releasing onNewHistoryData");
+ }
+
+ // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2
+ // Returns the value at a given percentile in a sorted numeric array.
+ // "Linear interpolation between closest ranks" method
+ public static double percentile(Double[] arr, double p) {
+ if (arr.length == 0) return 0;
+ if (p <= 0) return arr[0];
+ if (p >= 1) return arr[arr.length - 1];
+
+ double index = arr.length * p,
+ lower = Math.floor(index),
+ upper = lower + 1,
+ weight = index % 1;
+
+ if (upper >= arr.length) return arr[(int) lower];
+ return arr[(int) lower] * (1 - weight) + arr[(int) upper] * weight;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/BasalData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/BasalData.java
new file mode 100644
index 0000000000..4e1dcc1bf6
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/BasalData.java
@@ -0,0 +1,11 @@
+package info.nightscout.androidaps.plugins.IobCobCalculator.events;
+
+/**
+ * Created by mike on 10.06.2017.
+ */
+
+public class BasalData {
+ public double basal;
+ public double tempBasalAbsolute;
+ public boolean isTempBasalRunning;
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventAutosensCalculationFinished.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventAutosensCalculationFinished.java
new file mode 100644
index 0000000000..f2977c90c5
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventAutosensCalculationFinished.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.plugins.IobCobCalculator.events;
+
+/**
+ * Created by mike on 30.04.2017.
+ */
+
+public class EventAutosensCalculationFinished {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventNewHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventNewHistoryData.java
new file mode 100644
index 0000000000..7499fad383
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventNewHistoryData.java
@@ -0,0 +1,13 @@
+package info.nightscout.androidaps.plugins.IobCobCalculator.events;
+
+/**
+ * Created by mike on 26.04.2017.
+ */
+
+public class EventNewHistoryData {
+ public long time = 0;
+
+ public EventNewHistoryData(long time) {
+ this.time = time;
+ }
+}
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 0d72464b73..3080717773 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
@@ -402,16 +402,4 @@ public class DeviceStatus {
return record;
}
- public void sendToNSClient() {
- Context context = MainApp.instance().getApplicationContext();
- Bundle bundle = new Bundle();
- bundle.putString("action", "dbAdd");
- bundle.putString("collection", "devicestatus");
- bundle.putString("data", mongoRecord().toString());
- Intent intent = new Intent(Intents.ACTION_DATABASE);
- intent.putExtras(bundle);
- intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- context.sendBroadcast(intent);
- DbLogger.dbAdd(intent, mongoRecord().toString(), DeviceStatus.class);
- }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java
index 43a8fa3c83..de295d8a6e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java
@@ -19,11 +19,10 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
-public class LoopFragment extends Fragment implements View.OnClickListener, FragmentBase {
+public class LoopFragment extends Fragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(LoopFragment.class);
private static LoopPlugin loopPlugin;
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 6a3869589b..6fa9e6d677 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
@@ -12,6 +12,7 @@ import android.support.v7.app.NotificationCompat;
import com.squareup.otto.Subscribe;
+import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,7 +33,10 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
+import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
+import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
+import info.nightscout.utils.SafeParse;
/**
* Created by mike on 05.08.2016.
@@ -44,7 +48,7 @@ public class LoopPlugin implements PluginBase {
private static HandlerThread sHandlerThread;
private boolean fragmentEnabled = false;
- private boolean fragmentVisible = true;
+ private boolean fragmentVisible = false;
private long loopSuspendedTill = 0L; // end of manual loop suspend
private boolean isSuperBolus = false;
@@ -113,6 +117,16 @@ public class LoopPlugin implements PluginBase {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == LOOP) this.fragmentEnabled = fragmentEnabled;
@@ -246,7 +260,7 @@ public class LoopPlugin implements PluginBase {
lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.setByPump = null;
- if (constraintsInterface.isClosedModeEnabled()) {
+ if (constraintsInterface.isClosedModeEnabled()) {
if (result.changeRequested) {
final PumpEnactResult waiting = new PumpEnactResult();
final PumpEnactResult previousResult = lastRun.setByPump;
@@ -306,7 +320,7 @@ public class LoopPlugin implements PluginBase {
}
MainApp.bus().post(new EventLoopUpdateGui());
- MainApp.getConfigBuilder().uploadDeviceStatus();
+ NSUpload.uploadDeviceStatus();
} finally {
if (Config.logFunctionCalls)
log.debug("invoke end");
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIFragment.java
deleted file mode 100644
index a67f68dfb3..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/MDI/MDIFragment.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package info.nightscout.androidaps.plugins.MDI;
-
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Handler;
-import android.support.annotation.Nullable;
-import android.support.v4.app.Fragment;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-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.interfaces.FragmentBase;
-import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpPlugin;
-import info.nightscout.androidaps.plugins.VirtualPump.events.EventVirtualPumpUpdateGui;
-
-public class MDIFragment extends Fragment implements FragmentBase {
- private static Logger log = LoggerFactory.getLogger(MDIFragment.class);
-
- private static MDIPlugin mdiPlugin = new MDIPlugin();
-
- public static MDIPlugin getPlugin() {
- return mdiPlugin;
- }
-}
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
index 3514285473..c3e8c777c6 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalFragment.java
@@ -28,13 +28,12 @@ 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 {
+public class NSClientInternalFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static Logger log = LoggerFactory.getLogger(NSClientInternalFragment.class);
static NSClientInternalPlugin nsClientInternalPlugin;
@@ -189,5 +188,4 @@ public class NSClientInternalFragment extends Fragment implements FragmentBase,
});
}
-
}
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
index 46c19b2eaa..a37d5442ca 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientInternalPlugin.java
@@ -4,11 +4,9 @@ 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;
@@ -20,20 +18,15 @@ import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
-import info.nightscout.androidaps.BuildConfig;
+import info.nightscout.androidaps.Config;
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;
@@ -116,6 +109,16 @@ public class NSClientInternalPlugin implements PluginBase {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return !Config.NSCLIENT;
+ }
+
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
@@ -147,11 +150,6 @@ public class NSClientInternalPlugin implements PluginBase {
MainApp.instance().getApplicationContext().unbindService(mConnection);
}
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange s) {
- //TODO
- }
-
@Subscribe
public void onStatusEvent(final EventNSClientNewLog ev) {
addToLog(ev);
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
index b318d8026f..24231de63f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java
@@ -5,22 +5,17 @@ import android.content.Intent;
import com.j256.ormlite.dao.CloseableIterator;
-import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
-import info.nightscout.utils.SP;
/**
* Created by mike on 21.02.2016.
@@ -118,7 +113,7 @@ public class UploadQueue {
String result = "";
CloseableIterator iterator = null;
try {
- iterator = MainApp.getDbHelper().getDaoDbRequest().closeableIterator();
+ iterator = MainApp.getDbHelper().getDbRequestInterator();
try {
while (iterator.hasNext()) {
DbRequest dbr = iterator.next();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java
index a1d44d0340..641a4e6a77 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java
@@ -11,7 +11,7 @@ import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.ProfileStore;
/**
@@ -20,10 +20,9 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
public class BroadcastProfile {
private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class);
- public void handleNewTreatment(NSProfile profile, Context context, boolean isDelta) {
+ public void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("profile", profile.getData().toString());
- bundle.putString("activeprofile", profile.getActiveProfile());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_PROFILE);
intent.putExtras(bundle);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java
index 70d8e9e336..79a66186fb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java
@@ -17,8 +17,9 @@ import info.nightscout.utils.ToastUtils;
* Created by mike on 02.07.2016.
*/
public class DbLogger {
- public static void dbAdd(Intent intent, String data, Class sender) {
- Logger log = LoggerFactory.getLogger(sender);
+ private static Logger log = LoggerFactory.getLogger(DbLogger.class);
+
+ public static void dbAdd(Intent intent, String data) {
List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0);
if (q.size() < 1) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.sResources.getString(R.string.nsclientnotinstalled));
@@ -27,8 +28,7 @@ public class DbLogger {
log.debug("DBADD dbAdd " + q.size() + " receivers " + data);
}
- public static void dbRemove(Intent intent, String data, Class sender) {
- Logger log = LoggerFactory.getLogger(sender);
+ public static void dbRemove(Intent intent, String data) {
List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0);
if (q.size() < 1) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.sResources.getString(R.string.nsclientnotinstalled));
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java
new file mode 100644
index 0000000000..79fa60c3bb
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java
@@ -0,0 +1,24 @@
+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 NSMbg {
+ private static Logger log = LoggerFactory.getLogger(NSMbg.class);
+ public long date;
+ public double mbg;
+ public String json;
+
+ public NSMbg(JSONObject json) {
+ try {
+ date = json.getLong("mills");
+ mbg = json.getDouble("mgdl");
+ this.json = json.toString();
+ } catch (JSONException e) {
+ e.printStackTrace();
+ log.debug("Data: " + json.toString());
+ }
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java
deleted file mode 100644
index 5ff95ddf39..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSProfile.java
+++ /dev/null
@@ -1,483 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.data;
-
-import android.support.annotation.Nullable;
-
-import com.crashlytics.android.Crashlytics;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.TimeZone;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.utils.DecimalFormatter;
-
-public class NSProfile {
- private static Logger log = LoggerFactory.getLogger(NSProfile.class);
-
- private JSONObject json = null;
- private String activeProfile = null;
-
- public NSProfile(JSONObject json, String activeProfile) {
- this.json = json;
- this.activeProfile = null;
- JSONObject store;
- try {
- store = json.getJSONObject("store");
- if (activeProfile != null && store.has(activeProfile)) {
- this.activeProfile = activeProfile;
- } else {
- log.error("Active profile not found in store");
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- public JSONObject getDefaultProfile() {
- String defaultProfileName = null;
- JSONObject store;
- JSONObject profile = null;
- try {
- defaultProfileName = (String) json.get("defaultProfile");
- store = json.getJSONObject("store");
- if (activeProfile != null && store.has(activeProfile)) {
- defaultProfileName = activeProfile;
- }
- profile = store.getJSONObject(defaultProfileName);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return profile;
- }
-
- public JSONObject getSpecificProfile(String profileName) {
- JSONObject profile = null;
- try {
- JSONObject store = json.getJSONObject("store");
- if (store.has(profileName)) {
- profile = store.getJSONObject(profileName);
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return profile;
- }
-
- public ArrayList getProfileList() {
- ArrayList ret = new ArrayList();
-
- JSONObject store;
- JSONObject profile = null;
- try {
- store = json.getJSONObject("store");
- Iterator> keys = store.keys();
-
- while (keys.hasNext()) {
- String profileName = (String) keys.next();
- ret.add(profileName);
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- return ret;
- }
-
- public String log() {
- String ret = "\n";
- for (Integer hour = 0; hour < 24; hour++) {
- double value = getBasal(hour * 60 * 60);
- ret += "NS basal value for " + hour + ":00 is " + value + "\n";
- }
- ret += "NS units: " + getUnits();
- return ret;
- }
-
- public JSONObject getData() {
- return json;
- }
-
- public Double getDia() {
- return getDia(getDefaultProfile());
- }
-
- public Double getDia(JSONObject profile) {
- Double dia;
- if (profile != null) {
- try {
- dia = profile.getDouble("dia");
- return dia;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 3D;
- }
-/*
- public Double getCarbAbsorbtionRate() {
- return getCarbAbsorbtionRate(getDefaultProfile());
- }
-
- public Double getCarbAbsorbtionRate(JSONObject profile) {
- Double carbAbsorptionRate;
- if (profile != null) {
- try {
- carbAbsorptionRate = profile.getDouble("carbs_hr");
- return carbAbsorptionRate;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 0D;
- }
-*/
- // mmol or mg/dl
- public String getUnits() {
- return getUnits(getDefaultProfile());
- }
-
- public String getUnits(JSONObject profile) {
- String units;
- if (profile != null) {
- try {
- units = profile.getString("units");
- return units.toLowerCase();
- } catch (JSONException e) {
- log.error("Profile not found. Failing over to main JSON");
- try {
- return json.getString("units").toLowerCase();
- } catch (JSONException e1) {
- e1.printStackTrace();
- Crashlytics.log("Profile failover failed too");
- }
- }
- }
- return Constants.MGDL;
- }
-
- public TimeZone getTimeZone() {
- return getTimeZone(getDefaultProfile());
- }
-
- public TimeZone getTimeZone(JSONObject profile) {
- TimeZone timeZone;
- if (profile != null) {
- try {
- return TimeZone.getTimeZone(profile.getString("timezone"));
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return TimeZone.getDefault();
- }
-
- @Nullable
- public Double getValueToTime(JSONArray array, Integer timeAsSeconds) {
- Double lastValue = null;
-
- for (Integer index = 0; index < array.length(); index++) {
- try {
- JSONObject o = array.getJSONObject(index);
- Integer tas = o.getInt("timeAsSeconds");
- Double value = o.getDouble("value");
- if (lastValue == null) lastValue = value;
- if (timeAsSeconds < tas) {
- break;
- }
- lastValue = value;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return lastValue;
- }
-
- public String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) {
- String retValue = "";
-
- for (Integer index = 0; index < array.length(); index++) {
- try {
- JSONObject o = array.getJSONObject(index);
- retValue += o.getString("time");
- retValue += " ";
- retValue += format.format(o.getDouble("value"));
- if (array2 != null) {
- JSONObject o2 = array2.getJSONObject(index);
- retValue += " - ";
- retValue += format.format(o2.getDouble("value"));
- }
- retValue += " " + units;
- retValue += "\n";
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return retValue;
- }
-
- @Nullable
- public Double getIsf(Integer timeAsSeconds) {
- return getIsf(getDefaultProfile(), timeAsSeconds);
- }
-
- @Nullable
- public Double getIsf(JSONObject profile, Integer timeAsSeconds) {
- if (profile != null) {
- try {
- return getValueToTime(profile.getJSONArray("sens"), timeAsSeconds);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 0D;
- }
-
- public String getIsfList() {
- return getIsfList(getDefaultProfile());
- }
-
- public String getIsfList(JSONObject profile) {
- if (profile != null) {
- try {
- return getValuesList(profile.getJSONArray("sens"), null, new DecimalFormat("0.0"), getUnits() + "/U");
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return "";
- }
-
- @Nullable
- public Double getIc(Integer timeAsSeconds) {
- return getIc(getDefaultProfile(), timeAsSeconds);
- }
-
- @Nullable
- public Double getIc(JSONObject profile, Integer timeAsSeconds) {
- if (profile != null) {
- try {
- return getValueToTime(profile.getJSONArray("carbratio"), timeAsSeconds);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 0D;
- }
-
- public String getIcList() {
- return getIcList(getDefaultProfile());
- }
-
- public String getIcList(JSONObject profile) {
- if (profile != null) {
- try {
- return getValuesList(profile.getJSONArray("carbratio"), null, new DecimalFormat("0.0"), "g");
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return "";
- }
-
- @Nullable
- public Double getBasal(Integer timeAsSeconds) {
- return getBasal(getDefaultProfile(), timeAsSeconds);
- }
-
- @Nullable
- public Double getBasal(JSONObject profile, Integer timeAsSeconds) {
- if (profile != null) {
- try {
- return getValueToTime(profile.getJSONArray("basal"), timeAsSeconds);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 0D;
- }
-
- public String getBasalList() {
- return getBasalList(getDefaultProfile());
- }
-
- public class BasalValue {
- public BasalValue(Integer timeAsSeconds, Double value) {
- this.timeAsSeconds = timeAsSeconds;
- this.value = value;
- }
-
- public Integer timeAsSeconds;
- public Double value;
- }
-
- public BasalValue[] getBasalValues() {
- try {
- JSONArray array = getDefaultProfile().getJSONArray("basal");
- BasalValue[] ret = new BasalValue[array.length()];
-
- for (Integer index = 0; index < array.length(); index++) {
- JSONObject o = array.getJSONObject(index);
- Integer tas = o.getInt("timeAsSeconds");
- Double value = o.getDouble("value");
- ret[index] = new BasalValue(tas, value);
- }
- return ret;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return new BasalValue[0];
- }
-
- public String getBasalList(JSONObject profile) {
- if (profile != null) {
- try {
- return getValuesList(profile.getJSONArray("basal"), null, new DecimalFormat("0.00"), "U");
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return "";
- }
-
- @Nullable
- public Double getTargetLow(Integer timeAsSeconds) {
- return getTargetLow(getDefaultProfile(), timeAsSeconds);
- }
-
- @Nullable
- public Double getTargetLow(JSONObject profile, Integer timeAsSeconds) {
- if (profile != null) {
- try {
- return getValueToTime(profile.getJSONArray("target_low"), timeAsSeconds);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 0D;
- }
-
- @Nullable
- public Double getTargetHigh(Integer timeAsSeconds) {
- return getTargetHigh(getDefaultProfile(), timeAsSeconds);
- }
-
- @Nullable
- public Double getTargetHigh(JSONObject profile, Integer timeAsSeconds) {
- if (profile != null) {
- try {
- return getValueToTime(profile.getJSONArray("target_high"), timeAsSeconds);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return 0D;
- }
-
- public String getTargetList() {
- return getTargetList(getDefaultProfile());
- }
-
- public String getTargetList(JSONObject profile) {
- if (profile != null) {
- try {
- return getValuesList(profile.getJSONArray("target_low"), profile.getJSONArray("target_high"), new DecimalFormat("0.0"), getUnits());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return "";
- }
-
- public String getActiveProfile() {
- if (activeProfile != null)
- return activeProfile;
- else {
- try {
- JSONObject store = json.getJSONObject("store");
- String defaultProfileName = (String) json.get("defaultProfile");
- if (store.has(defaultProfileName)) {
- return defaultProfileName;
- }
- log.error("Default profile not found");
- return null;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- public void setActiveProfile(String newProfile) {
- try {
- JSONObject store = json.getJSONObject("store");
- if (newProfile != null && store.has(newProfile)) {
- activeProfile = newProfile;
- } else {
- log.error("Attempt to set wrong active profile");
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- public Double getMaxDailyBasal() {
- Double max = 0d;
- for (Integer hour = 0; hour < 24; hour++) {
- double value = getBasal(hour * 60 * 60);
- if (value > max) max = value;
- }
- return max;
- }
-
- public static int secondsFromMidnight() {
- Calendar c = Calendar.getInstance();
- long now = c.getTimeInMillis();
- c.set(Calendar.HOUR_OF_DAY, 0);
- c.set(Calendar.MINUTE, 0);
- c.set(Calendar.SECOND, 0);
- c.set(Calendar.MILLISECOND, 0);
- long passed = now - c.getTimeInMillis();
- return (int) (passed / 1000);
- }
-
- public static int secondsFromMidnight(Date date) {
- Calendar c = Calendar.getInstance();
- long now = date.getTime();
- c.setTime(date);
- c.set(Calendar.HOUR_OF_DAY, 0);
- c.set(Calendar.MINUTE, 0);
- c.set(Calendar.SECOND, 0);
- c.set(Calendar.MILLISECOND, 0);
- long passed = now - c.getTimeInMillis();
- return (int) (passed / 1000);
- }
-
- public static Double toMgdl(Double value, String units) {
- if (units.equals(Constants.MGDL)) return value;
- else return value * Constants.MMOLL_TO_MGDL;
- }
-
- public static Double fromMgdlToUnits(Double value, String units) {
- if (units.equals(Constants.MGDL)) return value;
- else return value * Constants.MGDL_TO_MMOLL;
- }
-
- public static Double toUnits(Double valueInMgdl, Double valueInMmol, String units) {
- if (units.equals(Constants.MGDL)) return valueInMgdl;
- else return valueInMmol;
- }
-
- public static String toUnitsString(Double valueInMgdl, Double valueInMmol, String units) {
- if (units.equals(Constants.MGDL)) return DecimalFormatter.to0Decimal(valueInMgdl);
- else return DecimalFormatter.to1Decimal(valueInMmol);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java
index 44c6587fb1..91fca44d12 100644
--- 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
@@ -14,10 +14,12 @@ import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.db.DbRequest;
+import info.nightscout.utils.SP;
public class DBAccessReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(DBAccessReceiver.class);
@@ -32,6 +34,10 @@ public class DBAccessReceiver extends BroadcastReceiver {
if (!nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) {
return;
}
+ if (SP.getBoolean(R.string.key_ns_noupload, false)) {
+ log.debug("Upload disabled. Message dropped");
+ return;
+ }
wakeLock.acquire();
try {
Bundle bundles = intent.getExtras();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java
index c109873faa..901b29ad16 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java
@@ -3,13 +3,11 @@ 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;
@@ -25,22 +23,20 @@ import org.slf4j.LoggerFactory;
import java.net.URISyntaxException;
import java.sql.SQLException;
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.data.ProfileStore;
+import info.nightscout.androidaps.db.DbRequest;
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;
@@ -49,9 +45,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastP
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.db.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;
@@ -68,15 +62,14 @@ import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class NSClientService extends Service {
- private static Logger log = LoggerFactory.getLogger(ExecutionService.class);
+ private static Logger log = LoggerFactory.getLogger(NSClientService.class);
static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder();
- static NSProfile nsProfile;
+ static ProfileStore profileStore;
static public Handler handler;
- static private HandlerThread handlerThread;
public static Socket mSocket;
public static boolean isConnected = false;
@@ -92,11 +85,9 @@ public class NSClientService extends Service {
static public String nsURL = "";
private String nsAPISecret = "";
private String nsDevice = "";
- private Integer nsHours = 24;
+ private Integer nsHours = 48;
- private final Integer timeToWaitForResponseInMs = 30000;
- private boolean uploading = false;
- public Date lastReception = new Date();
+ public long lastResendTime = 0;
public long latestDateInReceivedData = 0;
@@ -107,7 +98,7 @@ public class NSClientService extends Service {
public NSClientService() {
registerBus();
if (handler == null) {
- handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler");
+ HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
@@ -180,14 +171,6 @@ public class NSClientService extends Service {
restart();
}
- public static void setNsProfile(NSProfile profile) {
- nsProfile = profile;
- }
-
- public static NSProfile getNsProfile() {
- return nsProfile;
- }
-
public void initialize() {
dataCounter = 0;
@@ -295,7 +278,6 @@ public class NSClientService extends Service {
} else {
MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
}
- lastReception = new Date();
}
public void readPreferences() {
@@ -318,7 +300,6 @@ public class NSClientService extends Service {
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() {
@@ -327,10 +308,8 @@ public class NSClientService extends Service {
"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
@@ -342,9 +321,7 @@ public class NSClientService extends Service {
JSONArray profiles = (JSONArray) data.getJSONArray("profiles");
if (profiles.length() > 0) {
JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1);
- String activeProfile = NSClientService.getNsProfile() == null ? null : NSClientService.getNsProfile().getActiveProfile();
- NSProfile nsProfile = new NSProfile(profile, activeProfile);
- NSClientService.setNsProfile(nsProfile);
+ profileStore = new ProfileStore(profile);
broadcastProfile = true;
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received"));
}
@@ -366,20 +343,6 @@ public class NSClientService extends Service {
BroadcastStatus bs = new BroadcastStatus();
bs.handleNewStatus(nsStatus, MainApp.instance().getApplicationContext(), isDelta);
- if (NSClientService.getNsProfile() != null) {
- String oldActiveProfile = NSClientService.getNsProfile().getActiveProfile();
- String receivedActiveProfile = nsStatus.getActiveProfile();
- NSClientService.getNsProfile().setActiveProfile(receivedActiveProfile);
- if (receivedActiveProfile != null) {
- MainApp.bus().post(new EventNSClientNewLog("PROFILE", "status activeProfile received: " + receivedActiveProfile));
- }
- // Change possible nulls to ""
- String oldP = oldActiveProfile == null ? "" : oldActiveProfile;
- String newP = receivedActiveProfile == null ? "" : receivedActiveProfile;
- if (!newP.equals(oldP)) {
- broadcastProfile = true;
- }
- }
/* Other received data to 2016/02/10
{
status: 'ok'
@@ -401,9 +364,9 @@ public class NSClientService extends Service {
}
// If new profile received or change detected broadcast it
- if (broadcastProfile && nsProfile != null) {
+ if (broadcastProfile && profileStore != null) {
BroadcastProfile bp = new BroadcastProfile();
- bp.handleNewTreatment(nsProfile, MainApp.instance().getApplicationContext(), isDelta);
+ bp.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta);
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting"));
}
@@ -427,12 +390,11 @@ public class NSClientService extends Service {
latestDateInReceivedData = treatment.getMills();
if (treatment.getAction() == null) {
- if (!isCurrent(treatment)) continue;
addedTreatments.put(jsonTreatment);
} else if (treatment.getAction().equals("update")) {
- if (!isCurrent(treatment)) continue;
updatedTreatments.put(jsonTreatment);
} else if (treatment.getAction().equals("remove")) {
+ if (treatment.getMills() != null && treatment.getMills() > new Date().getTime() - 24 * 60 * 60 * 1000L) // handle 1 day old deletions only
removedTreatments.put(jsonTreatment);
}
}
@@ -479,9 +441,6 @@ public class NSClientService extends Service {
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));
}
@@ -489,7 +448,6 @@ public class NSClientService extends Service {
}
if (data.has("sgvs")) {
BroadcastSgvs bs = new BroadcastSgvs();
- String units = nsProfile != null ? nsProfile.getUnits() : "mg/dl";
JSONArray sgvs = (JSONArray) data.getJSONArray("sgvs");
if (sgvs.length() > 0)
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
@@ -595,40 +553,6 @@ public class NSClientService extends Service {
}
}
- 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;
@@ -646,17 +570,22 @@ public class NSClientService extends Service {
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);
if (mSocket == null || !mSocket.connected()) return;
+ if (lastResendTime > new Date().getTime() - 10 * 1000L) {
+ log.debug("Skipping resend by lastResendTime: " + ((new Date().getTime() - lastResendTime) / 1000L) + " sec");
+ return;
+ }
+ lastResendTime = new Date().getTime();
+
+ MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
+
CloseableIterator iterator = null;
try {
- iterator = MainApp.getDbHelper().getDaoDbRequest().closeableIterator();
+ iterator = MainApp.getDbHelper().getDbRequestInterator();
try {
while (iterator.hasNext()) {
DbRequest dbr = iterator.next();
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
deleted file mode 100644
index b504dde984..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/Autosens.java
+++ /dev/null
@@ -1,255 +0,0 @@
-package info.nightscout.androidaps.plugins.OpenAPSAMA;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
-import info.nightscout.utils.Round;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.SafeParse;
-
-
-public class Autosens {
- private static Logger log = LoggerFactory.getLogger(Autosens.class);
-
- public static AutosensResult detectSensitivityandCarbAbsorption(List glucose_data, Long mealTime) {
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
-
- //console.error(mealTime);
-
- double deviationSum = 0;
- double carbsAbsorbed = 0;
-
- List bucketed_data = new ArrayList<>();
- bucketed_data.add(glucose_data.get(0));
- int j = 0;
- for (int i = 1; i < glucose_data.size(); ++i) {
- long bgTime = glucose_data.get(i).getTimeIndex();
- long lastbgTime = glucose_data.get(i - 1).getTimeIndex();
- //log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + glucose_data.get(i).value + " Previous: " + new Date(lastbgTime).toString() + " " + glucose_data.get(i - 1).value);
- if (glucose_data.get(i).value < 39 || glucose_data.get(i - 1).value < 39) {
- continue;
- }
-
- long elapsed_minutes = (bgTime - lastbgTime) / (60 * 1000);
- if (Math.abs(elapsed_minutes) > 8) {
- // interpolate missing data points
- double lastbg = glucose_data.get(i - 1).value;
- elapsed_minutes = Math.abs(elapsed_minutes);
- //console.error(elapsed_minutes);
- long nextbgTime;
- while (elapsed_minutes > 5) {
- nextbgTime = lastbgTime - 5 * 60 * 1000;
- j++;
- BgReading newBgreading = new BgReading();
- newBgreading.timeIndex = nextbgTime;
- double gapDelta = glucose_data.get(i).value - lastbg;
- //console.error(gapDelta, lastbg, elapsed_minutes);
- double nextbg = lastbg + (5d / elapsed_minutes * gapDelta);
- newBgreading.value = Math.round(nextbg);
- //console.error("Interpolated", bucketed_data[j]);
- bucketed_data.add(newBgreading);
- //log.error("******************************************************************************************************* Adding:" + new Date(newBgreading.timeIndex).toString() + " " + newBgreading.value);
-
- elapsed_minutes = elapsed_minutes - 5;
- lastbg = nextbg;
- lastbgTime = nextbgTime;
- }
- j++;
- BgReading newBgreading = new BgReading();
- newBgreading.value = glucose_data.get(i).value;
- newBgreading.timeIndex = bgTime;
- bucketed_data.add(newBgreading);
- //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.timeIndex).toString() + " " + newBgreading.value);
- } else if (Math.abs(elapsed_minutes) > 2) {
- j++;
- BgReading newBgreading = new BgReading();
- newBgreading.value = glucose_data.get(i).value;
- newBgreading.timeIndex = bgTime;
- bucketed_data.add(newBgreading);
- //log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.timeIndex).toString() + " " + newBgreading.value);
- } else {
- bucketed_data.get(j).value = (bucketed_data.get(j).value + glucose_data.get(i).value) / 2;
- //log.error("***** Average");
- }
- }
- //console.error(bucketed_data);
- double[] avgDeltas = new double[bucketed_data.size() - 2];
- double[] bgis = new double[bucketed_data.size() - 2];
- double[] deviations = new double[bucketed_data.size() - 2];
-
- String pastSensitivity = "";
- for (int i = 0; i < bucketed_data.size() - 3; ++i) {
- long bgTime = bucketed_data.get(i).timeIndex;
- int secondsFromMidnight = NSProfile.secondsFromMidnight(new Date(bgTime));
-
- String hour = "";
- //log.debug(new Date(bgTime).toString());
- if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) {
- hour += "(" + Math.round(secondsFromMidnight / 3600d) + ")";
- }
-
- double sens = NSProfile.toMgdl(profile.getIsf(secondsFromMidnight), profile.getUnits());
-
- //console.error(bgTime , bucketed_data[i].glucose);
- double bg;
- double avgDelta;
- double delta;
- bg = bucketed_data.get(i).value;
- if (bg < 40 || bucketed_data.get(i + 3).value < 40) {
- log.error("! value < 40");
- continue;
- }
- avgDelta = (bg - bucketed_data.get(i + 3).value) / 3;
- delta = (bg - bucketed_data.get(i + 1).value);
-
-// avgDelta = avgDelta.toFixed(2);
- IobTotal iob = IobTotal.calulateFromTreatmentsAndTemps(bgTime);
-
- double bgi = Math.round((-iob.activity * sens * 5) * 100) / 100d;
-// bgi = bgi.toFixed(2);
- //console.error(delta);
- double deviation = delta - bgi;
-// deviation = deviation.toFixed(2);
- //if (deviation < 0 && deviation > -2) { console.error("BG: "+bg+", avgDelta: "+avgDelta+", BGI: "+bgi+", deviation: "+deviation); }
-
- // Exclude large positive deviations (carb absorption) from autosens
- if (avgDelta - bgi < 6) {
- if (deviation > 0) {
- pastSensitivity += "+";
- } else if (deviation == 0) {
- pastSensitivity += "=";
- } else {
- pastSensitivity += "-";
- }
- avgDeltas[i] = avgDelta;
- bgis[i] = bgi;
- deviations[i] = deviation;
- deviationSum += deviation;
- } else {
- pastSensitivity += ">";
- //console.error(bgTime);
- }
- pastSensitivity += hour;
- //log.debug("TIME: " + new Date(bgTime).toString() + " BG: " + bg + " SENS: " + sens + " DELTA: " + delta + " AVGDELTA: " + avgDelta + " IOB: " + iob.iob + " ACTIVITY: " + iob.activity + " BGI: " + bgi + " DEVIATION: " + deviation);
-
- // if bgTime is more recent than mealTime
- 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, 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;
- }
- }
-
- double ratio = 1;
- String ratioLimit = "";
- String sensResult = "";
-
- if (mealTime == null) {
- //console.error("");
- log.debug(pastSensitivity);
- //console.log(JSON.stringify(avgDeltas));
- //console.log(JSON.stringify(bgis));
- Arrays.sort(avgDeltas);
- Arrays.sort(bgis);
- Arrays.sort(deviations);
-
- for (double i = 0.9; i > 0.1; i = i - 0.02) {
- //console.error("p="+i.toFixed(2)+": "+percentile(avgDeltas, i).toFixed(2)+", "+percentile(bgis, i).toFixed(2)+", "+percentile(deviations, i).toFixed(2));
- if (percentile(deviations, (i + 0.02)) >= 0 && percentile(deviations, i) < 0) {
- //console.error("p="+i.toFixed(2)+": "+percentile(avgDeltas, i).toFixed(2)+", "+percentile(bgis, i).toFixed(2)+", "+percentile(deviations, i).toFixed(2));
- log.debug(Math.round(100 * i) + "% of non-meal deviations negative (target 45%-50%)");
- }
- }
- double pSensitive = percentile(deviations, 0.50);
- double pResistant = percentile(deviations, 0.45);
- //p30 = percentile(deviations, 0.3);
-
-// average = deviationSum / deviations.length;
-
- //console.error("Mean deviation: "+average.toFixed(2));
- double basalOff = 0;
-
- if (pSensitive < 0) { // sensitive
- basalOff = pSensitive * (60 / 5) / NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()), profile.getUnits());
- sensResult = "Excess insulin sensitivity detected";
- } else if (pResistant > 0) { // resistant
- basalOff = pResistant * (60 / 5) / NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()), profile.getUnits());
- sensResult = "Excess insulin resistance detected";
- } else {
- sensResult = "Sensitivity normal";
- }
- log.debug(sensResult);
- ratio = 1 + (basalOff / profile.getMaxDailyBasal());
-
- // don't adjust more than 1.5x
- double rawRatio = ratio;
- ratio = Math.max(ratio, SafeParse.stringToDouble(SP.getString("openapsama_autosens_min", "0.7")));
- ratio = Math.min(ratio, SafeParse.stringToDouble(SP.getString("openapsama_autosens_max", "1.2")));
-
- if (ratio != rawRatio) {
- ratioLimit = "Ratio limited from " + rawRatio + " to " + ratio;
- log.debug(ratioLimit);
- }
-
- double newisf = Math.round(NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()), profile.getUnits()) / ratio);
- if (ratio != 1) {
- log.debug("ISF adjusted from " + NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()), profile.getUnits()) + " to " + newisf);
- }
- //console.error("Basal adjustment "+basalOff.toFixed(2)+"U/hr");
- //console.error("Ratio: "+ratio*100+"%: new ISF: "+newisf.toFixed(1)+"mg/dL/U");
- }
-
- AutosensResult output = new AutosensResult();
- output.ratio = Round.roundTo(ratio, 0.01);
- output.carbsAbsorbed = Round.roundTo(carbsAbsorbed, 0.01);
- output.pastSensitivity = pastSensitivity;
- output.ratioLimit = ratioLimit;
- output.sensResult = sensResult;
- return output;
- }
-
- // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2
- // Returns the value at a given percentile in a sorted numeric array.
- // "Linear interpolation between closest ranks" method
- public static double percentile(double[] arr, double p) {
- if (arr.length == 0) return 0;
- if (p <= 0) return arr[0];
- if (p >= 1) return arr[arr.length - 1];
-
- double index = arr.length * p,
- lower = Math.floor(index),
- upper = lower + 1,
- weight = index % 1;
-
- if (upper >= arr.length) return arr[(int) lower];
- return arr[(int) lower] * (1 - weight) + arr[(int) upper] * weight;
- }
-
- // Returns the percentile of the given value in a sorted numeric array.
- public static double percentRank(double[] arr, double v) {
- for (int i = 0, l = arr.length; i < l; i++) {
- if (v <= arr[i]) {
- while (i < l && v == arr[i]) i++;
- if (i == 0) return 0;
- if (v != arr[i - 1]) {
- i += (v - arr[i - 1]) / (arr[i] - arr[i - 1]);
- }
- return i / l;
- }
- }
- return 1;
- }
-
-}
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 f03a892cae..044374bc86 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java
@@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-
import com.eclipsesource.v8.JavaVoidCallback;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
@@ -14,18 +11,19 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
+import java.util.Date;
import info.nightscout.androidaps.Config;
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.Loop.ScriptReader;
import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.MealData;
+import info.nightscout.androidaps.db.TemporaryBasal;
+import info.nightscout.androidaps.interfaces.PumpInterface;
+import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.Loop.ScriptReader;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.SP;
-import info.nightscout.utils.SafeParse;
public class DetermineBasalAdapterAMAJS {
private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterAMAJS.class);
@@ -192,7 +190,7 @@ public class DetermineBasalAdapterAMAJS {
}
- public void setData(NSProfile profile,
+ public void setData(Profile profile,
double maxIob,
double maxBasal,
double minBg,
@@ -217,8 +215,8 @@ public class DetermineBasalAdapterAMAJS {
mProfile.add("min_bg", minBg);
mProfile.add("max_bg", maxBg);
mProfile.add("target_bg", targetBg);
- mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight()));
- mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units));
+ mProfile.add("carb_ratio", profile.getIc());
+ mProfile.add("sens", Profile.toMgdl(profile.getIsf().doubleValue(), units));
mProfile.add("max_daily_safety_multiplier", SP.getInt("openapsama_max_daily_safety_multiplier", 3));
mProfile.add("current_basal_safety_multiplier", SP.getInt("openapsama_current_basal_safety_multiplier", 4));
mProfile.add("skip_neutral_temps", true);
@@ -230,23 +228,28 @@ public class DetermineBasalAdapterAMAJS {
mCurrentTemp = new V8Object(mV8rt);
mCurrentTemp.add("temp", "absolute");
- mCurrentTemp.add("duration", pump.getTempBasalRemainingMinutes());
- mCurrentTemp.add("rate", pump.getTempBasalAbsoluteRate());
+ mCurrentTemp.add("duration", MainApp.getConfigBuilder().getTempBasalRemainingMinutesFromHistory());
+ mCurrentTemp.add("rate", MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory());
// as we have non default temps longer than 30 mintues
- TempBasal tempBasal = pump.getTempBasal();
- if(tempBasal != null){
+ TemporaryBasal tempBasal = MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime());
+ if (tempBasal != null) {
mCurrentTemp.add("minutesrunning", tempBasal.getRealDuration());
}
mV8rt.add(PARAM_currentTemp, mCurrentTemp);
- mIobData = mV8rt.executeArrayScript(IobTotal.convertToJSONArray(iobArray).toString());
+ mIobData = mV8rt.executeArrayScript(IobCobCalculatorPlugin.convertToJSONArray(iobArray).toString());
mV8rt.add(PARAM_iobData, mIobData);
mGlucoseStatus = new V8Object(mV8rt);
mGlucoseStatus.add("glucose", glucoseStatus.glucose);
- mGlucoseStatus.add("delta", glucoseStatus.delta);
+
+ if (SP.getBoolean("always_use_shortavg", false)) {
+ mGlucoseStatus.add("delta", glucoseStatus.short_avgdelta);
+ } else {
+ mGlucoseStatus.add("delta", glucoseStatus.delta);
+ }
mGlucoseStatus.add("short_avgdelta", glucoseStatus.short_avgdelta);
mGlucoseStatus.add("long_avgdelta", glucoseStatus.long_avgdelta);
mV8rt.add(PARAM_glucoseStatus, mGlucoseStatus);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java
index 652ec856bd..c086ff2cd5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java
@@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA;
-import android.os.Parcel;
-import android.os.Parcelable;
-
import com.eclipsesource.v8.V8Object;
import org.json.JSONArray;
@@ -102,7 +99,8 @@ public class DetermineBasalResultAMA extends APSResult {
for (int i = 1; i < iob.length(); i ++) {
BgReading bg = new BgReading();
bg.value = iob.getInt(i);
- bg.timeIndex = startTime + i * 5 * 60 * 1000L;
+ bg.date = startTime + i * 5 * 60 * 1000L;
+ bg.isPrediction = true;
array.add(bg);
}
}
@@ -111,7 +109,8 @@ public class DetermineBasalResultAMA extends APSResult {
for (int i = 1; i < iob.length(); i ++) {
BgReading bg = new BgReading();
bg.value = iob.getInt(i);
- bg.timeIndex = startTime + i * 5 * 60 * 1000L;
+ bg.date = startTime + i * 5 * 60 * 1000L;
+ bg.isPrediction = true;
array.add(bg);
}
}
@@ -120,7 +119,8 @@ public class DetermineBasalResultAMA extends APSResult {
for (int i = 1; i < iob.length(); i ++) {
BgReading bg = new BgReading();
bg.value = iob.getInt(i);
- bg.timeIndex = startTime + i * 5 * 60 * 1000L;
+ bg.date = startTime + i * 5 * 60 * 1000L;
+ bg.isPrediction = true;
array.add(bg);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java
index 76753e86a7..c480ebfe3c 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java
@@ -20,12 +20,11 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.JSONFormatter;
-public class OpenAPSAMAFragment extends Fragment implements View.OnClickListener, FragmentBase {
+public class OpenAPSAMAFragment extends Fragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(OpenAPSAMAFragment.class);
private static OpenAPSAMAPlugin openAPSAMAPlugin;
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 2cbffae52a..c39e9a78d3 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java
@@ -1,35 +1,32 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date;
-import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
+import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
-import info.nightscout.androidaps.db.BgReading;
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.plugins.IobCobCalculator.AutosensResult;
+import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.NSUpload;
import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
@@ -59,7 +56,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.oaps_shortname);
- if (!name.trim().isEmpty()){
+ if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
@@ -82,6 +79,16 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == APS) this.fragmentVisible = fragmentVisible;
@@ -125,7 +132,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
+ Profile profile = MainApp.getConfigBuilder().getProfile();
PumpInterface pump = MainApp.getConfigBuilder();
if (!isEnabled(PluginBase.APS)) {
@@ -142,20 +149,6 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
return;
}
- if (profile == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noprofile)));
- if (Config.logAPSResult)
- log.debug(MainApp.instance().getString(R.string.openapsma_noprofile));
- return;
- }
-
- if (pump == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_nopump)));
- if (Config.logAPSResult)
- log.debug(MainApp.instance().getString(R.string.openapsma_nopump));
- return;
- }
-
String units = profile.getUnits();
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
@@ -171,20 +164,20 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
- double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
- double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
- double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
+ double minBg = Profile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
+ double maxBg = Profile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
+ double targetBg = Profile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d);
Date start = new Date();
Date startPart = new Date();
- IobTotal[] iobArray = IobTotal.calculateIobArrayInDia();
+ IobTotal[] iobArray = IobCobCalculatorPlugin.calculateIobArrayInDia();
Profiler.log(log, "calculateIobArrayInDia()", startPart);
startPart = new Date();
- MealData mealData = MainApp.getConfigBuilder().getActiveTreatments().getMealData();
+ MealData mealData = MainApp.getConfigBuilder().getMealData();
Profiler.log(log, "getMealData()", startPart);
maxIob = MainApp.getConfigBuilder().applyMaxIOBConstraints(maxIob);
@@ -194,15 +187,12 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
targetBg = verifyHardLimits(targetBg, "targetBg", Constants.VERY_HARD_LIMIT_TARGET_BG[0], Constants.VERY_HARD_LIMIT_TARGET_BG[1]);
boolean isTempTarget = false;
- TempTargetRangePlugin tempTargetRangePlugin = (TempTargetRangePlugin) MainApp.getSpecificPlugin(TempTargetRangePlugin.class);
- if (tempTargetRangePlugin != null && tempTargetRangePlugin.isEnabled(PluginBase.GENERAL)) {
- TempTarget tempTarget = tempTargetRangePlugin.getTempTargetInProgress(new Date().getTime());
- if (tempTarget != null) {
- isTempTarget = true;
- minBg = verifyHardLimits(tempTarget.low, "minBg", Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
- maxBg = verifyHardLimits(tempTarget.high, "maxBg", Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
- targetBg = verifyHardLimits((tempTarget.low + tempTarget.high) / 2, "targetBg", Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
- }
+ TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
+ if (tempTarget != null) {
+ isTempTarget = true;
+ minBg = verifyHardLimits(tempTarget.low, "minBg", Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
+ maxBg = verifyHardLimits(tempTarget.high, "maxBg", Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
+ targetBg = verifyHardLimits((tempTarget.low + tempTarget.high) / 2, "targetBg", Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
}
@@ -210,20 +200,21 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
maxBasal = verifyHardLimits(maxBasal, "max_basal", 0.1, 10);
if (!checkOnlyHardLimits(profile.getDia(), "dia", 2, 7)) return;
- if (!checkOnlyHardLimits(profile.getIc(profile.secondsFromMidnight()), "carbratio", 2, 100)) return;
- if (!checkOnlyHardLimits(NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units), "sens", 2, 900)) return;
+ if (!checkOnlyHardLimits(profile.getIc(profile.secondsFromMidnight()), "carbratio", 2, 100))
+ return;
+ if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf().doubleValue(), units), "sens", 2, 900))
+ return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.1, 10)) return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, 5)) return;
- startPart = new Date();
- long oldestDataAvailable = MainApp.getConfigBuilder().getActiveTempBasals().oldestDataAvaialable();
- List bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(Math.max(oldestDataAvailable, (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + profile.getDia()))), false);
- log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString() + " (" + bgReadings.size() + " records)");
- Profiler.log(log, "getBgreadingsDataFromTime()", startPart);
+ long oldestDataAvailable = MainApp.getConfigBuilder().oldestDataAvailable();
+ long getBGDataFrom = Math.max(oldestDataAvailable, (long) (new Date().getTime() - 60 * 60 * 1000L * (24 + profile.getDia())));
+ log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString());
startPart = new Date();
- if(MainApp.getConfigBuilder().isAMAModeEnabled()){
- lastAutosensResult = Autosens.detectSensitivityandCarbAbsorption(bgReadings, null);
+ if (MainApp.getConfigBuilder().isAMAModeEnabled()) {
+ //lastAutosensResult = Autosens.detectSensitivityandCarbAbsorption(getBGDataFrom, null);
+ lastAutosensResult = IobCobCalculatorPlugin.detectSensitivity(getBGDataFrom);
} else {
lastAutosensResult = new AutosensResult();
}
@@ -235,7 +226,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
lastAutosensResult.ratio, //autosensDataRatio
isTempTarget,
SafeParse.stringToDouble(SP.getString("openapsama_min_5m_carbimpact", "3.0"))//min_5m_carbimpact
- );
+ );
DetermineBasalResultAMA determineBasalResultAMA = determineBasalAdapterAMAJS.invoke();
@@ -245,7 +236,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
determineBasalResultAMA.changeRequested = false;
// limit requests on openloop mode
if (!MainApp.getConfigBuilder().isClosedModeEnabled()) {
- if (MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResultAMA.rate - MainApp.getConfigBuilder().getTempBasalAbsoluteRate()) < 0.1)
+ if (MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResultAMA.rate - MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory()) < 0.1)
determineBasalResultAMA.changeRequested = false;
if (!MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResultAMA.rate - MainApp.getConfigBuilder().getBaseBasalRate()) < 0.1)
determineBasalResultAMA.changeRequested = false;
@@ -283,7 +274,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
msg += ".\n";
msg += String.format(MainApp.sResources.getString(R.string.openapsma_valuelimitedto), value, newvalue);
log.error(msg);
- MainApp.getConfigBuilder().uploadError(msg);
+ NSUpload.uploadError(msg);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error);
}
return newvalue;
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 75f87021c5..7df122fc92 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java
@@ -13,12 +13,14 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import info.nightscout.androidaps.Config;
+import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.utils.SP;
public class DetermineBasalAdapterMAJS {
private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterMAJS.class);
@@ -44,8 +46,8 @@ public class DetermineBasalAdapterMAJS {
private String storedProfile = null;
private String storedMeal_data = null;
- /**
- * Main code
+ /**
+ * Main code
*/
public DetermineBasalAdapterMAJS(ScriptReader scriptReader) throws IOException {
@@ -105,10 +107,10 @@ public class DetermineBasalAdapterMAJS {
mV8rt.executeVoidScript(
"console.error(\"determine_basal(\"+\n" +
"JSON.stringify(" + PARAM_glucoseStatus + ")+ \", \" +\n" +
- "JSON.stringify(" + PARAM_currentTemp + ")+ \", \" +\n" +
- "JSON.stringify(" + PARAM_iobData + ")+ \", \" +\n" +
- "JSON.stringify(" + PARAM_profile + ")+ \", \" +\n" +
- "JSON.stringify(" + PARAM_meal_data + ")+ \") \");"
+ "JSON.stringify(" + PARAM_currentTemp + ")+ \", \" +\n" +
+ "JSON.stringify(" + PARAM_iobData + ")+ \", \" +\n" +
+ "JSON.stringify(" + PARAM_profile + ")+ \", \" +\n" +
+ "JSON.stringify(" + PARAM_meal_data + ")+ \") \");"
);
mV8rt.executeVoidScript(
"var rT = determine_basal(" +
@@ -215,7 +217,7 @@ public class DetermineBasalAdapterMAJS {
}
- public void setData(NSProfile profile,
+ public void setData(Profile profile,
double maxIob,
double maxBasal,
double minBg,
@@ -236,12 +238,12 @@ public class DetermineBasalAdapterMAJS {
mProfile.add("min_bg", minBg);
mProfile.add("max_bg", maxBg);
mProfile.add("target_bg", targetBg);
- mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight()));
- mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units));
+ mProfile.add("carb_ratio", profile.getIc());
+ mProfile.add("sens", Profile.toMgdl(profile.getIsf().doubleValue(), units));
mProfile.add("current_basal", pump.getBaseBasalRate());
- mCurrentTemp.add("duration", pump.getTempBasalRemainingMinutes());
- mCurrentTemp.add("rate", pump.getTempBasalAbsoluteRate());
+ mCurrentTemp.add("duration", MainApp.getConfigBuilder().getTempBasalRemainingMinutesFromHistory());
+ mCurrentTemp.add("rate", MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory());
mIobData.add("iob", iobData.iob); //netIob
mIobData.add("activity", iobData.activity); //netActivity
@@ -251,7 +253,11 @@ public class DetermineBasalAdapterMAJS {
mIobData.add("hightempinsulin", iobData.hightempinsulin);
mGlucoseStatus.add("glucose", glucoseStatus.glucose);
- mGlucoseStatus.add("delta", glucoseStatus.delta);
+ if (SP.getBoolean("always_use_shortavg", false)) {
+ mGlucoseStatus.add("delta", glucoseStatus.short_avgdelta);
+ } else {
+ mGlucoseStatus.add("delta", glucoseStatus.delta);
+ }
mGlucoseStatus.add("avgdelta", glucoseStatus.avgdelta);
mMealData.add("carbs", mealData.carbs);
@@ -259,7 +265,7 @@ public class DetermineBasalAdapterMAJS {
}
- public void release() {
+ public void release() {
mProfile.release();
mCurrentTemp.release();
mIobData.release();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java
index bfe4bb5dab..16249dffc3 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java
@@ -18,18 +18,17 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.JSONFormatter;
-public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, FragmentBase {
+public class OpenAPSMAFragment extends Fragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class);
private static OpenAPSMAPlugin openAPSMAPlugin;
public static OpenAPSMAPlugin getPlugin() {
- if(openAPSMAPlugin==null){
+ if (openAPSMAPlugin == null) {
openAPSMAPlugin = new OpenAPSMAPlugin();
}
return openAPSMAPlugin;
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 c4b8f3e34a..11ea2de109 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java
@@ -18,14 +18,11 @@ 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.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.data.Profile;
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.utils.DateUtil;
import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round;
@@ -80,6 +77,16 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
return true;
}
+ @Override
+ public boolean hasFragment() {
+ return true;
+ }
+
+ @Override
+ public boolean showInList(int type) {
+ return true;
+ }
+
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == APS) this.fragmentVisible = fragmentVisible;
@@ -123,7 +130,7 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
+ Profile profile = MainApp.getConfigBuilder().getProfile();
PumpInterface pump = MainApp.getConfigBuilder();
if (!isEnabled(PluginBase.APS)) {
@@ -140,20 +147,6 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
return;
}
- if (profile == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noprofile)));
- if (Config.logAPSResult)
- log.debug(MainApp.instance().getString(R.string.openapsma_noprofile));
- return;
- }
-
- if (pump == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_nopump)));
- if (Config.logAPSResult)
- log.debug(MainApp.instance().getString(R.string.openapsma_nopump));
- return;
- }
-
String units = profile.getUnits();
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
@@ -169,24 +162,22 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
- double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
- double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
- double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
+ double minBg = Profile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
+ double maxBg = Profile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
+ double targetBg = Profile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d);
Date start = new Date();
- TreatmentsInterface treatments = MainApp.getConfigBuilder().getActiveTreatments();
- TempBasalsInterface tempBasals = MainApp.getConfigBuilder().getActiveTempBasals();
- treatments.updateTotalIOB();
- tempBasals.updateTotalIOB();
- IobTotal bolusIob = treatments.getLastCalculation();
- IobTotal basalIob = tempBasals.getLastCalculation();
+ MainApp.getConfigBuilder().updateTotalIOBTreatments();
+ MainApp.getConfigBuilder().updateTotalIOBTempBasals();
+ IobTotal bolusIob = MainApp.getConfigBuilder().getLastCalculationTreatments();
+ IobTotal basalIob = MainApp.getConfigBuilder().getLastCalculationTempBasals();
IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
- MealData mealData = treatments.getMealData();
+ MealData mealData = MainApp.getConfigBuilder().getMealData();
maxIob = MainApp.getConfigBuilder().applyMaxIOBConstraints(maxIob);
Profiler.log(log, "MA data gathering", start);
@@ -194,23 +185,20 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
minBg = verifyHardLimits(minBg, "minBg", Constants.VERY_HARD_LIMIT_MIN_BG[0], Constants.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", Constants.VERY_HARD_LIMIT_MAX_BG[0], Constants.VERY_HARD_LIMIT_MAX_BG[1]);
targetBg = verifyHardLimits(targetBg, "targetBg", Constants.VERY_HARD_LIMIT_TARGET_BG[0], Constants.VERY_HARD_LIMIT_TARGET_BG[1]);
-
- TempTargetRangePlugin tempTargetRangePlugin = (TempTargetRangePlugin) MainApp.getSpecificPlugin(TempTargetRangePlugin.class);
- if (tempTargetRangePlugin != null && tempTargetRangePlugin.isEnabled(PluginBase.GENERAL)) {
- TempTarget tempTarget = tempTargetRangePlugin.getTempTargetInProgress(new Date().getTime());
- if (tempTarget != null) {
- minBg = verifyHardLimits(tempTarget.low, "minBg", Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
- maxBg = verifyHardLimits(tempTarget.high, "maxBg", Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
- targetBg = verifyHardLimits((tempTarget.low + tempTarget.high) / 2, "targetBg", Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
- }
+
+ TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
+ if (tempTarget != null) {
+ minBg = verifyHardLimits(tempTarget.low, "minBg", Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
+ maxBg = verifyHardLimits(tempTarget.high, "maxBg", Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[0], Constants.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
+ targetBg = verifyHardLimits((tempTarget.low + tempTarget.high) / 2, "targetBg", Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], Constants.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
}
maxIob = verifyHardLimits(maxIob, "maxIob", 0, 7);
maxBasal = verifyHardLimits(maxBasal, "max_basal", 0.1, 10);
if (!checkOnlyHardLimits(profile.getDia(), "dia", 2, 7)) return;
- if (!checkOnlyHardLimits(profile.getIc(profile.secondsFromMidnight()), "carbratio", 2, 100)) return;
- if (!checkOnlyHardLimits(NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units), "sens", 2, 900)) return;
+ if (!checkOnlyHardLimits(profile.getIc(), "carbratio", 2, 100)) return;
+ if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf().doubleValue(), units), "sens", 2, 900)) return;
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.1, 10)) return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, 5)) return;
@@ -225,7 +213,7 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
determineBasalResultMA.changeRequested = false;
// limit requests on openloop mode
if (!MainApp.getConfigBuilder().isClosedModeEnabled()) {
- if (MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResultMA.rate - MainApp.getConfigBuilder().getTempBasalAbsoluteRate()) < 0.1)
+ if (MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResultMA.rate - MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory()) < 0.1)
determineBasalResultMA.changeRequested = false;
if (!MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResultMA.rate - MainApp.getConfigBuilder().getBaseBasalRate()) < 0.1)
determineBasalResultMA.changeRequested = false;
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 31ffa468d8..f536af5860 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
@@ -22,7 +22,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
-import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart;
+import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRBolusStart;
public class BolusProgressDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(BolusProgressDialog.class);
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 6ff9dceb1f..d1b25fff3a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java
@@ -24,8 +24,9 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.utils.PlusMinusEditText;
+import info.nightscout.utils.SafeParse;
import info.nightscout.utils.XdripCalibrations;
public class CalibrationDialog extends DialogFragment implements View.OnClickListener {
@@ -34,6 +35,7 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
Button okButton;
PlusMinusEditText bgText;
TextView unitsView;
+ TextView bgView;
Context context;
@@ -58,8 +60,8 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
okButton = (Button) view.findViewById(R.id.overview_calibration_okbutton);
okButton.setOnClickListener(this);
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- Double bg = profile != null ? NSProfile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()) : 0d;
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ Double bg = profile != null ? Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()) : 0d;
String units = Constants.MGDL;
if (profile != null)
@@ -72,6 +74,7 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
unitsView = (TextView) view.findViewById(R.id.overview_calibration_units);
unitsView.setText(units);
+ bgView = (TextView) view.findViewById(R.id.overview_calibration_bg);
return view;
}
@@ -80,7 +83,8 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
public void onClick(View view) {
switch (view.getId()) {
case R.id.overview_calibration_okbutton:
- final Double bg = bgText.getValue();
+ final Double bg = SafeParse.stringToDouble(this.bgView.getText().toString());
+ ;
XdripCalibrations.confirmAndSendCalibration(bg, context);
dismiss();
Answers.getInstance().logCustom(new CustomEvent("Calibration"));
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java
index a86740cdfd..352c158c1e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java
@@ -71,8 +71,7 @@ public class EditQuickWizardDialog extends DialogFragment implements View.OnClic
timeList.add(DateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60)));
ArrayAdapter adapter = new ArrayAdapter(getContext(),
- android.R.layout.simple_spinner_item, timeList);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ R.layout.spinner_centered, timeList);
fromSpinner.setAdapter(adapter);
toSpinner.setAdapter(adapter);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java
index ec25d2a0b0..9b6b7a0f45 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java
@@ -24,17 +24,16 @@ import java.text.DecimalFormat;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
+import info.nightscout.androidaps.db.CareportalEvent;
+import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SafeParse;
public class NewTreatmentDialog extends DialogFragment implements OnClickListener {
- Button deliverButton;
- TextView insulin;
- TextView carbs;
-
PlusMinusEditText editCarbs;
PlusMinusEditText editInsulin;
@@ -52,13 +51,11 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.overview_newtreatment_dialog, null, false);
- deliverButton = (Button) view.findViewById(R.id.treatments_newtreatment_deliverbutton);
+ view.findViewById(R.id.ok).setOnClickListener(this);
+ view.findViewById(R.id.cancel).setOnClickListener(this);
- deliverButton.setOnClickListener(this);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
- insulin = (TextView) view.findViewById(R.id.treatments_newtreatment_insulinamount);
- carbs = (TextView) view.findViewById(R.id.treatments_newtreatment_carbsamount);
Integer maxCarbs = MainApp.getConfigBuilder().applyCarbsConstraints(Constants.carbsOnlyForCheckLimit);
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
@@ -79,11 +76,11 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
@Override
public void onClick(View view) {
switch (view.getId()) {
- case R.id.treatments_newtreatment_deliverbutton:
+ case R.id.ok:
try {
- Double insulin = SafeParse.stringToDouble(this.insulin.getText().toString());
- Integer carbs = SafeParse.stringToInt(this.carbs.getText().toString());
+ Double insulin = SafeParse.stringToDouble(editInsulin.getText());
+ final Integer carbs = SafeParse.stringToInt(editCarbs.getText());
String confirmMessage = getString(R.string.entertreatmentquestion) + "\n";
@@ -95,8 +92,8 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
if (insulinAfterConstraints - insulin != 0 || carbsAfterConstraints != carbs)
confirmMessage += "\n" + getString(R.string.constraintapllied);
- final Double finalInsulinAfterConstraints = insulinAfterConstraints;
- final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
+ final double finalInsulinAfterConstraints = insulinAfterConstraints;
+ final int finalCarbsAfterConstraints = carbsAfterConstraints;
final Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
@@ -110,7 +107,14 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
mHandler.post(new Runnable() {
@Override
public void run() {
- PumpEnactResult result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints, context);
+ DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
+ if (finalInsulinAfterConstraints == 0) detailedBolusInfo.eventType = CareportalEvent.CARBCORRECTION;
+ if (finalCarbsAfterConstraints == 0) detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
+ detailedBolusInfo.insulin = finalInsulinAfterConstraints;
+ detailedBolusInfo.carbs = finalCarbsAfterConstraints;
+ detailedBolusInfo.context = context;
+ detailedBolusInfo.source = Source.USER;
+ PumpEnactResult result = pump.deliverTreatment(detailedBolusInfo);
if (!result.success) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
@@ -131,6 +135,9 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
e.printStackTrace();
}
break;
+ case R.id.cancel:
+ dismiss();
+ break;
}
}
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 eaebeec73e..5ba5f3a6f3 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
@@ -34,106 +34,69 @@ import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.w3c.dom.Text;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnCheckedChanged;
-import butterknife.OnClick;
-import butterknife.OnItemSelected;
-import butterknife.OnTextChanged;
-import butterknife.Unbinder;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
+import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
+import info.nightscout.androidaps.db.CareportalEvent;
+import info.nightscout.androidaps.db.DatabaseHelper;
+import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventRefreshGui;
-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.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
-import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA;
+import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.utils.OKDialog;
import info.nightscout.utils.PlusMinusEditText;
+import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
-import static butterknife.OnItemSelected.Callback.NOTHING_SELECTED;
-
-public class WizardDialog extends DialogFragment {
+public class WizardDialog extends DialogFragment implements OnClickListener, CompoundButton.OnCheckedChangeListener, Spinner.OnItemSelectedListener {
private static Logger log = LoggerFactory.getLogger(WizardDialog.class);
- @BindView(R.id.treatments_wizard_deliverButton)
Button wizardDialogDeliverButton;
- @BindView(R.id.treatments_wizard_correctioninput)
TextView correctionInput;
- @BindView(R.id.treatments_wizard_carbsinput)
TextView carbsInput;
- @BindView(R.id.treatments_wizard_bginput)
TextView bgInput;
- @BindView(R.id.treatments_wizard_bg)
TextView bg;
- @BindView(R.id.treatments_wizard_bginsulin)
TextView bgInsulin;
- @BindView(R.id.treatments_wizard_bgunits)
TextView bgUnits;
- @BindView(R.id.treatments_wizard_bgcheckbox)
CheckBox bgCheckbox;
- @BindView(R.id.treatments_wizard_carbs)
TextView carbs;
- @BindView(R.id.treatments_wizard_carbsinsulin)
TextView carbsInsulin;
- @BindView(R.id.treatments_wizard_bolusiobinsulin)
TextView bolusIobInsulin;
- @BindView(R.id.treatments_wizard_basaliobinsulin)
TextView basalIobInsulin;
- @BindView(R.id.treatments_wizard_bolusiobcheckbox)
CheckBox bolusIobCheckbox;
- @BindView(R.id.treatments_wizard_basaliobcheckbox)
CheckBox basalIobCheckbox;
- @BindView(R.id.treatments_wizard_correctioninsulin)
TextView correctionInsulin;
- @BindView(R.id.treatments_wizard_total)
TextView total;
- @BindView(R.id.treatments_wizard_totalinsulin)
TextView totalInsulin;
- @BindView(R.id.treatments_wizard_carbtimeinput)
EditText carbTimeEdit;
- @BindView(R.id.treatments_wizard_profile)
Spinner profileSpinner;
- @BindView(R.id.treatments_wizard_sbcheckbox)
CheckBox superbolusCheckbox;
- @BindView(R.id.treatments_wizard_sb)
TextView superbolus;
- @BindView(R.id.treatments_wizard_sbinsulin)
TextView superbolusInsulin;
- @BindView(R.id.treatments_wizard_bgtrendcheckbox)
CheckBox bgtrendCheckbox;
- @BindView(R.id.treatments_wizard_bgtrend)
TextView bgTrend;
- @BindView(R.id.treatments_wizard_bgtrendinsulin)
TextView bgTrendInsulin;
- @BindView(R.id.treatments_wizard_cob_layout)
LinearLayout cobLayout;
- @BindView(R.id.treatments_wizard_cobcheckbox)
CheckBox cobCheckbox;
- @BindView(R.id.treatments_wizard_cob)
TextView cob;
- @BindView(R.id.treatments_wizard_cobinsulin)
TextView cobInsulin;
PlusMinusEditText editBg;
@@ -141,8 +104,6 @@ public class WizardDialog extends DialogFragment {
PlusMinusEditText editCorr;
PlusMinusEditText editCarbTime;
- private Unbinder unbinder;
-
Integer calculatedCarbs = 0;
Double calculatedTotalInsulin = 0d;
JSONObject boluscalcJSON;
@@ -166,12 +127,6 @@ public class WizardDialog extends DialogFragment {
this.context = context;
}
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- unbinder.unbind();
- }
-
@Override
public void onResume() {
super.onResume();
@@ -240,12 +195,56 @@ public class WizardDialog extends DialogFragment {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
- unbinder = ButterKnife.bind(this, view);
+ wizardDialogDeliverButton = (Button) view.findViewById(R.id.treatments_wizard_deliverButton);
+ wizardDialogDeliverButton.setOnClickListener(this);
+ bg = (TextView) view.findViewById(R.id.treatments_wizard_bg);
+ bgInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bginsulin);
+ bgUnits = (TextView) view.findViewById(R.id.treatments_wizard_bgunits);
+ carbs = (TextView) view.findViewById(R.id.treatments_wizard_carbs);
+ carbsInsulin = (TextView) view.findViewById(R.id.treatments_wizard_carbsinsulin);
+ bolusIobInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bolusiobinsulin);
+ basalIobInsulin = (TextView) view.findViewById(R.id.treatments_wizard_basaliobinsulin);
+ correctionInsulin = (TextView) view.findViewById(R.id.treatments_wizard_correctioninsulin);
+ total = (TextView) view.findViewById(R.id.treatments_wizard_total);
+ totalInsulin = (TextView) view.findViewById(R.id.treatments_wizard_totalinsulin);
+ carbTimeEdit = (EditText) view.findViewById(R.id.treatments_wizard_carbtimeinput);
+ superbolus = (TextView) view.findViewById(R.id.treatments_wizard_sb);
+ superbolusInsulin = (TextView) view.findViewById(R.id.treatments_wizard_sbinsulin);
+
+ bgTrend = (TextView) view.findViewById(R.id.treatments_wizard_bgtrend);
+ bgTrendInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bgtrendinsulin);
+ cobLayout = (LinearLayout) view.findViewById(R.id.treatments_wizard_cob_layout);
+ cob = (TextView) view.findViewById(R.id.treatments_wizard_cob);
+ ;
+ cobInsulin = (TextView) view.findViewById(R.id.treatments_wizard_cobinsulin);
+ ;
+
+ bgCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_bgcheckbox);
+ bolusIobCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_bolusiobcheckbox);
+ basalIobCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_basaliobcheckbox);
+ superbolusCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_sbcheckbox);
+ bgtrendCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_bgtrendcheckbox);
+ cobCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_cobcheckbox);
+ bgCheckbox.setOnCheckedChangeListener(this);
+ basalIobCheckbox.setOnCheckedChangeListener(this);
+ bolusIobCheckbox.setOnCheckedChangeListener(this);
+ superbolusCheckbox.setOnCheckedChangeListener(this);
+ bgtrendCheckbox.setOnCheckedChangeListener(this);
+ cobCheckbox.setOnCheckedChangeListener(this);
+
+ profileSpinner = (Spinner) view.findViewById(R.id.treatments_wizard_profile);
+ profileSpinner.setOnItemSelectedListener(this);
+
+ correctionInput = (TextView) view.findViewById(R.id.treatments_wizard_correctioninput);
+ carbsInput = (TextView) view.findViewById(R.id.treatments_wizard_carbsinput);
+ bgInput = (TextView) view.findViewById(R.id.treatments_wizard_bginput);
correctionInput.addTextChangedListener(textWatcher);
carbsInput.addTextChangedListener(textWatcher);
bgInput.addTextChangedListener(textWatcher);
+ superbolusCheckbox.setVisibility(SP.getBoolean(R.string.key_usesuperbolus, false) ? View.VISIBLE : View.GONE);
+
Integer maxCarbs = MainApp.getConfigBuilder().applyCarbsConstraints(Constants.carbsOnlyForCheckLimit);
Double maxCorrection = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
@@ -258,106 +257,105 @@ public class WizardDialog extends DialogFragment {
return view;
}
- @OnCheckedChanged({R.id.treatments_wizard_bgcheckbox, R.id.treatments_wizard_bolusiobcheckbox, R.id.treatments_wizard_basaliobcheckbox, R.id.treatments_wizard_sbcheckbox, R.id.treatments_wizard_cobcheckbox, R.id.treatments_wizard_bgtrendcheckbox})
- public void checkboxToggled(boolean isChecked) {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
calculateInsulin();
}
- @OnItemSelected(R.id.treatments_wizard_profile)
- public void profileSelected(int position) {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
calculateInsulin();
wizardDialogDeliverButton.setVisibility(View.VISIBLE);
}
- @OnItemSelected(value = R.id.treatments_wizard_profile,
- callback = NOTHING_SELECTED)
- public void profileNotSelected() {
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
ToastUtils.showToastInUiThread(context, MainApp.sResources.getString(R.string.noprofileselected));
wizardDialogDeliverButton.setVisibility(View.GONE);
}
- @OnClick(R.id.treatments_wizard_deliverButton)
+ @Override
public void onClick(View view) {
- if (calculatedTotalInsulin > 0d || calculatedCarbs > 0d) {
- DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
- String confirmMessage = getString(R.string.entertreatmentquestion);
+ switch (view.getId()) {
+ case R.id.treatments_wizard_deliverButton:
+ if (calculatedTotalInsulin > 0d || calculatedCarbs > 0d) {
+ DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
+ String confirmMessage = getString(R.string.entertreatmentquestion);
- Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(calculatedTotalInsulin);
- Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(calculatedCarbs);
+ Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(calculatedTotalInsulin);
+ Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(calculatedCarbs);
- confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
- confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g";
+ confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
+ confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g";
- if (insulinAfterConstraints - calculatedTotalInsulin != 0 || !carbsAfterConstraints.equals(calculatedCarbs)) {
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
- builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput));
- builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
- builder.show();
- return;
- }
-
- final Double finalInsulinAfterConstraints = insulinAfterConstraints;
- final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
- final Double bg = SafeParse.stringToDouble(bgInput.getText().toString());
- final int carbTime = SafeParse.stringToInt(carbTimeEdit.getText().toString());
- final boolean useSuperBolus = superbolusCheckbox.isChecked();
-
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
- builder.setMessage(confirmMessage);
- builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
- final ConfigBuilderPlugin pump = MainApp.getConfigBuilder();
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- PumpEnactResult result = pump.deliverTreatmentFromBolusWizard(
- context,
- finalInsulinAfterConstraints,
- finalCarbsAfterConstraints,
- bg,
- "Manual",
- carbTime,
- boluscalcJSON
- );
- if (!result.success) {
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
- builder.setMessage(result.comment);
- builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
- builder.show();
- }
- if (useSuperBolus) {
- final LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
- result = pump.setTempBasalAbsolute(0d, 120);
- if (!result.success) {
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
- builder.setMessage(result.comment);
- builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
- builder.show();
- }
- if (activeloop != null) {
- activeloop.superBolusTo(new Date().getTime() + 2 * 60L * 60 * 1000);
- MainApp.bus().post(new EventRefreshGui(false));
- }
- }
- }
- });
- Answers.getInstance().logCustom(new CustomEvent("Wizard"));
+ if (insulinAfterConstraints - calculatedTotalInsulin != 0 || !carbsAfterConstraints.equals(calculatedCarbs)) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(context);
+ builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
+ builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput));
+ builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
+ builder.show();
+ return;
}
+
+ final Double finalInsulinAfterConstraints = insulinAfterConstraints;
+ final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
+ final Double bg = SafeParse.stringToDouble(bgInput.getText().toString());
+ final int carbTime = SafeParse.stringToInt(carbTimeEdit.getText().toString());
+ final boolean useSuperBolus = superbolusCheckbox.isChecked();
+
+ AlertDialog.Builder builder = new AlertDialog.Builder(context);
+ builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
+ builder.setMessage(confirmMessage);
+ builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
+ final ConfigBuilderPlugin pump = MainApp.getConfigBuilder();
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ PumpEnactResult result;
+ if (useSuperBolus) {
+ final LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
+ if (activeloop != null) {
+ activeloop.superBolusTo(new Date().getTime() + 2 * 60L * 60 * 1000);
+ MainApp.bus().post(new EventRefreshGui(false));
+ }
+ result = pump.setTempBasalAbsolute(0d, 120);
+ if (!result.success) {
+ OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror), result.comment, null);
+ }
+ }
+ DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
+ detailedBolusInfo.eventType = CareportalEvent.BOLUSWIZARD;
+ detailedBolusInfo.insulin = finalInsulinAfterConstraints;
+ detailedBolusInfo.carbs = finalCarbsAfterConstraints;
+ detailedBolusInfo.context = context;
+ detailedBolusInfo.glucose = bg;
+ detailedBolusInfo.glucoseType = "Manual";
+ detailedBolusInfo.carbTime = carbTime;
+ detailedBolusInfo.boluscalc = boluscalcJSON;
+ detailedBolusInfo.source = Source.USER;
+ result = pump.deliverTreatment(detailedBolusInfo);
+ if (!result.success) {
+ OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.treatmentdeliveryerror), result.comment, null);
+ }
+ }
+ });
+ Answers.getInstance().logCustom(new CustomEvent("Wizard"));
+ }
+ }
+ });
+ builder.setNegativeButton(getString(R.string.cancel), null);
+ builder.show();
+ dismiss();
}
- });
- builder.setNegativeButton(getString(R.string.cancel), null);
- builder.show();
- dismiss();
+ break;
}
}
private void initDialog() {
- NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile));
@@ -365,14 +363,14 @@ public class WizardDialog extends DialogFragment {
}
ArrayList profileList;
- profileList = profile.getProfileList();
+ profileList = profileStore.getProfileList();
ArrayAdapter adapter = new ArrayAdapter(getContext(),
- android.R.layout.simple_spinner_item, profileList);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ R.layout.spinner_centered, profileList);
+
profileSpinner.setAdapter(adapter);
// set selected to actual profile
for (int p = 0; p < profileList.size(); p++) {
- if (profileList.get(p).equals(profile.getActiveProfile()))
+ if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName()))
profileSpinner.setSelection(p);
}
@@ -382,13 +380,13 @@ public class WizardDialog extends DialogFragment {
else editBg.setStep(0.1d);
// Set BG if not old
- BgReading lastBg = GlucoseStatus.actualBg();
+ BgReading lastBg = DatabaseHelper.actualBg();
if (lastBg != null) {
Double lastBgValue = lastBg.valueToUnits(units);
- Double sens = profile.getIsf(NSProfile.secondsFromMidnight());
- Double targetBGLow = profile.getTargetLow(NSProfile.secondsFromMidnight());
- Double targetBGHigh = profile.getTargetHigh(NSProfile.secondsFromMidnight());
+ Double sens = profile.getIsf();
+ Double targetBGLow = profile.getTargetLow();
+ Double targetBGHigh = profile.getTargetHigh();
Double bgDiff;
if (lastBgValue <= targetBGLow) {
bgDiff = lastBgValue - targetBGLow;
@@ -412,15 +410,10 @@ public class WizardDialog extends DialogFragment {
}
// IOB calculation
- TreatmentsInterface treatments = ConfigBuilderPlugin.getActiveTreatments();
- treatments.updateTotalIOB();
- IobTotal bolusIob = treatments.getLastCalculation();
- TempBasalsInterface tempBasals = ConfigBuilderPlugin.getActiveTempBasals();
- IobTotal basalIob = new IobTotal(new Date().getTime());
- if (tempBasals != null) {
- tempBasals.updateTotalIOB();
- basalIob = tempBasals.getLastCalculation().round();
- }
+ MainApp.getConfigBuilder().updateTotalIOBTreatments();
+ IobTotal bolusIob = MainApp.getConfigBuilder().getLastCalculationTreatments().round();
+ MainApp.getConfigBuilder().updateTotalIOBTempBasals();
+ IobTotal basalIob = MainApp.getConfigBuilder().getLastCalculationTempBasals().round();
bolusIobInsulin.setText(DecimalFormatter.to2Decimal(-bolusIob.iob) + "U");
basalIobInsulin.setText(DecimalFormatter.to2Decimal(-basalIob.basaliob) + "U");
@@ -439,11 +432,11 @@ public class WizardDialog extends DialogFragment {
}
private void calculateInsulin() {
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
+ ProfileStore profile = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profileSpinner == null || profileSpinner.getSelectedItem() == null)
return; // not initialized yet
String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString();
- JSONObject specificProfile = profile.getSpecificProfile(selectedAlternativeProfile);
+ Profile specificProfile = profile.getSpecificProfile(selectedAlternativeProfile);
// Entered values
Double c_bg = SafeParse.stringToDouble(bgInput.getText().toString());
@@ -517,7 +510,7 @@ public class WizardDialog extends DialogFragment {
// Trend
if (bgtrendCheckbox.isChecked()) {
if (wizard.glucoseStatus != null) {
- bgTrend.setText((wizard.glucoseStatus.avgdelta > 0 ? "+" : "") + NSProfile.toUnitsString(wizard.glucoseStatus.avgdelta * 3, wizard.glucoseStatus.avgdelta * 3 / 18, profile.getUnits()) + " " + profile.getUnits());
+ bgTrend.setText((wizard.glucoseStatus.avgdelta > 0 ? "+" : "") + Profile.toUnitsString(wizard.glucoseStatus.avgdelta * 3, wizard.glucoseStatus.avgdelta * 3 / 18, specificProfile.getUnits()) + " " + specificProfile.getUnits());
} else {
bgTrend.setText("");
}
@@ -571,4 +564,5 @@ public class WizardDialog extends DialogFragment {
e.printStackTrace();
}
}
+
}
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 0508917312..c9a80dbaef 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,7 +23,13 @@ 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 static final int NSCLIENT_NO_WRITE_PERMISSION = 11;
+ public static final int MISSING_SMS_PERMISSION = 12;
+ public static final int ISF_MISSING = 13;
+ public static final int IC_MISSING = 14;
+ public static final int BASAL_MISSING = 15;
+ public static final int TARGET_MISSING = 16;
+ public static final int ANNOUNCEMENT = 17;
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 22d5e48b57..7d81f307a2 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
@@ -2,15 +2,15 @@ package info.nightscout.androidaps.plugins.Overview;
import android.annotation.SuppressLint;
import android.app.Activity;
+import android.app.NotificationManager;
+import android.content.Context;
import android.content.DialogInterface;
-import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
-import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
@@ -18,6 +18,8 @@ import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
@@ -33,11 +35,13 @@ import android.widget.TextView;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.jjoe64.graphview.GraphView;
+import com.jjoe64.graphview.LabelFormatter;
import com.jjoe64.graphview.ValueDependentColor;
+import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
-import com.jjoe64.graphview.series.PointsGraphSeries;
+import com.jjoe64.graphview.series.Series;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
@@ -51,34 +55,51 @@ import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.TempBasal;
+import info.nightscout.androidaps.db.CareportalEvent;
+import info.nightscout.androidaps.db.DatabaseHelper;
+import info.nightscout.androidaps.db.ExtendedBolus;
+import info.nightscout.androidaps.db.ProfileSwitch;
+import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
+import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.events.EventCareportalEventChange;
+import info.nightscout.androidaps.events.EventExtendedBolusChange;
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.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
+import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
+import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
+import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.IobCobCalculator.events.BasalData;
+import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
-import info.nightscout.androidaps.plugins.Objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
@@ -86,21 +107,24 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.NewTreatmentDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.WizardDialog;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.AreaGraphSeries;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.DoubleDataPoint;
+import info.nightscout.androidaps.plugins.Overview.graphExtensions.FixedLineGraphSeries;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.TimeAsXAxisLabelFormatter;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
-import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
-import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange;
-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.NSUpload;
+import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
-public class OverviewFragment extends Fragment {
+public class OverviewFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static Logger log = LoggerFactory.getLogger(OverviewFragment.class);
private static OverviewPlugin overviewPlugin = new OverviewPlugin();
@@ -109,28 +133,41 @@ public class OverviewFragment extends Fragment {
return overviewPlugin;
}
+ TextView timeView;
TextView bgView;
TextView arrowView;
TextView timeAgoView;
TextView deltaView;
TextView avgdeltaView;
- TextView runningTempView;
TextView baseBasalView;
- LinearLayout basalLayout;
+ TextView extendedBolusView;
TextView activeProfileView;
TextView iobView;
+ TextView cobView;
TextView apsModeView;
TextView tempTargetView;
TextView pumpStatusView;
LinearLayout loopStatusLayout;
LinearLayout pumpStatusLayout;
GraphView bgGraph;
+ GraphView iobGraph;
+
+ TextView iage;
+ TextView cage;
+ TextView sage;
+ TextView pbage;
+
+ TextView updating;
+
CheckBox showPredictionView;
+ CheckBox showBasalsView;
+ CheckBox showIobView;
+ CheckBox showCobView;
+ CheckBox showDeviationsView;
RecyclerView notificationsView;
LinearLayoutManager llm;
- LinearLayout cancelTempLayout;
LinearLayout acceptTempLayout;
Button cancelTempButton;
Button treatmentButton;
@@ -139,12 +176,21 @@ public class OverviewFragment extends Fragment {
Button acceptTempButton;
Button quickWizardButton;
+ boolean smallWidth;
+ boolean smallHeight;
+
+
+ private int rangeToDisplay = 6; // for graph
+
Handler sLoopHandler = new Handler();
Runnable sRefreshLoop = null;
private static Handler sHandler;
private static HandlerThread sHandlerThread;
+ private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
+ private static ScheduledFuture> scheduledUpdate = null;
+
public OverviewFragment() {
super();
if (sHandlerThread == null) {
@@ -158,167 +204,134 @@ public class OverviewFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.overview_fragment, container, false);
+ //check screen width
+ final DisplayMetrics dm = new DisplayMetrics();
+ getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
+ int screen_width = dm.widthPixels;
+ int screen_height = dm.heightPixels;
+ smallWidth = screen_width < Constants.SMALL_WIDTH;
+ smallHeight = screen_height < Constants.SMALL_HEIGHT;
+
+ View view;
+
+ if (MainApp.sResources.getBoolean(R.bool.isTablet)) {
+ view = inflater.inflate(R.layout.overview_fragment_tablet, container, false);
+ } else if (smallHeight) {
+ view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false);
+ } else {
+ view = inflater.inflate(R.layout.overview_fragment, container, false);
+ }
+
+ timeView = (TextView) view.findViewById(R.id.overview_time);
bgView = (TextView) view.findViewById(R.id.overview_bg);
arrowView = (TextView) view.findViewById(R.id.overview_arrow);
+ if (smallWidth) {
+ arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35);
+ }
timeAgoView = (TextView) view.findViewById(R.id.overview_timeago);
deltaView = (TextView) view.findViewById(R.id.overview_delta);
avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta);
- runningTempView = (TextView) view.findViewById(R.id.overview_runningtemp);
baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal);
- basalLayout = (LinearLayout) view.findViewById(R.id.overview_basallayout);
+ extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus);
activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile);
pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus);
loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout);
pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout);
+ pumpStatusView.setBackgroundColor(MainApp.sResources.getColor(R.color.colorInitializingBorder));
+
iobView = (TextView) view.findViewById(R.id.overview_iob);
+ cobView = (TextView) view.findViewById(R.id.overview_cob);
apsModeView = (TextView) view.findViewById(R.id.overview_apsmode);
tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget);
+
+ iage = (TextView) view.findViewById(R.id.careportal_insulinage);
+ cage = (TextView) view.findViewById(R.id.careportal_canulaage);
+ sage = (TextView) view.findViewById(R.id.careportal_sensorage);
+ pbage = (TextView) view.findViewById(R.id.careportal_pbage);
+
+ updating = (TextView) view.findViewById(R.id.overview_updating);
+
bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph);
- cancelTempButton = (Button) view.findViewById(R.id.overview_canceltemp);
- treatmentButton = (Button) view.findViewById(R.id.overview_treatment);
- wizardButton = (Button) view.findViewById(R.id.overview_wizard);
- cancelTempButton = (Button) view.findViewById(R.id.overview_canceltemp);
- cancelTempLayout = (LinearLayout) view.findViewById(R.id.overview_canceltemplayout);
+ iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph);
+
+ cancelTempButton = (Button) view.findViewById(R.id.overview_canceltempbutton);
+ cancelTempButton.setOnClickListener(this);
+ treatmentButton = (Button) view.findViewById(R.id.overview_treatmentbutton);
+ treatmentButton.setOnClickListener(this);
+ wizardButton = (Button) view.findViewById(R.id.overview_wizardbutton);
+ wizardButton.setOnClickListener(this);
acceptTempButton = (Button) view.findViewById(R.id.overview_accepttempbutton);
+ acceptTempButton.setOnClickListener(this);
+ quickWizardButton = (Button) view.findViewById(R.id.overview_quickwizardbutton);
+ quickWizardButton.setOnClickListener(this);
+ calibrationButton = (Button) view.findViewById(R.id.overview_calibrationbutton);
+ calibrationButton.setOnClickListener(this);
+
acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout);
- quickWizardButton = (Button) view.findViewById(R.id.overview_quickwizard);
- calibrationButton = (Button) view.findViewById(R.id.overview_calibration);
+
showPredictionView = (CheckBox) view.findViewById(R.id.overview_showprediction);
+ showBasalsView = (CheckBox) view.findViewById(R.id.overview_showbasals);
+ showIobView = (CheckBox) view.findViewById(R.id.overview_showiob);
+ showCobView = (CheckBox) view.findViewById(R.id.overview_showcob);
+ showDeviationsView = (CheckBox) view.findViewById(R.id.overview_showdeviations);
+ showPredictionView.setChecked(SP.getBoolean("showprediction", false));
+ showBasalsView.setChecked(SP.getBoolean("showbasals", true));
+ showIobView.setChecked(SP.getBoolean("showiob", false));
+ showCobView.setChecked(SP.getBoolean("showcob", false));
+ showDeviationsView.setChecked(SP.getBoolean("showdeviations", false));
+ showPredictionView.setOnCheckedChangeListener(this);
+ showBasalsView.setOnCheckedChangeListener(this);
+ showIobView.setOnCheckedChangeListener(this);
+ showCobView.setOnCheckedChangeListener(this);
+ showDeviationsView.setOnCheckedChangeListener(this);
notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications);
notificationsView.setHasFixedSize(true);
llm = new LinearLayoutManager(view.getContext());
notificationsView.setLayoutManager(llm);
-
- showPredictionView.setChecked(SP.getBoolean("showprediction", false));
-
- showPredictionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+/*
+ final LinearLayout graphs = (LinearLayout)view.findViewById(R.id.overview_graphs_layout);
+ ViewTreeObserver observer = graphs.getViewTreeObserver();
+ observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putBoolean("showprediction", showPredictionView.isChecked());
- editor.apply();
- updateGUI();
+ public void onGlobalLayout() {
+ log.debug("Height: " + graphs.getHeight());
+ graphs.getViewTreeObserver().removeGlobalOnLayoutListener(
+ this);
+ int heightNeeded = Math.max(320, graphs.getHeight() - 200);
+ if (heightNeeded != bgGraph.getHeight())
+ bgGraph.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, heightNeeded));
+ }
+ });
+*/
+ bgGraph.getGridLabelRenderer().setGridColor(MainApp.sResources.getColor(R.color.graphgrid));
+ bgGraph.getGridLabelRenderer().reloadStyles();
+ iobGraph.getGridLabelRenderer().setGridColor(MainApp.sResources.getColor(R.color.graphgrid));
+ iobGraph.getGridLabelRenderer().reloadStyles();
+ iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
+ bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
+ iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
+ iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
+
+ bgGraph.setOnLongClickListener(new View.OnLongClickListener() {
+ @Override
+ public boolean onLongClick(View v) {
+ rangeToDisplay += 6;
+ rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
+ updateGUI("rangeChange");
+ return false;
}
});
- treatmentButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- FragmentManager manager = getFragmentManager();
- NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog();
- treatmentDialogFragment.show(manager, "TreatmentDialog");
- }
- });
-
- wizardButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- FragmentManager manager = getFragmentManager();
- WizardDialog wizardDialog = new WizardDialog();
- wizardDialog.show(manager, "WizardDialog");
- }
- });
-
- quickWizardButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- processQuickWizard();
- }
- });
-
- cancelTempButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- final PumpInterface pump = MainApp.getConfigBuilder();
- if (pump.isTempBasalInProgress()) {
- sHandler.post(new Runnable() {
- @Override
- public void run() {
- pump.cancelTempBasal();
- MainApp.bus().post(new EventTempBasalChange());
- Answers.getInstance().logCustom(new CustomEvent("CancelTemp"));
- }
- });
- }
- }
- });
-
- calibrationButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- FragmentManager manager = getFragmentManager();
- CalibrationDialog calibrationDialog = new CalibrationDialog();
- calibrationDialog.show(manager, "CalibrationDialog");
- }
- });
-
- acceptTempButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (ConfigBuilderPlugin.getActiveLoop() != null) {
- ConfigBuilderPlugin.getActiveLoop().invoke("Accept temp button", false);
- final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
- if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.changeRequested) {
- AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
- builder.setTitle(getContext().getString(R.string.confirmation));
- builder.setMessage(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
- builder.setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- sHandler.post(new Runnable() {
- @Override
- public void run() {
- hideTempRecommendation();
- PumpEnactResult applyResult = MainApp.getConfigBuilder().applyAPSRequest(finalLastRun.constraintsProcessed);
- if (applyResult.enacted) {
- finalLastRun.setByPump = applyResult;
- finalLastRun.lastEnact = new Date();
- finalLastRun.lastOpenModeAccept = new Date();
- MainApp.getConfigBuilder().uploadDeviceStatus();
- ObjectivesPlugin objectivesPlugin = (ObjectivesPlugin) MainApp.getSpecificPlugin(ObjectivesPlugin.class);
- if (objectivesPlugin != null) {
- objectivesPlugin.manualEnacts++;
- objectivesPlugin.saveProgress();
- }
- }
- updateGUIIfVisible();
- }
- });
- Answers.getInstance().logCustom(new CustomEvent("AcceptTemp"));
- }
- });
- builder.setNegativeButton(getContext().getString(R.string.cancel), null);
- builder.show();
- }
- updateGUI();
- }
- }
- });
-
- pumpStatusView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (MainApp.getConfigBuilder().isSuspended() || !MainApp.getConfigBuilder().isInitialized())
- sHandler.post(new Runnable() {
- @Override
- public void run() {
- MainApp.getConfigBuilder().refreshDataFromPump("RefreshClicked");
- }
- });
- }
- });
-
- updateGUI();
return view;
}
+
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
- final LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
+ final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (activeloop == null)
return;
menu.setHeaderTitle(MainApp.sResources.getString(R.string.loop));
@@ -341,52 +354,139 @@ public class OverviewFragment extends Fragment {
menu.add(MainApp.sResources.getString(R.string.enableloop));
}
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ switch (buttonView.getId()) {
+ case R.id.overview_showprediction:
+ SP.putBoolean("showprediction", showPredictionView.isChecked());
+ updateGUI("onPredictionCheckedChanged");
+ break;
+ case R.id.overview_showbasals:
+ SP.putBoolean("showbasals", showBasalsView.isChecked());
+ updateGUI("onBasalsCheckedChanged");
+ break;
+ case R.id.overview_showiob:
+ SP.putBoolean("showiob", showIobView.isChecked());
+ updateGUI("onIobCheckedChanged");
+ break;
+ case R.id.overview_showcob:
+ showDeviationsView.setOnCheckedChangeListener(null);
+ showDeviationsView.setChecked(false);
+ showDeviationsView.setOnCheckedChangeListener(this);
+ SP.putBoolean("showcob", showCobView.isChecked());
+ SP.putBoolean("showdeviations", showDeviationsView.isChecked());
+ updateGUI("onCobCheckedChanged");
+ break;
+ case R.id.overview_showdeviations:
+ showCobView.setOnCheckedChangeListener(null);
+ showCobView.setChecked(false);
+ showCobView.setOnCheckedChangeListener(this);
+ SP.putBoolean("showcob", showCobView.isChecked());
+ SP.putBoolean("showdeviations", showDeviationsView.isChecked());
+ updateGUI("onDeviationsCheckedChanged");
+ break;
+ }
+ }
+
@Override
public boolean onContextItemSelected(MenuItem item) {
- final LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
+ final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (item.getTitle().equals(MainApp.sResources.getString(R.string.disableloop))) {
activeloop.setFragmentEnabled(PluginBase.LOOP, false);
activeloop.setFragmentVisible(PluginBase.LOOP, false);
MainApp.getConfigBuilder().storeSettings();
- MainApp.bus().post(new EventRefreshGui(false));
- return true;
- } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.enableloop))) {
- activeloop.setFragmentEnabled(PluginBase.LOOP, true);
- activeloop.setFragmentVisible(PluginBase.LOOP, true);
- MainApp.getConfigBuilder().storeSettings();
- MainApp.bus().post(new EventRefreshGui(false));
- return true;
- } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.resume))) {
- activeloop.suspendTo(0L);
+ updateGUI("suspendmenu");
sHandler.post(new Runnable() {
@Override
public void run() {
- MainApp.bus().post(new EventRefreshGui(false));
PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal();
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
+ NSUpload.uploadOpenAPSOffline(60); // upload 60 min, we don;t know real duration
+ return true;
+ } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.enableloop))) {
+ activeloop.setFragmentEnabled(PluginBase.LOOP, true);
+ activeloop.setFragmentVisible(PluginBase.LOOP, true);
+ MainApp.getConfigBuilder().storeSettings();
+ updateGUI("suspendmenu");
+ NSUpload.uploadOpenAPSOffline(0);
+ return true;
+ } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.resume))) {
+ activeloop.suspendTo(0L);
+ updateGUI("suspendmenu");
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal();
+ if (!result.success) {
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
+ }
+ }
+ });
+ NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor1h))) {
activeloop.suspendTo(new Date().getTime() + 60L * 60 * 1000);
- MainApp.bus().post(new EventRefreshGui(false));
+ updateGUI("suspendmenu");
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal();
+ if (!result.success) {
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
+ }
+ }
+ });
+ NSUpload.uploadOpenAPSOffline(60);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor2h))) {
activeloop.suspendTo(new Date().getTime() + 2 * 60L * 60 * 1000);
- MainApp.bus().post(new EventRefreshGui(false));
+ updateGUI("suspendmenu");
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal();
+ if (!result.success) {
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
+ }
+ }
+ });
+ NSUpload.uploadOpenAPSOffline(120);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor3h))) {
activeloop.suspendTo(new Date().getTime() + 3 * 60L * 60 * 1000);
- MainApp.bus().post(new EventRefreshGui(false));
+ updateGUI("suspendmenu");
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal();
+ if (!result.success) {
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
+ }
+ }
+ });
+ NSUpload.uploadOpenAPSOffline(180);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor10h))) {
activeloop.suspendTo(new Date().getTime() + 10 * 60L * 60 * 1000);
- MainApp.bus().post(new EventRefreshGui(false));
+ updateGUI("suspendmenu");
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal();
+ if (!result.success) {
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
+ }
+ }
+ });
+ NSUpload.uploadOpenAPSOffline(600);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor30m))) {
activeloop.suspendTo(new Date().getTime() + 30L * 60 * 1000);
+ updateGUI("suspendmenu");
sHandler.post(new Runnable() {
@Override
public void run() {
@@ -394,66 +494,152 @@ public class OverviewFragment extends Fragment {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
- MainApp.bus().post(new EventRefreshGui(false));
}
});
+ NSUpload.uploadOpenAPSOffline(30);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor1h))) {
activeloop.suspendTo(new Date().getTime() + 1 * 60L * 60 * 1000);
+ updateGUI("suspendmenu");
sHandler.post(new Runnable() {
@Override
public void run() {
- MainApp.bus().post(new EventRefreshGui(false));
PumpEnactResult result = MainApp.getConfigBuilder().setTempBasalAbsolute(0d, 60);
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
+ NSUpload.uploadOpenAPSOffline(60);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor2h))) {
activeloop.suspendTo(new Date().getTime() + 2 * 60L * 60 * 1000);
+ updateGUI("suspendmenu");
sHandler.post(new Runnable() {
@Override
public void run() {
- MainApp.bus().post(new EventRefreshGui(false));
PumpEnactResult result = MainApp.getConfigBuilder().setTempBasalAbsolute(0d, 2 * 60);
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
+ NSUpload.uploadOpenAPSOffline(120);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor3h))) {
activeloop.suspendTo(new Date().getTime() + 3 * 60L * 60 * 1000);
+ updateGUI("suspendmenu");
sHandler.post(new Runnable() {
@Override
public void run() {
- MainApp.bus().post(new EventRefreshGui(false));
PumpEnactResult result = MainApp.getConfigBuilder().setTempBasalAbsolute(0d, 3 * 60);
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
+ NSUpload.uploadOpenAPSOffline(180);
return true;
}
return super.onContextItemSelected(item);
}
- void processQuickWizard() {
- final BgReading actualBg = GlucoseStatus.actualBg();
- if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet
- return;
- final NSProfile profile = ConfigBuilderPlugin.getActiveProfile().getProfile();
+ @Override
+ public void onClick(View v) {
+ FragmentManager manager = getFragmentManager();
+ switch (v.getId()) {
+ case R.id.overview_accepttempbutton:
+ onClickAcceptTemp();
+ break;
+ case R.id.overview_quickwizardbutton:
+ onClickQuickwizard();
+ break;
+ case R.id.overview_wizardbutton:
+ WizardDialog wizardDialog = new WizardDialog();
+ wizardDialog.show(manager, "WizardDialog");
+ break;
+ case R.id.overview_calibrationbutton:
+ CalibrationDialog calibrationDialog = new CalibrationDialog();
+ calibrationDialog.show(manager, "CalibrationDialog");
+ break;
+ case R.id.overview_treatmentbutton:
+ NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog();
+ treatmentDialogFragment.show(manager, "TreatmentDialog");
+ break;
+ case R.id.overview_canceltempbutton:
+ final PumpInterface pump = MainApp.getConfigBuilder();
+ if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ pump.cancelTempBasal();
+ Answers.getInstance().logCustom(new CustomEvent("CancelTemp"));
+ }
+ });
+ }
+ break;
+ case R.id.overview_pumpstatus:
+ if (MainApp.getConfigBuilder().isSuspended() || !MainApp.getConfigBuilder().isInitialized())
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ MainApp.getConfigBuilder().refreshDataFromPump("RefreshClicked");
+ }
+ });
+ break;
+ }
+
+ }
+
+ private void onClickAcceptTemp() {
+ if (ConfigBuilderPlugin.getActiveLoop() != null) {
+ ConfigBuilderPlugin.getActiveLoop().invoke("Accept temp button", false);
+ final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
+ if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.changeRequested) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
+ builder.setTitle(getContext().getString(R.string.confirmation));
+ builder.setMessage(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
+ builder.setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ sHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ hideTempRecommendation();
+ clearNotification();
+ PumpEnactResult applyResult = MainApp.getConfigBuilder().applyAPSRequest(finalLastRun.constraintsProcessed);
+ if (applyResult.enacted) {
+ finalLastRun.setByPump = applyResult;
+ finalLastRun.lastEnact = new Date();
+ finalLastRun.lastOpenModeAccept = new Date();
+ NSUpload.uploadDeviceStatus();
+ ObjectivesPlugin objectivesPlugin = (ObjectivesPlugin) MainApp.getSpecificPlugin(ObjectivesPlugin.class);
+ if (objectivesPlugin != null) {
+ ObjectivesPlugin.manualEnacts++;
+ ObjectivesPlugin.saveProgress();
+ }
+ }
+ scheduleUpdateGUI("onClickAcceptTemp");
+ }
+ });
+ Answers.getInstance().logCustom(new CustomEvent("AcceptTemp"));
+ }
+ });
+ builder.setNegativeButton(getContext().getString(R.string.cancel), null);
+ builder.show();
+ }
+ }
+ }
+
+ void onClickQuickwizard() {
+ final BgReading actualBg = DatabaseHelper.actualBg();
+ final Profile profile = MainApp.getConfigBuilder().getProfile();
QuickWizard.QuickWizardEntry quickWizardEntry = getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && actualBg != null) {
quickWizardButton.setVisibility(View.VISIBLE);
- String text = MainApp.sResources.getString(R.string.bolus) + ": " + quickWizardEntry.buttonText();
BolusWizard wizard = new BolusWizard();
- wizard.doCalc(profile.getDefaultProfile(), quickWizardEntry.carbs(), 0d, actualBg.valueToUnits(profile.getUnits()), 0d, true, true, false, true);
+ wizard.doCalc(profile, quickWizardEntry.carbs(), 0d, actualBg.valueToUnits(profile.getUnits()), 0d, true, true, false, false);
final JSONObject boluscalcJSON = new JSONObject();
try {
@@ -487,7 +673,7 @@ public class OverviewFragment extends Fragment {
confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g";
- if (insulinAfterConstraints - wizard.calculatedTotalInsulin != 0 || carbsAfterConstraints != quickWizardEntry.carbs()) {
+ if (!insulinAfterConstraints.equals(wizard.calculatedTotalInsulin) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput));
@@ -498,8 +684,8 @@ public class OverviewFragment extends Fragment {
final Double finalInsulinAfterConstraints = insulinAfterConstraints;
final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
-
- AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
+ final Context context = getContext();
+ AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@@ -509,15 +695,14 @@ public class OverviewFragment extends Fragment {
sHandler.post(new Runnable() {
@Override
public void run() {
- PumpEnactResult result = pump.deliverTreatmentFromBolusWizard(
- getContext(),
- finalInsulinAfterConstraints,
- finalCarbsAfterConstraints,
- actualBg.valueToUnits(profile.getUnits()),
- "Manual",
- 0,
- boluscalcJSON
- );
+ DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
+ detailedBolusInfo.eventType = CareportalEvent.BOLUSWIZARD;
+ detailedBolusInfo.insulin = finalInsulinAfterConstraints;
+ detailedBolusInfo.carbs = finalCarbsAfterConstraints;
+ detailedBolusInfo.context = context;
+ detailedBolusInfo.boluscalc = boluscalcJSON;
+ detailedBolusInfo.source = Source.USER;
+ PumpEnactResult result = pump.deliverTreatment(detailedBolusInfo);
if (!result.success) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
@@ -553,58 +738,75 @@ public class OverviewFragment extends Fragment {
sRefreshLoop = new Runnable() {
@Override
public void run() {
- updateGUIIfVisible();
+ scheduleUpdateGUI("refreshLoop");
sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
}
};
sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
registerForContextMenu(apsModeView);
- updateGUIIfVisible();
+ updateGUI("onResume");
}
@Subscribe
public void onStatusEvent(final EventInitializationChanged ev) {
- updateGUIIfVisible();
+ scheduleUpdateGUI("EventInitializationChanged");
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange ev) {
- updateGUIIfVisible();
+ scheduleUpdateGUI("EventPreferenceChange");
}
@Subscribe
public void onStatusEvent(final EventRefreshGui ev) {
- updateGUIIfVisible();
+ scheduleUpdateGUI("EventRefreshGui");
+ }
+
+ @Subscribe
+ public void onStatusEvent(final EventAutosensCalculationFinished ev) {
+ scheduleUpdateGUI("EventAutosensCalculationFinished");
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
- updateGUIIfVisible();
+ scheduleUpdateGUI("EventTreatmentChange");
+ }
+
+ @Subscribe
+ public void onStatusEvent(final EventCareportalEventChange ev) {
+ scheduleUpdateGUI("EventCareportalEventChange");
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
- updateGUIIfVisible();
+ scheduleUpdateGUI("EventTempBasalChange");
}
@Subscribe
- public void onStatusEvent(final EventNewBG ev) {
- updateGUIIfVisible();
+ public void onStatusEvent(final EventExtendedBolusChange ev) {
+ scheduleUpdateGUI("EventExtendedBolusChange");
}
+// Handled by EventAutosensCalculationFinished
+// @Subscribe
+// public void onStatusEvent(final EventNewBG ev) {
+// scheduleUpdateGUI("EventNewBG");
+// }
+
@Subscribe
public void onStatusEvent(final EventNewOpenLoopNotification ev) {
- updateGUIIfVisible();
+ scheduleUpdateGUI("EventNewOpenLoopNotification");
}
- @Subscribe
- public void onStatusEvent(final EventNewBasalProfile ev) {
- updateGUIIfVisible();
- }
+// Handled by EventAutosensCalculationFinished
+// @Subscribe
+// public void onStatusEvent(final EventNewBasalProfile ev) {
+// scheduleUpdateGUI("EventNewBasalProfile");
+// }
@Subscribe
- public void onStatusEvent(final EventTempTargetRangeChange ev) {
- updateGUIIfVisible();
+ public void onStatusEvent(final EventTempTargetChange ev) {
+ scheduleUpdateGUI("EventTempTargetChange");
}
@Subscribe
@@ -640,73 +842,97 @@ public class OverviewFragment extends Fragment {
});
}
- private void updateGUIIfVisible() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- updateGUI();
- }
- });
+ private void clearNotification() {
+ NotificationManager notificationManager =
+ (NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
+ notificationManager.cancel(Constants.notificationID);
}
private void updatePumpStatus(String status) {
- PumpInterface pump = MainApp.getConfigBuilder();
if (!status.equals("")) {
pumpStatusView.setText(status);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
} else {
- wizardButton.setVisibility(View.VISIBLE);
- treatmentButton.setVisibility(View.VISIBLE);
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
}
}
- @SuppressLint("SetTextI18n")
- public void updateGUI() {
- updateNotifications();
- BgReading actualBG = GlucoseStatus.actualBg();
- BgReading lastBG = GlucoseStatus.lastBg();
-
- if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null || MainApp.getConfigBuilder().getActiveProfile().getProfile() == null) {// app not initialized yet
- pumpStatusView.setText(R.string.noprofileset);
- pumpStatusLayout.setVisibility(View.VISIBLE);
- loopStatusLayout.setVisibility(View.GONE);
- return;
- } else {
- pumpStatusLayout.setVisibility(View.GONE);
- loopStatusLayout.setVisibility(View.VISIBLE);
+ public void scheduleUpdateGUI(final String from) {
+ class UpdateRunnable implements Runnable {
+ public void run() {
+ Activity activity = getActivity();
+ if (activity != null)
+ activity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ updateGUI(from);
+ scheduledUpdate = null;
+ }
+ });
+ }
}
+ // prepare task for execution in 400 msec
+ // cancel waiting task to prevent multiple updates
+ if (scheduledUpdate != null)
+ scheduledUpdate.cancel(false);
+ Runnable task = new UpdateRunnable();
+ final int msec = 2000;
+ scheduledUpdate = worker.schedule(task, msec, TimeUnit.MILLISECONDS);
+ }
- PumpInterface pump = MainApp.getConfigBuilder();
-
- // Skip if not initialized yet
- if (bgGraph == null)
- return;
+ @SuppressLint("SetTextI18n")
+ public void updateGUI(String from) {
+ log.debug("updateGUI entered from: " + from);
+ Date updateGUIStart = new Date();
if (getActivity() == null)
return;
+ if (timeView != null) { //must not exists
+ timeView.setText(DateUtil.timeString(new Date()));
+ }
+ if (updating != null)
+ updating.setVisibility(View.VISIBLE);
+
+ if (MainApp.getConfigBuilder().getProfile() == null) {// app not initialized yet
+ pumpStatusView.setText(R.string.noprofileset);
+ pumpStatusLayout.setVisibility(View.VISIBLE);
+ loopStatusLayout.setVisibility(View.GONE);
+ if (updating != null)
+ updating.setVisibility(View.GONE);
+ return;
+ }
+ pumpStatusLayout.setVisibility(View.GONE);
+ loopStatusLayout.setVisibility(View.VISIBLE);
+
+ updateNotifications();
+ CareportalFragment.updateAge(getActivity(), sage, iage, cage, pbage);
+ BgReading actualBG = DatabaseHelper.actualBg();
+ BgReading lastBG = DatabaseHelper.lastBg();
+
+ PumpInterface pump = MainApp.getConfigBuilder();
+
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+
// open loop mode
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (Config.APS && MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable) {
apsModeView.setVisibility(View.VISIBLE);
- apsModeView.setBackgroundResource(R.drawable.loopmodeborder);
+ apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.loopenabled));
apsModeView.setTextColor(Color.BLACK);
- final LoopPlugin activeloop = MainApp.getConfigBuilder().getActiveLoop();
+ final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (activeloop != null && activeloop.isEnabled(activeloop.getType()) && activeloop.isSuperBolus()) {
- apsModeView.setBackgroundResource(R.drawable.loopmodesuspendedborder);
+ apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(String.format(MainApp.sResources.getString(R.string.loopsuperbolusfor), activeloop.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE);
} else if (activeloop != null && activeloop.isEnabled(activeloop.getType()) && activeloop.isSuspended()) {
- apsModeView.setBackgroundResource(R.drawable.loopmodesuspendedborder);
+ apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(String.format(MainApp.sResources.getString(R.string.loopsuspendedfor), activeloop.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE);
} else if (pump.isSuspended()) {
- apsModeView.setBackgroundResource(R.drawable.loopmodesuspendedborder);
+ apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(MainApp.sResources.getString(R.string.pumpsuspended));
apsModeView.setTextColor(Color.WHITE);
} else if (activeloop != null && activeloop.isEnabled(activeloop.getType())) {
@@ -716,7 +942,7 @@ public class OverviewFragment extends Fragment {
apsModeView.setText(MainApp.sResources.getString(R.string.openloop));
}
} else {
- apsModeView.setBackgroundResource(R.drawable.loopmodedisabledborder);
+ apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.loopdisabled));
apsModeView.setText(MainApp.sResources.getString(R.string.disabledloop));
apsModeView.setTextColor(Color.WHITE);
}
@@ -725,29 +951,28 @@ public class OverviewFragment extends Fragment {
}
// temp target
- NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
- TempTargetRangePlugin tempTargetRangePlugin = (TempTargetRangePlugin) MainApp.getSpecificPlugin(TempTargetRangePlugin.class);
- if (Config.APS && tempTargetRangePlugin != null && tempTargetRangePlugin.isEnabled(PluginBase.GENERAL)) {
- TempTarget tempTarget = tempTargetRangePlugin.getTempTargetInProgress(new Date().getTime());
- if (tempTarget != null) {
- tempTargetView.setTextColor(Color.BLACK);
- tempTargetView.setBackgroundResource(R.drawable.temptargetborder);
- tempTargetView.setVisibility(View.VISIBLE);
- tempTargetView.setText(NSProfile.toUnitsString(tempTarget.low, NSProfile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + NSProfile.toUnitsString(tempTarget.high, NSProfile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits()));
- } else {
-
- 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(SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault));
- tempTargetView.setVisibility(View.VISIBLE);
- }
+ TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
+ if (tempTarget != null) {
+ tempTargetView.setTextColor(Color.BLACK);
+ tempTargetView.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetBackground));
+ tempTargetView.setVisibility(View.VISIBLE);
+ if (tempTarget.low == tempTarget.high)
+ tempTargetView.setText(Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()));
+ else
+ tempTargetView.setText(Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + Profile.toUnitsString(tempTarget.high, Profile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits()));
} else {
+ 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.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetDisabledBackground));
+ tempTargetView.setText(SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault));
+ tempTargetView.setVisibility(View.VISIBLE);
+ }
+ if (Config.NSCLIENT && tempTarget == null) {
tempTargetView.setVisibility(View.GONE);
}
@@ -765,32 +990,41 @@ public class OverviewFragment extends Fragment {
}
// **** Calibration button ****
- if (MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE) && profile != null && GlucoseStatus.actualBg() != null) {
+ if (MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE) && profile != null && DatabaseHelper.actualBg() != null) {
calibrationButton.setVisibility(View.VISIBLE);
} else {
calibrationButton.setVisibility(View.GONE);
}
- TempBasal activeTemp = pump.getTempBasal();
- if (pump.isTempBasalInProgress()) {
- cancelTempLayout.setVisibility(View.VISIBLE);
- cancelTempButton.setText(MainApp.instance().getString(R.string.cancel) + ": " + activeTemp.toString());
- runningTempView.setVisibility(View.VISIBLE);
- runningTempView.setText(activeTemp.toString());
+ TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime());
+ if (activeTemp != null) {
+ cancelTempButton.setVisibility(View.VISIBLE);
+ cancelTempButton.setText(MainApp.instance().getString(R.string.cancel) + "\n" + activeTemp.toStringShort());
} else {
- cancelTempLayout.setVisibility(View.GONE);
- runningTempView.setVisibility(View.GONE);
+ cancelTempButton.setVisibility(View.GONE);
}
- if (pump.getPumpDescription().isTempBasalCapable) {
- basalLayout.setVisibility(View.VISIBLE);
- baseBasalView.setText(DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + " U/h");
- } else {
- basalLayout.setVisibility(View.GONE);
+ String basalText = "";
+ if (activeTemp != null) {
+ basalText = activeTemp.toStringFull() + " ";
}
+ if (Config.NSCLIENT)
+ basalText += "( " + DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + " U/h )";
+ else if (pump.getPumpDescription().isTempBasalCapable) {
+ basalText += "( " + DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + " U/h )";
+ }
+ baseBasalView.setText(basalText);
- if (profile != null && profile.getActiveProfile() != null)
- activeProfileView.setText(profile.getActiveProfile());
+ ExtendedBolus extendedBolus = MainApp.getConfigBuilder().getExtendedBolusFromHistory(new Date().getTime());
+ String extendedBolusText = "";
+ if (extendedBolus != null) {
+ extendedBolusText = extendedBolus.toString();
+ }
+ if (extendedBolusView != null) // must not exists in all layouts
+ extendedBolusView.setText(extendedBolusText);
+
+ activeProfileView.setText(MainApp.getConfigBuilder().getProfileName());
+ activeProfileView.setBackgroundColor(Color.GRAY);
activeProfileView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
@@ -825,9 +1059,9 @@ public class OverviewFragment extends Fragment {
QuickWizard.QuickWizardEntry quickWizardEntry = getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && lastBG != null && pump.isInitialized() && !pump.isSuspended()) {
quickWizardButton.setVisibility(View.VISIBLE);
- String text = MainApp.sResources.getString(R.string.bolus) + ": " + quickWizardEntry.buttonText() + " " + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
+ String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
BolusWizard wizard = new BolusWizard();
- wizard.doCalc(profile.getDefaultProfile(), quickWizardEntry.carbs(), 0d, lastBG.valueToUnits(profile.getUnits()), 0d, true, true, false, true);
+ wizard.doCalc(profile, quickWizardEntry.carbs(), 0d, lastBG.valueToUnits(profile.getUnits()), 0d, true, true, false, false);
text += " " + DecimalFormatter.to2Decimal(wizard.calculatedTotalInsulin) + "U";
quickWizardButton.setText(text);
if (wizard.calculatedTotalInsulin <= 0)
@@ -835,26 +1069,51 @@ public class OverviewFragment extends Fragment {
} else
quickWizardButton.setVisibility(View.GONE);
+ // Bolus and calc button
+ if (pump.isInitialized() && !pump.isSuspended()) {
+ wizardButton.setVisibility(View.VISIBLE);
+ treatmentButton.setVisibility(View.VISIBLE);
+ } else {
+ wizardButton.setVisibility(View.GONE);
+ treatmentButton.setVisibility(View.GONE);
+ }
+
String units = profile.getUnits();
+ Double lowLine = SP.getDouble("low_mark", 0d);
+ Double highLine = SP.getDouble("high_mark", 0d);
+ if (lowLine < 1) {
+ lowLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
+ }
+ if (highLine < 1) {
+ highLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
+ }
+
// **** BG value ****
if (lastBG != null) {
+ int color = MainApp.sResources.getColor(R.color.inrange);
+ if (lastBG.valueToUnits(units) < lowLine)
+ color = MainApp.sResources.getColor(R.color.low);
+ else if (lastBG.valueToUnits(units) > highLine)
+ color = MainApp.sResources.getColor(R.color.high);
bgView.setText(lastBG.valueToUnitsToString(profile.getUnits()));
arrowView.setText(lastBG.directionToSymbol());
+ bgView.setTextColor(color);
+ arrowView.setTextColor(color);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null) {
- deltaView.setText("Δ " + NSProfile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
- avgdeltaView.setText("øΔ15m: " + NSProfile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
- " øΔ40m: " + NSProfile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
+ deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
+ avgdeltaView.setText("øΔ15m: " + Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
+ " øΔ40m: " + Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
} else {
deltaView.setText("Δ " + MainApp.sResources.getString(R.string.notavailable));
avgdeltaView.setText("");
}
-
- BgReading.units = profile.getUnits();
- } else
+ } else {
+ if (updating != null)
+ updating.setVisibility(View.GONE);
return;
-
+ }
Integer flag = bgView.getPaintFlags();
if (actualBG == null) {
flag |= Paint.STRIKE_THRU_TEXT_FLAG;
@@ -862,32 +1121,41 @@ public class OverviewFragment extends Fragment {
flag &= ~Paint.STRIKE_THRU_TEXT_FLAG;
bgView.setPaintFlags(flag);
- Long agoMsec = new Date().getTime() - lastBG.timeIndex;
+ Long agoMsec = new Date().getTime() - lastBG.date;
int agoMin = (int) (agoMsec / 60d / 1000d);
timeAgoView.setText(String.format(MainApp.sResources.getString(R.string.minago), agoMin));
// iob
- ConfigBuilderPlugin.getActiveTreatments().updateTotalIOB();
- IobTotal bolusIob = ConfigBuilderPlugin.getActiveTreatments().getLastCalculation().round();
- IobTotal basalIob = new IobTotal(new Date().getTime());
- if (ConfigBuilderPlugin.getActiveTempBasals() != null) {
- ConfigBuilderPlugin.getActiveTempBasals().updateTotalIOB();
- basalIob = ConfigBuilderPlugin.getActiveTempBasals().getLastCalculation().round();
- }
+ MainApp.getConfigBuilder().updateTotalIOBTreatments();
+ MainApp.getConfigBuilder().updateTotalIOBTempBasals();
+ IobTotal bolusIob = MainApp.getConfigBuilder().getLastCalculationTreatments().round();
+ IobTotal basalIob = MainApp.getConfigBuilder().getLastCalculationTempBasals().round();
String iobtext = getString(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
iobView.setText(iobtext);
+ // cob
+ if (cobView != null) { // view must not exists
+ String cobText = "";
+ AutosensData autosensData = IobCobCalculatorPlugin.getAutosensData(new Date().getTime());
+ if (autosensData != null)
+ cobText = (int) autosensData.cob + " g " + String.format(MainApp.sResources.getString(R.string.minago), autosensData.minOld());
+ cobView.setText(cobText);
+ }
+
boolean showPrediction = showPredictionView.isChecked() && finalLastRun != null && finalLastRun.constraintsProcessed.getClass().equals(DetermineBasalResultAMA.class);
if (MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class) != null && MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class).isEnabled(PluginBase.APS)) {
showPredictionView.setVisibility(View.VISIBLE);
+ getActivity().findViewById(R.id.overview_showprediction_label).setVisibility(View.VISIBLE);
} else {
showPredictionView.setVisibility(View.GONE);
+ getActivity().findViewById(R.id.overview_showprediction_label).setVisibility(View.GONE);
}
// ****** GRAPH *******
+ //log.debug("updateGUI checkpoint 1");
// allign to hours
Calendar calendar = Calendar.getInstance();
@@ -905,205 +1173,357 @@ public class OverviewFragment extends Fragment {
int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - new Date().getTime()) / (60 * 60 * 1000));
predHours = Math.min(2, predHours);
predHours = Math.max(0, predHours);
- hoursToFetch = (int) (6 - predHours);
- toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding
+ hoursToFetch = rangeToDisplay - predHours;
+ toTime = calendar.getTimeInMillis() + 60000; // little bit more to avoid wrong rounding
fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
endTime = toTime + predHours * 60 * 60 * 1000L;
} else {
- hoursToFetch = 6;
- toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding
+ hoursToFetch = rangeToDisplay;
+ toTime = calendar.getTimeInMillis() + 600000; // little bit more to avoid wrong rounding
fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
endTime = toTime;
}
- Double lowLine = SP.getDouble("low_mark", 0d);
- Double highLine = SP.getDouble("high_mark", 0d);
-
- if (lowLine < 1) {
- lowLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
- }
-
- if (highLine < 1) {
- highLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
- }
-
LineGraphSeries basalsLineSeries = null;
- BarGraphSeries basalsSeries = null;
- LineGraphSeries seriesLow = null;
- LineGraphSeries seriesHigh = null;
- LineGraphSeries seriesNow = null;
- PointsGraphSeries seriesInRage = null;
- PointsGraphSeries seriesOutOfRange = null;
- PointsGraphSeries predSeries = null;
- PointsWithLabelGraphSeries seriesTreatments = null;
-
- // remove old data from graph
- bgGraph.removeAllSeries();
-
- // **** HIGH and LOW targets graph ****
- DataPoint[] lowDataPoints = new DataPoint[]{
- new DataPoint(fromTime, lowLine),
- new DataPoint(endTime, lowLine)
- };
- DataPoint[] highDataPoints = new DataPoint[]{
- new DataPoint(fromTime, highLine),
- new DataPoint(endTime, highLine)
- };
- bgGraph.addSeries(seriesLow = new LineGraphSeries(lowDataPoints));
- seriesLow.setColor(Color.RED);
- bgGraph.addSeries(seriesHigh = new LineGraphSeries(highDataPoints));
- seriesHigh.setColor(Color.RED);
+ LineGraphSeries absoluteBasalsLineSeries = null;
+ LineGraphSeries baseBasalsSeries = null;
+ LineGraphSeries tempBasalsSeries = null;
+ AreaGraphSeries areaSeries;
+ LineGraphSeries seriesNow, seriesNow2;
// **** TEMP BASALS graph ****
- class BarDataPoint extends DataPoint {
- public BarDataPoint(double x, double y, boolean isTempBasal) {
- super(x, y);
- this.isTempBasal = isTempBasal;
- }
-
- public boolean isTempBasal = false;
- }
-
Double maxBasalValueFound = 0d;
long now = new Date().getTime();
- if (pump.getPumpDescription().isTempBasalCapable) {
- List basalArray = new ArrayList();
- List basalLineArray = new ArrayList();
+ if (pump.getPumpDescription().isTempBasalCapable && showBasalsView.isChecked()) {
+ List baseBasalArray = new ArrayList<>();
+ List tempBasalArray = new ArrayList<>();
+ List basalLineArray = new ArrayList<>();
+ List