commit
4ce643ae08
478 changed files with 11137 additions and 7204 deletions
|
@ -44,7 +44,7 @@ android {
|
|||
minSdkVersion 21
|
||||
targetSdkVersion 23
|
||||
versionCode 1500
|
||||
version "1.5"
|
||||
version "1.5g"
|
||||
buildConfigField "String", "VERSION", '"' + version + '"'
|
||||
buildConfigField "String", "BUILDVERSION", generateGitBuild()
|
||||
}
|
||||
|
@ -173,6 +173,9 @@ dependencies {
|
|||
androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
|
||||
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'
|
||||
compile(name: 'android-edittext-validator-v1.3.4-mod', ext: 'aar')
|
||||
compile ('com.google.android:flexbox:0.3.0') {
|
||||
exclude group: 'com.android.support'
|
||||
}
|
||||
compile('io.socket:socket.io-client:0.8.3') {
|
||||
// excluding org.json which is provided by Android
|
||||
exclude group: 'org.json', module: 'json'
|
||||
|
@ -180,4 +183,4 @@ dependencies {
|
|||
compile 'com.google.code.gson:gson:2.7'
|
||||
compile 'com.google.guava:guava:20.0'
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@
|
|||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
|
||||
|
||||
<uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
|
||||
<!-- To receive data from xdrip. -->
|
||||
|
@ -41,14 +42,11 @@
|
|||
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity"
|
||||
android:theme="@style/Theme.AppCompat.Translucent" />
|
||||
<activity android:name=".AgreementActivity" />
|
||||
<activity android:name=".plugins.PumpDanaR.History.DanaRHistoryActivity" />
|
||||
<activity android:name=".plugins.PumpDanaRKorean.History.DanaRHistoryActivity" />
|
||||
<activity android:name=".plugins.PumpDanaR.History.DanaRStatsActivity" />
|
||||
<activity android:name=".plugins.PumpDanaRKorean.History.DanaRStatsActivity" />
|
||||
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" />
|
||||
<activity android:name=".plugins.PumpDanaR.activities.DanaRStatsActivity" />
|
||||
<activity android:name=".plugins.Overview.activities.QuickWizardListActivity">
|
||||
<intent-filter>
|
||||
<action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" />
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
@ -58,17 +56,6 @@
|
|||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
|
||||
<!-- Receiver from NSClient -->
|
||||
<action android:name="info.nightscout.client.NEW_SGV" />
|
||||
<action android:name="info.nightscout.client.NEW_TREATMENT" />
|
||||
<action android:name="info.nightscout.client.CHANGED_TREATMENT" />
|
||||
<action android:name="info.nightscout.client.REMOVED_TREATMENT" />
|
||||
<action android:name="info.nightscout.client.NEW_PROFILE" />
|
||||
<action android:name="info.nightscout.client.NEW_STATUS" />
|
||||
<action android:name="info.nightscout.client.NEW_MBG" />
|
||||
<action android:name="info.nightscout.client.NEW_DEVICESTATUS" />
|
||||
<action android:name="info.nightscout.client.NEW_CAL" />
|
||||
<!-- Receive new SMS messages -->
|
||||
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
|
||||
<!-- Receiver from xDrip -->
|
||||
|
@ -79,7 +66,6 @@
|
|||
<action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- Receiver keepalive, scheduled every 30 min -->
|
||||
<receiver android:name=".receivers.KeepAliveReceiver" />
|
||||
|
||||
|
@ -117,7 +103,6 @@
|
|||
android:exported="false" />
|
||||
<service
|
||||
android:name=".plugins.PumpDanaR.services.DanaRExecutionService"
|
||||
|
||||
android:enabled="true"
|
||||
android:exported="false" />
|
||||
<service
|
||||
|
@ -135,16 +120,19 @@
|
|||
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
<service
|
||||
android:name=".plugins.NSClientInternal.services.NSClientService"
|
||||
android:enabled="true"
|
||||
android:exported="true" />
|
||||
<service
|
||||
android:name=".Services.AlarmSoundService"
|
||||
android:enabled="true"
|
||||
android:exported="true" />
|
||||
|
||||
<meta-data
|
||||
android:name="io.fabric.ApiKey"
|
||||
android:value="59d462666c664c57b29e1d79ea123e01f8057cfa" />
|
||||
|
||||
<service
|
||||
android:name=".plugins.NSClientInternal.services.NSClientService"
|
||||
android:enabled="true"
|
||||
android:exported="true" />
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
|
@ -4,6 +4,8 @@ package info.nightscout.androidaps;
|
|||
* Created by mike on 07.06.2016.
|
||||
*/
|
||||
public class Config {
|
||||
public static int SUPPORTEDNSVERSION = 1000; // 0.10.00
|
||||
|
||||
// MAIN FUCTIONALITY
|
||||
public static final boolean APS = BuildConfig.APS;
|
||||
// PLUGINS
|
||||
|
@ -29,19 +31,16 @@ public class Config {
|
|||
|
||||
public static final boolean detailedLog = true;
|
||||
public static final boolean logFunctionCalls = true;
|
||||
public static final boolean logIncommingBG = true;
|
||||
public static final boolean logIncommingData = true;
|
||||
public static final boolean logAPSResult = true;
|
||||
public static final boolean logPumpComm = true;
|
||||
public static final boolean logPrefsChange = true;
|
||||
public static final boolean logConfigBuilder = true;
|
||||
public static final boolean logConstraintsChanges = true;
|
||||
public static final boolean logTempBasalsCut = true;
|
||||
public static final boolean logNSUpload = true;
|
||||
public static final boolean logPumpActions = true;
|
||||
public static final boolean logSMSComm = true;
|
||||
public static final boolean logCongigBuilderActions = true;
|
||||
public static final boolean logAutosensData = false;
|
||||
public static final boolean logAutosensData = true;
|
||||
|
||||
// DanaR specific
|
||||
public static final boolean logDanaBTComm = true;
|
||||
|
|
|
@ -33,14 +33,6 @@ public class Constants {
|
|||
public static final int CPP_MIN_PERCENTAGE = 50;
|
||||
public static final int CPP_MAX_PERCENTAGE = 200;
|
||||
|
||||
// Defaults for settings
|
||||
public static final Double MAX_BG_DEFAULT_MGDL = 180d;
|
||||
public static final Double MAX_BG_DEFAULT_MMOL = 10d;
|
||||
public static final Double MIN_BG_DEFAULT_MGDL = 100d;
|
||||
public static final Double MIN_BG_DEFAULT_MMOL = 5d;
|
||||
public static final Double TARGET_BG_DEFAULT_MGDL = 150d;
|
||||
public static final Double TARGET_BG_DEFAULT_MMOL = 7d;
|
||||
|
||||
// Very Hard Limits Ranges
|
||||
// First value is the Lowest and second value is the Highest a Limit can define
|
||||
public static final int[] VERY_HARD_LIMIT_MIN_BG = {72,180};
|
||||
|
|
|
@ -23,6 +23,7 @@ import android.view.MenuInflater;
|
|||
import android.view.MenuItem;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ImageButton;
|
||||
|
@ -34,10 +35,14 @@ import com.squareup.otto.Subscribe;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import info.nightscout.androidaps.Services.AlarmSoundService;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.androidaps.events.EventAppExit;
|
||||
import info.nightscout.androidaps.events.EventPreferenceChange;
|
||||
import info.nightscout.androidaps.events.EventRefreshGui;
|
||||
import info.nightscout.androidaps.interfaces.PluginBase;
|
||||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
|
||||
import info.nightscout.androidaps.plugins.Overview.events.EventSetWakeLock;
|
||||
import info.nightscout.androidaps.tabs.SlidingTabLayout;
|
||||
import info.nightscout.androidaps.tabs.TabPageAdapter;
|
||||
import info.nightscout.utils.ImportExportPrefs;
|
||||
|
@ -58,6 +63,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
|
||||
ImageButton menuButton;
|
||||
|
||||
protected PowerManager.WakeLock mWakeLock;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
|
@ -74,13 +80,28 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
Manifest.permission.WRITE_EXTERNAL_STORAGE}, CASE_STORAGE);
|
||||
}
|
||||
askForBatteryOptimizationPermission();
|
||||
checkUpgradeToProfileTarget();
|
||||
if (Config.logFunctionCalls)
|
||||
log.debug("onCreate");
|
||||
|
||||
onStatusEvent(new EventSetWakeLock(SP.getBoolean("lockscreen", false)));
|
||||
|
||||
registerBus();
|
||||
setUpTabs(false);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventSetWakeLock ev) {
|
||||
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
|
||||
if (ev.lock) {
|
||||
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "AAPS");
|
||||
mWakeLock.acquire();
|
||||
} else {
|
||||
if (mWakeLock != null)
|
||||
mWakeLock.release();
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventRefreshGui ev) {
|
||||
String lang = SP.getString("language", "en");
|
||||
|
@ -90,10 +111,15 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
public void run() {
|
||||
recreate();
|
||||
try { // activity may be destroyed
|
||||
setUpTabs(ev.isSwitchToLast());
|
||||
setUpTabs(true);
|
||||
} catch (IllegalStateException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
boolean lockScreen = BuildConfig.NSCLIENTOLNY && SP.getBoolean("lockscreen", false);
|
||||
if (lockScreen)
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
else
|
||||
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -130,6 +156,29 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
}
|
||||
}
|
||||
|
||||
private void checkUpgradeToProfileTarget() { // TODO: can be removed in the future
|
||||
boolean oldKeyExists = SP.contains("openapsma_min_bg");
|
||||
if (oldKeyExists) {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
String oldRange = SP.getDouble("openapsma_min_bg", 0d) + " - " + SP.getDouble("openapsma_max_bg", 0d);
|
||||
String newRange = "";
|
||||
if (profile != null) {
|
||||
newRange = profile.getTargetLow() + " - " + profile.getTargetHigh();
|
||||
}
|
||||
String message = "Target range is changed in current version.\n\nIt's not taken from preferences but from profile.\n\n!!! REVIEW YOUR SETTINGS !!!";
|
||||
message += "\n\nOld settings: " + oldRange;
|
||||
message += "\nProfile settings: " + newRange;
|
||||
OKDialog.show(this, "Target range change", message, new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
SP.remove("openapsma_min_bg");
|
||||
SP.remove("openapsma_max_bg");
|
||||
SP.remove("openapsma_target_bg");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//check for sms permission if enable in prefernces
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventPreferenceChange ev) {
|
||||
|
@ -154,6 +203,13 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
askForSMSPermissions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
if (mWakeLock != null)
|
||||
mWakeLock.release();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private void askForBatteryOptimizationPermission() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
final String packageName = getPackageName();
|
||||
|
@ -162,7 +218,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
|
||||
log.debug("Requesting ignore battery optimization");
|
||||
|
||||
OKDialog.show(getParent(), getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() {
|
||||
OKDialog.show(this, getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
@ -299,7 +355,9 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
|
|||
builder.setIcon(R.mipmap.yellowowl);
|
||||
else
|
||||
builder.setIcon(R.mipmap.blueowl);
|
||||
builder.setMessage("Build: " + BuildConfig.BUILDVERSION);
|
||||
String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
|
||||
message += MainApp.sResources.getString(R.string.configbuilder_nightscoutversion_label) + " " + ConfigBuilderPlugin.nightscoutVersionName;
|
||||
builder.setMessage(message);
|
||||
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
|
||||
AlertDialog alertDialog = builder.create();
|
||||
alertDialog.show();
|
||||
|
|
|
@ -2,8 +2,10 @@ package info.nightscout.androidaps;
|
|||
|
||||
import android.app.Application;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.res.Resources;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import com.crashlytics.android.Crashlytics;
|
||||
import com.crashlytics.android.answers.Answers;
|
||||
|
@ -17,6 +19,7 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.androidaps.db.DatabaseHelper;
|
||||
import info.nightscout.androidaps.interfaces.InsulinInterface;
|
||||
import info.nightscout.androidaps.interfaces.PluginBase;
|
||||
|
@ -26,12 +29,13 @@ import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
|
|||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
|
||||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
|
||||
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesFragment;
|
||||
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyFragment;
|
||||
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
|
||||
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.IobCobCalculator.IobCobCalculatorPlugin;
|
||||
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalFragment;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
|
||||
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment;
|
||||
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAFragment;
|
||||
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
|
||||
|
@ -46,18 +50,22 @@ 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.PumpMDI.MDIPlugin;
|
||||
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
|
||||
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.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.Treatments.TreatmentsFragment;
|
||||
import info.nightscout.androidaps.plugins.Wear.WearFragment;
|
||||
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslineFragment;
|
||||
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
|
||||
import info.nightscout.androidaps.receivers.DataReceiver;
|
||||
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
|
||||
import info.nightscout.androidaps.receivers.NSAlarmReceiver;
|
||||
import info.nightscout.utils.NSUpload;
|
||||
import io.fabric.sdk.android.Fabric;
|
||||
|
||||
|
@ -75,6 +83,11 @@ public class MainApp extends Application {
|
|||
|
||||
private static ArrayList<PluginBase> pluginsList = null;
|
||||
|
||||
private static DataReceiver dataReceiver = new DataReceiver();
|
||||
private static NSAlarmReceiver alarmReciever = new NSAlarmReceiver();
|
||||
private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver();
|
||||
private LocalBroadcastManager lbm;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
@ -90,19 +103,24 @@ public class MainApp extends Application {
|
|||
sInstance = this;
|
||||
sResources = getResources();
|
||||
|
||||
registerLocalBroadcastReceiver();
|
||||
|
||||
if (pluginsList == null) {
|
||||
pluginsList = new ArrayList<>();
|
||||
// Register all tabs in app here
|
||||
pluginsList.add(OverviewFragment.getPlugin());
|
||||
pluginsList.add(IobCobCalculatorFragment.getPlugin());
|
||||
pluginsList.add(IobCobCalculatorPlugin.getPlugin());
|
||||
if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
|
||||
pluginsList.add(InsulinFastactingFragment.getPlugin());
|
||||
pluginsList.add(InsulinFastactingProlongedFragment.getPlugin());
|
||||
pluginsList.add(SensitivityOref0Plugin.getPlugin());
|
||||
pluginsList.add(SensitivityAAPSPlugin.getPlugin());
|
||||
pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
|
||||
if (Config.DANAR) pluginsList.add(DanaRFragment.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.MDI) pluginsList.add(MDIPlugin.getPlugin());
|
||||
if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getInstance());
|
||||
if (Config.LOOPENABLED) pluginsList.add(LoopFragment.getPlugin());
|
||||
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSMAFragment.getPlugin());
|
||||
|
@ -113,19 +131,19 @@ public class MainApp extends Application {
|
|||
if (Config.OTHERPROFILES)
|
||||
pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
|
||||
pluginsList.add(TreatmentsFragment.getPlugin());
|
||||
if (Config.SAFETY) pluginsList.add(SafetyFragment.getPlugin());
|
||||
if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
|
||||
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin());
|
||||
if (!Config.NSCLIENT)
|
||||
pluginsList.add(SourceXdripFragment.getPlugin());
|
||||
pluginsList.add(SourceNSClientFragment.getPlugin());
|
||||
pluginsList.add(SourceXdripPlugin.getPlugin());
|
||||
pluginsList.add(SourceNSClientPlugin.getPlugin());
|
||||
if (!Config.NSCLIENT)
|
||||
pluginsList.add(SourceMM640gFragment.getPlugin());
|
||||
pluginsList.add(SourceMM640gPlugin.getPlugin());
|
||||
if (!Config.NSCLIENT)
|
||||
pluginsList.add(SourceGlimpFragment.getPlugin());
|
||||
pluginsList.add(SourceGlimpPlugin.getPlugin());
|
||||
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorFragment.getPlugin());
|
||||
|
||||
if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this));
|
||||
pluginsList.add(StatuslineFragment.getPlugin(this));
|
||||
pluginsList.add(StatuslinePlugin.getPlugin(this));
|
||||
pluginsList.add(new PersistentNotificationPlugin(this));
|
||||
pluginsList.add(NSClientInternalFragment.getPlugin());
|
||||
|
||||
|
@ -150,6 +168,29 @@ public class MainApp extends Application {
|
|||
}
|
||||
});
|
||||
t.start();
|
||||
|
||||
}
|
||||
|
||||
private void registerLocalBroadcastReceiver() {
|
||||
lbm = LocalBroadcastManager.getInstance(this);
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_TREATMENT));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_TREATMENT));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_SGV));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_PROFILE));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_STATUS));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_MBG));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_DEVICESTATUS));
|
||||
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_CAL));
|
||||
|
||||
//register alarms
|
||||
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ALARM));
|
||||
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ANNOUNCEMENT));
|
||||
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_CLEAR_ALARM));
|
||||
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_URGENT_ALARM));
|
||||
|
||||
//register ack alarm
|
||||
lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM));
|
||||
}
|
||||
|
||||
private void startKeepAliveService() {
|
||||
|
|
|
@ -21,9 +21,14 @@ import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugi
|
|||
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
|
||||
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
|
||||
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
|
||||
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
|
||||
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
|
||||
import info.nightscout.utils.LocaleHelper;
|
||||
import info.nightscout.utils.OKDialog;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
|
||||
MyPreferenceFragment myPreferenceFragment;
|
||||
|
@ -43,10 +48,13 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
|
|||
String lang = sharedPreferences.getString("language", "en");
|
||||
LocaleHelper.setLocale(getApplicationContext(), lang);
|
||||
recreate();
|
||||
MainApp.bus().post(new EventRefreshGui(true));
|
||||
MainApp.bus().post(new EventRefreshGui());
|
||||
}
|
||||
if (key.equals("short_tabtitles")) {
|
||||
MainApp.bus().post(new EventRefreshGui(true));
|
||||
MainApp.bus().post(new EventRefreshGui());
|
||||
}
|
||||
if (key.equals("openapsama_useautosens") && SP.getBoolean("openapsama_useautosens", false)) {
|
||||
OKDialog.show(this, MainApp.sResources.getString(R.string.configbuilder_sensitivity), MainApp.sResources.getString(R.string.sensitivity_warning), null);
|
||||
}
|
||||
updatePrefSummary(myPreferenceFragment.getPreference(key));
|
||||
}
|
||||
|
@ -88,8 +96,8 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
|
|||
super.onCreate(savedInstanceState);
|
||||
if (Config.ALLPREFERENCES) {
|
||||
addPreferencesFromResource(R.xml.pref_password);
|
||||
addPreferencesFromResource(R.xml.pref_age);
|
||||
}
|
||||
addPreferencesFromResource(R.xml.pref_age);
|
||||
addPreferencesFromResource(R.xml.pref_language);
|
||||
if (Config.ALLPREFERENCES) {
|
||||
addPreferencesFromResource(R.xml.pref_quickwizard);
|
||||
|
@ -105,6 +113,11 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
|
|||
if (MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class) != null && MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class).isEnabled(PluginBase.APS))
|
||||
addPreferencesFromResource(R.xml.pref_openapsama);
|
||||
}
|
||||
if (MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class) != null && MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class).isEnabled(PluginBase.SENSITIVITY)
|
||||
|| MainApp.getSpecificPlugin(SensitivityWeightedAveragePlugin.class) != null && MainApp.getSpecificPlugin(SensitivityWeightedAveragePlugin.class).isEnabled(PluginBase.SENSITIVITY))
|
||||
addPreferencesFromResource(R.xml.pref_absorption_aaps);
|
||||
if (MainApp.getSpecificPlugin(SensitivityOref0Plugin.class) != null && MainApp.getSpecificPlugin(SensitivityOref0Plugin.class).isEnabled(PluginBase.SENSITIVITY))
|
||||
addPreferencesFromResource(R.xml.pref_absorption_oref0);
|
||||
if (Config.ALLPREFERENCES) {
|
||||
addPreferencesFromResource(R.xml.pref_profile);
|
||||
}
|
||||
|
@ -134,8 +147,8 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
|
|||
addPreferencesFromResource(R.xml.pref_smscommunicator);
|
||||
if (Config.ALLPREFERENCES) {
|
||||
addPreferencesFromResource(R.xml.pref_others);
|
||||
addPreferencesFromResource(R.xml.pref_advanced);
|
||||
}
|
||||
addPreferencesFromResource(R.xml.pref_advanced);
|
||||
|
||||
if (Config.WEAR) {
|
||||
WearPlugin wearPlugin = (WearPlugin) MainApp.getSpecificPlugin(WearPlugin.class);
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
package info.nightscout.androidaps.Services;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.res.AssetFileDescriptor;
|
||||
import android.media.MediaPlayer;
|
||||
import android.os.IBinder;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
|
||||
public class AlarmSoundService extends Service {
|
||||
private static Logger log = LoggerFactory.getLogger(AlarmSoundService.class);
|
||||
|
||||
MediaPlayer player;
|
||||
int resourceId = R.raw.error;
|
||||
|
||||
public AlarmSoundService() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
// TODO: Return the communication channel to the service.
|
||||
throw new UnsupportedOperationException("Not yet implemented");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
log.debug("onCreate");
|
||||
}
|
||||
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
if (player != null && player.isPlaying())
|
||||
player.stop();
|
||||
log.debug("onStartCommand");
|
||||
if (intent != null && intent.hasExtra("soundid"))
|
||||
resourceId = intent.getIntExtra("soundid", R.raw.error);
|
||||
|
||||
player = new MediaPlayer();
|
||||
AssetFileDescriptor afd = MainApp.sResources.openRawResourceFd(resourceId);
|
||||
if (afd == null)
|
||||
return START_STICKY;
|
||||
try {
|
||||
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
|
||||
afd.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
player.setLooping(true); // Set looping
|
||||
player.setVolume(100, 100);
|
||||
|
||||
try {
|
||||
player.prepare();
|
||||
player.start();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
player.stop();
|
||||
player.release();
|
||||
}
|
||||
}
|
|
@ -2,6 +2,7 @@ package info.nightscout.androidaps.Services;
|
|||
|
||||
import android.app.IntentService;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Telephony;
|
||||
|
||||
|
@ -11,10 +12,7 @@ import org.json.JSONObject;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import info.nightscout.androidaps.Config;
|
||||
import info.nightscout.androidaps.Constants;
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.db.BgReading;
|
||||
|
@ -25,18 +23,20 @@ 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.NSClientInternal.data.NSSettingsStatus;
|
||||
import info.nightscout.androidaps.plugins.Overview.Notification;
|
||||
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
|
||||
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
|
||||
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
|
||||
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
|
||||
import info.nightscout.androidaps.plugins.PumpDanaR.History.DanaRNSHistorySync;
|
||||
import info.nightscout.androidaps.plugins.PumpDanaR.activities.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.receivers.DataReceiver;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
|
||||
|
@ -229,19 +229,27 @@ public class DataService extends IntentService {
|
|||
|
||||
|
||||
if (intent.getAction().equals(Intents.ACTION_NEW_STATUS)) {
|
||||
if (Config.logIncommingData)
|
||||
log.debug("Received status: " + bundles);
|
||||
if (bundles.containsKey("nsclientversioncode")) {
|
||||
ConfigBuilderPlugin.nightscoutVersionCode = bundles.getInt("nightscoutversioncode"); // for ver 1.2.3 contains 10203
|
||||
ConfigBuilderPlugin.nightscoutVersionName = bundles.getString("nightscoutversionname");
|
||||
ConfigBuilderPlugin.nsClientVersionCode = bundles.getInt("nsclientversioncode"); // for ver 1.17 contains 117
|
||||
ConfigBuilderPlugin.nsClientVersionName = bundles.getString("nsclientversionname");
|
||||
log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName);
|
||||
if (ConfigBuilderPlugin.nsClientVersionCode < 121) {
|
||||
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.sResources.getString(R.string.unsupportedclientver), Notification.URGENT);
|
||||
try {
|
||||
if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
|
||||
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.sResources.getString(R.string.unsupportedclientver), Notification.URGENT);
|
||||
MainApp.bus().post(new EventNewNotification(notification));
|
||||
} else {
|
||||
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
|
||||
}
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
|
||||
Notification notification = new Notification(Notification.OLD_NS, MainApp.sResources.getString(R.string.unsupportednsversion), Notification.URGENT);
|
||||
MainApp.bus().post(new EventNewNotification(notification));
|
||||
} else {
|
||||
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
|
||||
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS));
|
||||
}
|
||||
} else {
|
||||
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.sResources.getString(R.string.unsupportedclientver), Notification.URGENT);
|
||||
|
@ -250,18 +258,15 @@ public class DataService extends IntentService {
|
|||
if (bundles.containsKey("status")) {
|
||||
try {
|
||||
JSONObject statusJson = new JSONObject(bundles.getString("status"));
|
||||
if (statusJson.has("settings")) {
|
||||
JSONObject settings = statusJson.getJSONObject("settings");
|
||||
if (settings.has("thresholds")) {
|
||||
JSONObject thresholds = settings.getJSONObject("thresholds");
|
||||
if (thresholds.has("bgTargetTop")) {
|
||||
OverviewPlugin.bgTargetHigh = thresholds.getDouble("bgTargetTop");
|
||||
}
|
||||
if (thresholds.has("bgTargetBottom")) {
|
||||
OverviewPlugin.bgTargetLow = thresholds.getDouble("bgTargetBottom");
|
||||
}
|
||||
}
|
||||
}
|
||||
NSSettingsStatus.getInstance().setData(statusJson);
|
||||
if (Config.logIncommingData)
|
||||
log.debug("Received status: " + statusJson.toString());
|
||||
Double targetHigh = NSSettingsStatus.getInstance().getThreshold("bgTargetTop");
|
||||
Double targetlow = NSSettingsStatus.getInstance().getThreshold("bgTargetBottom");
|
||||
if (targetHigh != null)
|
||||
OverviewPlugin.bgTargetHigh = targetHigh;
|
||||
if (targetlow != null)
|
||||
OverviewPlugin.bgTargetLow = targetlow;
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
@ -270,8 +275,8 @@ public class DataService extends IntentService {
|
|||
if (intent.getAction().equals(Intents.ACTION_NEW_DEVICESTATUS)) {
|
||||
try {
|
||||
if (bundles.containsKey("devicestatus")) {
|
||||
String devicestatusesstring = bundles.getString("devicestatus");
|
||||
JSONObject devicestatusJson = new JSONObject(bundles.getString("devicestatus"));
|
||||
NSDeviceStatus.getInstance().setData(devicestatusJson);
|
||||
if (devicestatusJson.has("pump")) {
|
||||
// Objectives 0
|
||||
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
|
||||
|
@ -281,8 +286,9 @@ public class DataService extends IntentService {
|
|||
if (bundles.containsKey("devicestatuses")) {
|
||||
String devicestatusesstring = bundles.getString("devicestatuses");
|
||||
JSONArray jsonArray = new JSONArray(devicestatusesstring);
|
||||
if (jsonArray.length() > 0) {
|
||||
JSONObject devicestatusJson = jsonArray.getJSONObject(0);
|
||||
for (int i = 0; i < jsonArray.length(); i++) {
|
||||
JSONObject devicestatusJson = jsonArray.getJSONObject(i);
|
||||
NSDeviceStatus.getInstance().setData(devicestatusJson);
|
||||
if (devicestatusJson.has("pump")) {
|
||||
// Objectives 0
|
||||
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
|
||||
|
@ -500,11 +506,11 @@ public class DataService extends IntentService {
|
|||
MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(trJson);
|
||||
}
|
||||
|
||||
if (trJson.getString("eventType").equals(CareportalEvent.ANNOUNCEMENT)) {
|
||||
if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.ANNOUNCEMENT)) {
|
||||
long date = trJson.getLong("mills");
|
||||
long now = new Date().getTime();
|
||||
long now = System.currentTimeMillis();
|
||||
if (date > now - 15 * 60 * 1000L && trJson.has("notes")) {
|
||||
Notification announcement = new Notification(Notification.ANNOUNCEMENT, trJson.getString("notes"), Notification.URGENT);
|
||||
Notification announcement = new Notification(Notification.NSANNOUNCEMENT, trJson.getString("notes"), Notification.ANNOUNCEMENT, 60);
|
||||
MainApp.bus().post(new EventNewNotification(announcement));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,12 +12,17 @@ public interface Intents {
|
|||
String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL";
|
||||
String ACTION_NEW_STATUS = "info.nightscout.client.NEW_STATUS";
|
||||
String ACTION_QUEUE_STATUS = "info.nightscout.client.QUEUE_STATUS";
|
||||
String ACTION_ANNOUNCEMENT = "info.nightscout.client.ANNOUNCEMENT";
|
||||
String ACTION_ALARM = "info.nightscout.client.ALARM";
|
||||
String ACTION_URGENT_ALARM = "info.nightscout.client.URGENT_ALARM";
|
||||
String ACTION_CLEAR_ALARM = "info.nightscout.client.CLEAR_ALARM";
|
||||
|
||||
|
||||
// App -> NSClient
|
||||
String ACTION_DATABASE = "info.nightscout.client.DBACCESS";
|
||||
String ACTION_RESTART = "info.nightscout.client.RESTART";
|
||||
String ACTION_RESEND = "info.nightscout.client.RESEND";
|
||||
String ACTION_ACK_ALARM = "info.nightscout.client.ACK_ALARM";
|
||||
|
||||
// xDrip -> App
|
||||
String RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_BG_ESTIMATE";
|
||||
|
|
|
@ -16,7 +16,7 @@ import info.nightscout.androidaps.interfaces.InsulinInterface;
|
|||
*/
|
||||
|
||||
public class DetailedBolusInfo {
|
||||
public long date = new Date().getTime();
|
||||
public long date = System.currentTimeMillis();
|
||||
public InsulinInterface insulinInterface = MainApp.getConfigBuilder().getActiveInsulin();
|
||||
public String eventType = CareportalEvent.MEALBOLUS;
|
||||
public double insulin = 0;
|
||||
|
@ -28,5 +28,6 @@ public class DetailedBolusInfo {
|
|||
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)
|
||||
public long pumpId = 0; // id of record if comming from pump history (not a newly created treatment)
|
||||
public boolean isSMB = false; // is a Super-MicroBolus
|
||||
}
|
||||
|
|
|
@ -67,11 +67,11 @@ public class GlucoseStatus {
|
|||
@Nullable
|
||||
public static GlucoseStatus getGlucoseStatusData() {
|
||||
// load 45min
|
||||
long fromtime = (long) (new Date().getTime() - 60 * 1000L * 45);
|
||||
long fromtime = (long) (System.currentTimeMillis() - 60 * 1000L * 45);
|
||||
List<BgReading> data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false);
|
||||
|
||||
int sizeRecords = data.size();
|
||||
if (sizeRecords < 1 || data.get(0).date < new Date().getTime() - 7 * 60 * 1000L) {
|
||||
if (sizeRecords < 1 || data.get(0).date < System.currentTimeMillis() - 7 * 60 * 1000L) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,90 @@
|
|||
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 abstract class Intervals<T extends Interval> {
|
||||
|
||||
LongSparseArray<T> rawData = new LongSparseArray<T>(); // oldest at index 0
|
||||
|
||||
public synchronized Intervals reset() {
|
||||
rawData = new LongSparseArray<T>();
|
||||
return this;
|
||||
}
|
||||
|
||||
protected abstract void merge();
|
||||
|
||||
/**
|
||||
* The List must be sorted by `T.start()` in ascending order
|
||||
*
|
||||
* */
|
||||
public synchronized void add(List<T> list) {
|
||||
for (T interval : list) {
|
||||
rawData.put(interval.start(), interval);
|
||||
}
|
||||
merge();
|
||||
}
|
||||
|
||||
|
||||
|
||||
public synchronized List<T> getList() {
|
||||
List<T> list = new ArrayList<>();
|
||||
for (int i = 0; i < rawData.size(); i++)
|
||||
list.add(rawData.valueAt(i));
|
||||
return list;
|
||||
}
|
||||
|
||||
public synchronized List<T> getReversedList() {
|
||||
List<T> list = new ArrayList<>();
|
||||
for (int i = rawData.size() -1; i>=0; i--)
|
||||
list.add(rawData.valueAt(i));
|
||||
return list;
|
||||
}
|
||||
|
||||
protected synchronized 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 abstract T getValueByInterval(long time);
|
||||
|
||||
public synchronized int size() {
|
||||
return rawData.size();
|
||||
}
|
||||
|
||||
public synchronized T get(int index) {
|
||||
return rawData.valueAt(index);
|
||||
}
|
||||
|
||||
public synchronized T getReversed(int index) {
|
||||
return rawData.valueAt(size() - 1 - index);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -9,17 +9,17 @@ import info.nightscout.utils.DateUtil;
|
|||
import info.nightscout.utils.Round;
|
||||
|
||||
public class IobTotal {
|
||||
public Double iob;
|
||||
public Double activity;
|
||||
public Double bolussnooze;
|
||||
public Double basaliob;
|
||||
public Double netbasalinsulin;
|
||||
public Double hightempinsulin;
|
||||
public double iob;
|
||||
public double activity;
|
||||
public double bolussnooze;
|
||||
public double basaliob;
|
||||
public double netbasalinsulin;
|
||||
public double hightempinsulin;
|
||||
|
||||
public Double netInsulin = 0d; // for calculations from temp basals only
|
||||
public Double netRatio = 0d; // net ratio at start of temp basal
|
||||
public double netInsulin = 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
|
||||
public double extendedBolusInsulin = 0d; // total insulin for extended bolus
|
||||
|
||||
long time;
|
||||
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
package info.nightscout.androidaps.data;
|
||||
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import info.nightscout.androidaps.interfaces.Interval;
|
||||
|
||||
/**
|
||||
* Created by adrian on 15/07/17.
|
||||
*/
|
||||
|
||||
public class NonOverlappingIntervals<T extends Interval> extends Intervals<T> {
|
||||
|
||||
protected synchronized 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 synchronized T getValueByInterval(long time) {
|
||||
int index = binarySearch(time);
|
||||
if (index >= 0) return rawData.valueAt(index);
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -1,99 +1,43 @@
|
|||
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 android.support.annotation.Nullable;
|
||||
|
||||
import info.nightscout.androidaps.interfaces.Interval;
|
||||
|
||||
/**
|
||||
* Created by mike on 09.05.2017.
|
||||
* Created by adrian on 15/07/17.
|
||||
*/
|
||||
|
||||
// Zero duration means end of interval
|
||||
public class OverlappingIntervals<T extends Interval> extends Intervals<T> {
|
||||
|
||||
public class OverlappingIntervals<T extends Interval> {
|
||||
protected synchronized void merge() {
|
||||
boolean needToCut = false;
|
||||
long cutTime = 0;
|
||||
|
||||
private LongSparseArray<T> 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<T> 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);
|
||||
for (int index = rawData.size()-1; index > 0; index--) { //begin with newest
|
||||
Interval cur = rawData.valueAt(index);
|
||||
if (cur.isEndingEvent()){
|
||||
needToCut = true;
|
||||
cutTime = cur.start();
|
||||
} else {
|
||||
//event that is no EndingEvent might need to be stopped by an ending event
|
||||
if(needToCut&&cur.end() > cutTime){
|
||||
cur.cutEndTo(cutTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Interval getValueByInterval(long time) {
|
||||
int index = binarySearch(time);
|
||||
if (index >= 0) return rawData.valueAt(index);
|
||||
public synchronized T getValueByInterval(long time) {
|
||||
for (int index = rawData.size()-1; index > 0; index--) { //begin with newest
|
||||
T cur = rawData.valueAt(index);
|
||||
if (cur.match(time)){
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
List<T> list = new ArrayList<>();
|
||||
for (int i = 0; i < rawData.size(); i++)
|
||||
list.add(rawData.valueAt(i));
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<T> getReversedList() {
|
||||
List<T> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package info.nightscout.androidaps.data;
|
||||
|
||||
import android.support.v4.util.LongSparseArray;
|
||||
|
||||
import com.crashlytics.android.Crashlytics;
|
||||
|
||||
import org.json.JSONArray;
|
||||
|
@ -30,8 +32,11 @@ public class Profile {
|
|||
double dia = Constants.defaultDIA;
|
||||
TimeZone timeZone = TimeZone.getDefault();
|
||||
JSONArray isf;
|
||||
private LongSparseArray<Double> isf_v = null; // oldest at index 0
|
||||
JSONArray ic;
|
||||
private LongSparseArray<Double> ic_v = null; // oldest at index 0
|
||||
JSONArray basal;
|
||||
private LongSparseArray<Double> basal_v = null; // oldest at index 0
|
||||
JSONArray targetLow;
|
||||
JSONArray targetHigh;
|
||||
|
||||
|
@ -112,7 +117,7 @@ public class Profile {
|
|||
public String log() {
|
||||
String ret = "\n";
|
||||
for (Integer hour = 0; hour < 24; hour++) {
|
||||
double value = getBasal(hour * 60 * 60);
|
||||
double value = getBasal((Integer) (hour * 60 * 60));
|
||||
ret += "NS basal value for " + hour + ":00 is " + value + "\n";
|
||||
}
|
||||
ret += "NS units: " + getUnits();
|
||||
|
@ -120,10 +125,16 @@ public class Profile {
|
|||
}
|
||||
|
||||
public JSONObject getData() {
|
||||
if (!json.has("units"))
|
||||
try {
|
||||
json.put("units", units);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
public Double getDia() {
|
||||
public double getDia() {
|
||||
return dia;
|
||||
}
|
||||
|
||||
|
@ -136,6 +147,21 @@ public class Profile {
|
|||
return timeZone;
|
||||
}
|
||||
|
||||
private LongSparseArray<Double> convertToSparseArray(JSONArray array) {
|
||||
LongSparseArray<Double> sparse = new LongSparseArray<>();
|
||||
for (Integer index = 0; index < array.length(); index++) {
|
||||
try {
|
||||
JSONObject o = array.getJSONObject(index);
|
||||
long tas = o.getLong("timeAsSeconds");
|
||||
Double value = o.getDouble("value");
|
||||
sparse.put(tas, value);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return sparse;
|
||||
}
|
||||
|
||||
private Double getValueToTime(JSONArray array, Integer timeAsSeconds) {
|
||||
Double lastValue = null;
|
||||
|
||||
|
@ -156,6 +182,21 @@ public class Profile {
|
|||
return lastValue;
|
||||
}
|
||||
|
||||
private Double getValueToTime(LongSparseArray<Double> array, long timeAsSeconds) {
|
||||
Double lastValue = null;
|
||||
|
||||
for (Integer index = 0; index < array.size(); index++) {
|
||||
long tas = array.keyAt(index);
|
||||
double value = array.valueAt(index);
|
||||
if (lastValue == null) lastValue = value;
|
||||
if (timeAsSeconds < tas) {
|
||||
break;
|
||||
}
|
||||
lastValue = value;
|
||||
}
|
||||
return lastValue;
|
||||
}
|
||||
|
||||
private String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) {
|
||||
String retValue = "";
|
||||
|
||||
|
@ -180,7 +221,7 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getIsf() {
|
||||
return getIsf(secondsFromMidnight(new Date().getTime()));
|
||||
return getIsf(secondsFromMidnight(System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
public Double getIsf(long time) {
|
||||
|
@ -188,7 +229,9 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getIsf(Integer timeAsSeconds) {
|
||||
return getValueToTime(isf, timeAsSeconds);
|
||||
if (isf_v == null)
|
||||
isf_v = convertToSparseArray(isf);
|
||||
return getValueToTime(isf_v, timeAsSeconds);
|
||||
}
|
||||
|
||||
public String getIsfList() {
|
||||
|
@ -196,7 +239,7 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getIc() {
|
||||
return getIc(secondsFromMidnight(new Date().getTime()));
|
||||
return getIc(secondsFromMidnight(System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
public Double getIc(long time) {
|
||||
|
@ -204,15 +247,17 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getIc(Integer timeAsSeconds) {
|
||||
return getValueToTime(ic, timeAsSeconds);
|
||||
if (ic_v == null)
|
||||
ic_v = convertToSparseArray(ic);
|
||||
return getValueToTime(ic_v, timeAsSeconds);
|
||||
}
|
||||
|
||||
public String getIcList() {
|
||||
return getValuesList(ic, null, new DecimalFormat("0.0"), getUnits() + "/U");
|
||||
return getValuesList(ic, null, new DecimalFormat("0.0"), " g/U");
|
||||
}
|
||||
|
||||
public Double getBasal() {
|
||||
return getBasal(secondsFromMidnight(new Date().getTime()));
|
||||
return getBasal(secondsFromMidnight(System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
public Double getBasal(long time) {
|
||||
|
@ -220,7 +265,9 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getBasal(Integer timeAsSeconds) {
|
||||
return getValueToTime(basal, timeAsSeconds);
|
||||
if (basal_v == null)
|
||||
basal_v = convertToSparseArray(basal);
|
||||
return getValueToTime(basal_v, timeAsSeconds);
|
||||
}
|
||||
|
||||
public String getBasalList() {
|
||||
|
@ -255,7 +302,7 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getTargetLow() {
|
||||
return getTargetLow(secondsFromMidnight(new Date().getTime()));
|
||||
return getTargetLow(secondsFromMidnight(System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
public Double getTargetLow(long time) {
|
||||
|
@ -267,7 +314,7 @@ public class Profile {
|
|||
}
|
||||
|
||||
public Double getTargetHigh() {
|
||||
return getTargetHigh(secondsFromMidnight(new Date().getTime()));
|
||||
return getTargetHigh(secondsFromMidnight(System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
public Double getTargetHigh(long time) {
|
||||
|
@ -285,7 +332,7 @@ public class Profile {
|
|||
public double getMaxDailyBasal() {
|
||||
Double max = 0d;
|
||||
for (Integer hour = 0; hour < 24; hour++) {
|
||||
double value = getBasal(hour * 60 * 60);
|
||||
double value = getBasal((Integer)(hour * 60 * 60));
|
||||
if (value > max) max = value;
|
||||
}
|
||||
return max;
|
||||
|
|
|
@ -19,24 +19,24 @@ public class ProfileIntervals<T extends Interval> {
|
|||
|
||||
private LongSparseArray<T> rawData = new LongSparseArray<>(); // oldest at index 0
|
||||
|
||||
public ProfileIntervals reset() {
|
||||
public synchronized ProfileIntervals reset() {
|
||||
rawData = new LongSparseArray<>();
|
||||
return this;
|
||||
}
|
||||
|
||||
public void add(T newInterval) {
|
||||
public synchronized void add(T newInterval) {
|
||||
rawData.put(newInterval.start(), newInterval);
|
||||
merge();
|
||||
}
|
||||
|
||||
public void add(List<T> list) {
|
||||
public synchronized void add(List<T> list) {
|
||||
for (T interval : list) {
|
||||
rawData.put(interval.start(), interval);
|
||||
}
|
||||
merge();
|
||||
}
|
||||
|
||||
private void merge() {
|
||||
private synchronized void merge() {
|
||||
for (int index = 0; index < rawData.size() - 1; index++) {
|
||||
Interval i = rawData.valueAt(index);
|
||||
long startOfNewer = rawData.valueAt(index + 1).start();
|
||||
|
@ -47,27 +47,27 @@ public class ProfileIntervals<T extends Interval> {
|
|||
}
|
||||
|
||||
@Nullable
|
||||
public Interval getValueToTime(long time) {
|
||||
public synchronized Interval getValueToTime(long time) {
|
||||
int index = binarySearch(time);
|
||||
if (index >= 0) return rawData.valueAt(index);
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
public synchronized List<T> getList() {
|
||||
List<T> list = new ArrayList<>();
|
||||
for (int i = 0; i < rawData.size(); i++)
|
||||
list.add(rawData.valueAt(i));
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<T> getReversedList() {
|
||||
public synchronized List<T> getReversedList() {
|
||||
List<T> list = new ArrayList<>();
|
||||
for (int i = rawData.size() -1; i>=0; i--)
|
||||
list.add(rawData.valueAt(i));
|
||||
return list;
|
||||
}
|
||||
|
||||
private int binarySearch(long value) {
|
||||
private synchronized int binarySearch(long value) {
|
||||
if (rawData.size() == 0)
|
||||
return -1;
|
||||
int lo = 0;
|
||||
|
@ -95,15 +95,15 @@ public class ProfileIntervals<T extends Interval> {
|
|||
return -1; // value not present
|
||||
}
|
||||
|
||||
public int size() {
|
||||
public synchronized int size() {
|
||||
return rawData.size();
|
||||
}
|
||||
|
||||
public T get(int index) {
|
||||
public synchronized T get(int index) {
|
||||
return rawData.valueAt(index);
|
||||
}
|
||||
|
||||
public T getReversed(int index) {
|
||||
public synchronized T getReversed(int index) {
|
||||
return rawData.valueAt(size() - 1 - index);
|
||||
}
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package info.nightscout.androidaps.data;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v4.util.ArrayMap;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
@ -10,6 +11,8 @@ import org.slf4j.LoggerFactory;
|
|||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
|
||||
import info.nightscout.androidaps.Constants;
|
||||
|
||||
/**
|
||||
* Created by mike on 01.06.2017.
|
||||
*/
|
||||
|
@ -17,9 +20,13 @@ import java.util.Iterator;
|
|||
public class ProfileStore {
|
||||
private static Logger log = LoggerFactory.getLogger(ProfileStore.class);
|
||||
private JSONObject json = null;
|
||||
private String units = Constants.MGDL;
|
||||
|
||||
ArrayMap<String, Profile> cachedObjects = new ArrayMap<>();
|
||||
|
||||
public ProfileStore(JSONObject json) {
|
||||
this.json = json;
|
||||
getDefaultProfile(); // initialize units
|
||||
}
|
||||
|
||||
public JSONObject getData() {
|
||||
|
@ -33,10 +40,14 @@ public class ProfileStore {
|
|||
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);
|
||||
profile = cachedObjects.get(defaultProfileName);
|
||||
if (profile == null) {
|
||||
if (store.has("units"))
|
||||
units = store.getString("units");
|
||||
profile = new Profile(store.getJSONObject(defaultProfileName), units);
|
||||
units = profile.getUnits();
|
||||
cachedObjects.put(defaultProfileName, profile);
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
|
@ -59,16 +70,24 @@ public class ProfileStore {
|
|||
return defaultProfileName;
|
||||
}
|
||||
|
||||
public String getUnits() {
|
||||
return units;
|
||||
}
|
||||
|
||||
@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);
|
||||
profile = cachedObjects.get(profileName);
|
||||
if (profile == null) {
|
||||
if (store.has("units"))
|
||||
units = store.getString("units");
|
||||
profile = new Profile(store.getJSONObject(profileName), units);
|
||||
units = profile.getUnits();
|
||||
cachedObjects.put(profileName, profile);
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
|
|
|
@ -69,7 +69,9 @@ public class BgReading implements DataPointWithLabelInterface {
|
|||
|
||||
public String directionToSymbol() {
|
||||
String symbol = "";
|
||||
if (direction.compareTo("DoubleDown") == 0) {
|
||||
if (direction == null) {
|
||||
symbol = "??";
|
||||
} else if (direction.compareTo("DoubleDown") == 0) {
|
||||
symbol = "\u21ca";
|
||||
} else if (direction.compareTo("SingleDown") == 0) {
|
||||
symbol = "\u2193";
|
||||
|
@ -158,7 +160,7 @@ public class BgReading implements DataPointWithLabelInterface {
|
|||
|
||||
@Override
|
||||
public double getY() {
|
||||
String units = MainApp.getConfigBuilder().getProfile().getUnits();
|
||||
String units = MainApp.getConfigBuilder().getProfileUnits();
|
||||
return valueToUnits(units);
|
||||
}
|
||||
|
||||
|
@ -190,7 +192,7 @@ public class BgReading implements DataPointWithLabelInterface {
|
|||
|
||||
@Override
|
||||
public int getColor() {
|
||||
String units = MainApp.getConfigBuilder().getProfile().getUnits();
|
||||
String units = MainApp.getConfigBuilder().getProfileUnits();
|
||||
Double lowLine = SP.getDouble("low_mark", 0d);
|
||||
Double highLine = SP.getDouble("high_mark", 0d);
|
||||
if (lowLine < 1) {
|
||||
|
|
|
@ -24,6 +24,7 @@ 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.OverviewFragment;
|
||||
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
|
||||
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
|
||||
import info.nightscout.utils.DateUtil;
|
||||
|
@ -81,16 +82,19 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
}
|
||||
|
||||
public long getMillisecondsFromStart() {
|
||||
return new Date().getTime() - date;
|
||||
return System.currentTimeMillis() - date;
|
||||
}
|
||||
|
||||
public long getHoursFromStart() {
|
||||
return (new Date().getTime() - date) / (60 * 1000);
|
||||
return (System.currentTimeMillis() - date) / (60 * 1000);
|
||||
}
|
||||
|
||||
public String age() {
|
||||
Map<TimeUnit,Long> 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);
|
||||
Map<TimeUnit, Long> diff = computeDiff(date, System.currentTimeMillis());
|
||||
if (OverviewFragment.shorttextmode)
|
||||
return diff.get(TimeUnit.DAYS) +"d" + diff.get(TimeUnit.HOURS) + "h";
|
||||
else
|
||||
return diff.get(TimeUnit.DAYS) + " " + MainApp.sResources.getString(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.sResources.getString(R.string.hours);
|
||||
}
|
||||
|
||||
public String log() {
|
||||
|
@ -105,17 +109,17 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
}
|
||||
|
||||
//Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
|
||||
public static Map<TimeUnit,Long> computeDiff(long date1, long date2) {
|
||||
public static Map<TimeUnit, Long> computeDiff(long date1, long date2) {
|
||||
long diffInMillies = date2 - date1;
|
||||
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
|
||||
Collections.reverse(units);
|
||||
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
|
||||
Map<TimeUnit, Long> result = new LinkedHashMap<TimeUnit, Long>();
|
||||
long milliesRest = diffInMillies;
|
||||
for ( TimeUnit unit : units ) {
|
||||
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
|
||||
for (TimeUnit unit : units) {
|
||||
long diff = unit.convert(milliesRest, TimeUnit.MILLISECONDS);
|
||||
long diffInMilliesForUnit = unit.toMillis(diff);
|
||||
milliesRest = milliesRest - diffInMilliesForUnit;
|
||||
result.put(unit,diff);
|
||||
result.put(unit, diff);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
@ -131,7 +135,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
|
||||
@Override
|
||||
public double getY() {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
String units = MainApp.getConfigBuilder().getProfileUnits();
|
||||
if (eventType.equals(MBG)) {
|
||||
double mbg = 0d;
|
||||
try {
|
||||
|
@ -140,13 +144,10 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (profile != null)
|
||||
return profile.fromMgdlToUnits(mbg, profile.getUnits());
|
||||
return 0d;
|
||||
return Profile.fromMgdlToUnits(mbg, units);
|
||||
}
|
||||
|
||||
double glucose = 0d;
|
||||
String units = Constants.MGDL;
|
||||
try {
|
||||
JSONObject object = new JSONObject(json);
|
||||
if (object.has("glucose")) {
|
||||
|
@ -156,7 +157,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (profile != null && glucose != 0d) {
|
||||
if (glucose != 0d) {
|
||||
double mmol = 0d;
|
||||
double mgdl = 0;
|
||||
if (units.equals(Constants.MGDL)) {
|
||||
|
@ -167,7 +168,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
mmol = glucose;
|
||||
mgdl = glucose * Constants.MMOLL_TO_MGDL;
|
||||
}
|
||||
return profile.toUnits(mgdl, mmol, profile.getUnits());
|
||||
return Profile.toUnits(mgdl, mmol, units);
|
||||
}
|
||||
|
||||
return yValue;
|
||||
|
@ -230,7 +231,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
|
|||
@Override
|
||||
public int getColor() {
|
||||
if (eventType.equals(ANNOUNCEMENT))
|
||||
return 0xFFFF8C00;
|
||||
return MainApp.sResources.getColor(R.color.notificationAnnouncement);
|
||||
if (eventType.equals(MBG))
|
||||
return Color.RED;
|
||||
if (eventType.equals(BGCHECK))
|
||||
|
|
|
@ -21,7 +21,6 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
@ -36,14 +35,16 @@ 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.EventRefreshOverview;
|
||||
import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
|
||||
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;
|
||||
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
|
||||
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
|
||||
|
||||
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
||||
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
|
||||
|
@ -59,7 +60,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
|
||||
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
|
||||
|
||||
private static final int DATABASE_VERSION = 7;
|
||||
private static final int DATABASE_VERSION = 8;
|
||||
|
||||
private static Long earliestDataChange = null;
|
||||
|
||||
|
@ -112,17 +113,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
@Override
|
||||
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
|
||||
try {
|
||||
log.info(DatabaseHelper.class.getName(), "onUpgrade");
|
||||
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);
|
||||
if (oldVersion == 7 && newVersion == 8) {
|
||||
log.debug("Upgrading database from v7 to v8");
|
||||
TableUtils.dropTable(connectionSource, Treatment.class, true);
|
||||
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
|
||||
} else {
|
||||
log.info(DatabaseHelper.class.getName(), "onUpgrade");
|
||||
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);
|
||||
throw new RuntimeException(e);
|
||||
|
@ -140,35 +147,35 @@ 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, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
|
||||
getWritableDatabase().delete(DATABASE_BGREADINGS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
|
||||
log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
|
||||
|
||||
log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
|
||||
getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
|
||||
getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (System.currentTimeMillis() - 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, "date" + " < '" + (new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
|
||||
getWritableDatabase().delete(DATABASE_TREATMENTS, "date" + " < '" + (System.currentTimeMillis() - 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);
|
||||
getWritableDatabase().delete(DATABASE_DANARHISTORY, "recordDate" + " < '" + (System.currentTimeMillis() - 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);
|
||||
getWritableDatabase().delete(DATABASE_TEMPORARYBASALS, "recordDate" + " < '" + (System.currentTimeMillis() - 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);
|
||||
getWritableDatabase().delete(DATABASE_EXTENDEDBOLUSES, "recordDate" + " < '" + (System.currentTimeMillis() - 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);
|
||||
getWritableDatabase().delete(DATABASE_CAREPORTALEVENTS, "recordDate" + " < '" + (System.currentTimeMillis() - 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);
|
||||
getWritableDatabase().delete(DATABASE_PROFILESWITCHES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
|
||||
log.debug("After ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
|
||||
}
|
||||
|
||||
|
@ -202,6 +209,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
VirtualPumpPlugin.setFakingStatus(true);
|
||||
scheduleBgChange(); // trigger refresh
|
||||
scheduleTemporaryBasalChange();
|
||||
scheduleTreatmentChange();
|
||||
|
@ -213,7 +221,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
new java.util.TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
MainApp.bus().post(new EventRefreshGui(false));
|
||||
MainApp.bus().post(new EventRefreshOverview("resetDatabases"));
|
||||
}
|
||||
},
|
||||
3000
|
||||
|
@ -249,6 +257,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
VirtualPumpPlugin.setFakingStatus(false);
|
||||
scheduleTemporaryBasalChange();
|
||||
}
|
||||
|
||||
|
@ -402,7 +411,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
if (lastBg == null)
|
||||
return null;
|
||||
|
||||
if (lastBg.date > new Date().getTime() - 9 * 60 * 1000)
|
||||
if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000)
|
||||
return lastBg;
|
||||
|
||||
return null;
|
||||
|
@ -680,6 +689,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
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("isSMB"))
|
||||
treatment.isSMB = trJson.getBoolean("isSMB");
|
||||
if (trJson.has("eventType")) {
|
||||
treatment.mealBolus = !trJson.get("eventType").equals("Correction Bolus");
|
||||
double carbs = treatment.carbs;
|
||||
|
@ -815,8 +826,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
|
||||
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
|
||||
try {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
String units = profile.getUnits();
|
||||
String units = MainApp.getConfigBuilder().getProfileUnits();
|
||||
TempTarget tempTarget = new TempTarget();
|
||||
tempTarget.date = trJson.getLong("mills");
|
||||
tempTarget.durationInMinutes = trJson.getInt("duration");
|
||||
|
@ -940,6 +950,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
if (tempBasal.source == Source.NIGHTSCOUT) {
|
||||
old = getDaoTemporaryBasal().queryForId(tempBasal.date);
|
||||
if (old != null) {
|
||||
if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute"
|
||||
// so far ignore, do not convert back because it may not be accurate
|
||||
return false;
|
||||
}
|
||||
if (!old.isEqual(tempBasal)) {
|
||||
long oldDate = old.date;
|
||||
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
|
||||
|
@ -1068,6 +1082,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
extendedBolus.durationInMinutes = trJson.getInt("duration");
|
||||
extendedBolus.insulin = trJson.getDouble("originalExtendedAmount");
|
||||
extendedBolus._id = trJson.getString("_id");
|
||||
if (!VirtualPumpPlugin.getFakingStatus()) {
|
||||
VirtualPumpPlugin.setFakingStatus(true);
|
||||
updateEarliestDataChange(0);
|
||||
scheduleTemporaryBasalChange();
|
||||
}
|
||||
createOrUpdate(extendedBolus);
|
||||
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
|
||||
ExtendedBolus extendedBolus = new ExtendedBolus();
|
||||
|
@ -1077,6 +1096,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
extendedBolus.durationInMinutes = 0;
|
||||
extendedBolus.insulin = 0;
|
||||
extendedBolus._id = trJson.getString("_id");
|
||||
if (!VirtualPumpPlugin.getFakingStatus()) {
|
||||
VirtualPumpPlugin.setFakingStatus(true);
|
||||
updateEarliestDataChange(0);
|
||||
scheduleTemporaryBasalChange();
|
||||
}
|
||||
createOrUpdate(extendedBolus);
|
||||
} else {
|
||||
TemporaryBasal tempBasal = new TemporaryBasal();
|
||||
|
@ -1153,7 +1177,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
getDaoExtendedBolus().create(extendedBolus);
|
||||
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
|
||||
updateEarliestDataChange(extendedBolus.date);
|
||||
scheduleTreatmentChange();
|
||||
scheduleExtendedBolusChange();
|
||||
return true;
|
||||
}
|
||||
if (extendedBolus.source == Source.NIGHTSCOUT) {
|
||||
|
@ -1167,7 +1191,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString());
|
||||
updateEarliestDataChange(oldDate);
|
||||
updateEarliestDataChange(old.date);
|
||||
scheduleTreatmentChange();
|
||||
scheduleExtendedBolusChange();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
@ -1189,7 +1213,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString());
|
||||
updateEarliestDataChange(oldDate);
|
||||
updateEarliestDataChange(old.date);
|
||||
scheduleTreatmentChange();
|
||||
scheduleExtendedBolusChange();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -1197,14 +1221,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
getDaoExtendedBolus().create(extendedBolus);
|
||||
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
|
||||
updateEarliestDataChange(extendedBolus.date);
|
||||
scheduleTreatmentChange();
|
||||
scheduleExtendedBolusChange();
|
||||
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();
|
||||
scheduleExtendedBolusChange();
|
||||
return true;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
|
@ -1248,6 +1272,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
scheduleExtendedBolusChange();
|
||||
}
|
||||
}
|
||||
|
||||
public ExtendedBolus findExtendedBolusById(String _id) {
|
||||
try {
|
||||
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
|
||||
|
@ -1504,7 +1529,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
old.copyFrom(profileSwitch);
|
||||
getDaoProfileSwitch().create(old);
|
||||
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
|
||||
scheduleTemporaryTargetChange();
|
||||
scheduleProfileSwitchChange();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
@ -1523,20 +1548,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
old.copyFrom(profileSwitch);
|
||||
getDaoProfileSwitch().create(old);
|
||||
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
|
||||
scheduleTemporaryTargetChange();
|
||||
scheduleProfileSwitchChange();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
getDaoProfileSwitch().create(profileSwitch);
|
||||
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
|
||||
scheduleTemporaryTargetChange();
|
||||
scheduleProfileSwitchChange();
|
||||
return true;
|
||||
}
|
||||
if (profileSwitch.source == Source.USER) {
|
||||
getDaoProfileSwitch().create(profileSwitch);
|
||||
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
|
||||
scheduleTemporaryTargetChange();
|
||||
scheduleProfileSwitchChange();
|
||||
return true;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
|
@ -1558,6 +1583,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
|
|||
class PostRunnable implements Runnable {
|
||||
public void run() {
|
||||
log.debug("Firing EventProfileSwitchChange");
|
||||
MainApp.bus().post(new EventReloadProfileSwitchData());
|
||||
MainApp.bus().post(new EventProfileSwitchChange());
|
||||
scheduledProfileSwitchEventPost = null;
|
||||
}
|
||||
|
|
|
@ -139,7 +139,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
|
|||
|
||||
@Override
|
||||
public boolean isInProgress() {
|
||||
return match(new Date().getTime());
|
||||
return match(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -171,31 +171,27 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
|
|||
|
||||
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;
|
||||
double dia_ago = time - dia * 60 * 60 * 1000;
|
||||
int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
|
||||
double spacing = realDuration / aboutFiveMinIntervals;
|
||||
|
||||
for (Long j = 0L; j < aboutFiveMinIntervals; j++) {
|
||||
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);
|
||||
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);
|
||||
Treatment tempBolusPart = new Treatment(insulinInterface, dia);
|
||||
tempBolusPart.insulin = tempBolusSize;
|
||||
tempBolusPart.date = calcdate;
|
||||
|
||||
Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, profile.getDia());
|
||||
Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, dia);
|
||||
result.iob += aIOB.iobContrib;
|
||||
result.activity += aIOB.activityContrib;
|
||||
result.extendedBolusInsulin += tempBolusPart.insulin;
|
||||
|
@ -206,7 +202,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
|
|||
}
|
||||
|
||||
public int getRealDuration() {
|
||||
return getDurationToTime(new Date().getTime());
|
||||
return getDurationToTime(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private int getDurationToTime(long time) {
|
||||
|
@ -216,7 +212,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
|
|||
}
|
||||
|
||||
public int getPlannedRemainingMinutes() {
|
||||
float remainingMin = (end() - new Date().getTime()) / 1000f / 60;
|
||||
float remainingMin = (end() - System.currentTimeMillis()) / 1000f / 60;
|
||||
return (remainingMin < 0) ? 0 : Math.round(remainingMin);
|
||||
}
|
||||
|
||||
|
|
|
@ -5,12 +5,15 @@ 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.Objects;
|
||||
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.androidaps.interfaces.Interval;
|
||||
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
|
||||
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
|
||||
|
@ -50,6 +53,18 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
|
|||
@DatabaseField
|
||||
public int durationInMinutes = 0;
|
||||
|
||||
private Profile profile = null;
|
||||
|
||||
public Profile getProfileObject() {
|
||||
if (profile == null)
|
||||
try {
|
||||
profile = new Profile(new JSONObject(profileJson));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
public boolean isEqual(ProfileSwitch other) {
|
||||
if (date != other.date) {
|
||||
return false;
|
||||
|
@ -133,7 +148,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
|
|||
|
||||
@Override
|
||||
public boolean isInProgress() {
|
||||
return match(new Date().getTime());
|
||||
return match(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -187,7 +202,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
|
|||
return Color.CYAN;
|
||||
}
|
||||
|
||||
public String log() {
|
||||
public String toString() {
|
||||
return "ProfileSwitch{" +
|
||||
"date=" + date +
|
||||
"date=" + DateUtil.dateAndTimeString(date) +
|
||||
|
|
|
@ -51,7 +51,7 @@ public class TempTarget implements Interval {
|
|||
return false;
|
||||
if (high != other.high)
|
||||
return false;
|
||||
if (reason != other.reason)
|
||||
if (!Objects.equals(reason, other.reason))
|
||||
return false;
|
||||
if (!Objects.equals(_id, other._id))
|
||||
return false;
|
||||
|
@ -115,7 +115,7 @@ public class TempTarget implements Interval {
|
|||
|
||||
@Override
|
||||
public boolean isInProgress() {
|
||||
return match(new Date().getTime());
|
||||
return match(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -10,6 +10,7 @@ import java.util.Date;
|
|||
import java.util.Objects;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.data.Iob;
|
||||
import info.nightscout.androidaps.data.IobTotal;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
|
@ -18,6 +19,7 @@ import info.nightscout.androidaps.interfaces.Interval;
|
|||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
|
||||
import info.nightscout.utils.DateUtil;
|
||||
import info.nightscout.utils.DecimalFormatter;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 21.05.2017.
|
||||
|
@ -45,11 +47,16 @@ public class TemporaryBasal implements Interval {
|
|||
public int durationInMinutes = 0; // duration == 0 means end of temp basal
|
||||
@DatabaseField
|
||||
public boolean isAbsolute = false;
|
||||
|
||||
public boolean isFakeExtended = false;
|
||||
|
||||
@DatabaseField
|
||||
public int percentRate = 0;
|
||||
@DatabaseField
|
||||
public double absoluteRate = 0d;
|
||||
|
||||
public double netExtendedRate = 0d;
|
||||
|
||||
public TemporaryBasal() {
|
||||
}
|
||||
|
||||
|
@ -65,6 +72,8 @@ public class TemporaryBasal implements Interval {
|
|||
this._id = extendedBolus._id;
|
||||
this.durationInMinutes = extendedBolus.durationInMinutes;
|
||||
this.isAbsolute = true;
|
||||
this.isFakeExtended = true;
|
||||
this.netExtendedRate = extendedBolus.absoluteRate();
|
||||
this.absoluteRate = basal + extendedBolus.absoluteRate();
|
||||
}
|
||||
|
||||
|
@ -94,6 +103,10 @@ public class TemporaryBasal implements Interval {
|
|||
return false;
|
||||
if (absoluteRate != other.absoluteRate)
|
||||
return false;
|
||||
if (netExtendedRate != other.netExtendedRate)
|
||||
return false;
|
||||
if (isFakeExtended != other.isFakeExtended)
|
||||
return false;
|
||||
if (pumpId != other.pumpId)
|
||||
return false;
|
||||
if (!Objects.equals(_id, other._id))
|
||||
|
@ -109,6 +122,8 @@ public class TemporaryBasal implements Interval {
|
|||
percentRate = t.percentRate;
|
||||
absoluteRate = t.absoluteRate;
|
||||
pumpId = t.pumpId;
|
||||
isFakeExtended = t.isFakeExtended;
|
||||
netExtendedRate = t.netExtendedRate;
|
||||
}
|
||||
|
||||
// -------- Interval interface ---------
|
||||
|
@ -159,7 +174,7 @@ public class TemporaryBasal implements Interval {
|
|||
|
||||
@Override
|
||||
public boolean isInProgress() {
|
||||
return match(new Date().getTime());
|
||||
return match(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -170,23 +185,29 @@ public class TemporaryBasal implements Interval {
|
|||
// -------- Interval interface end ---------
|
||||
|
||||
public IobTotal iobCalc(long time) {
|
||||
|
||||
if(isFakeExtended){
|
||||
log.error("iobCalc should only be called on Extended boluses separately");
|
||||
return new IobTotal(time);
|
||||
}
|
||||
|
||||
IobTotal result = new IobTotal(time);
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile(time);
|
||||
InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
|
||||
|
||||
int realDuration = getDurationToTime(time);
|
||||
Double netBasalAmount = 0d;
|
||||
double netBasalAmount = 0d;
|
||||
|
||||
if (realDuration > 0) {
|
||||
Double netBasalRate = 0d;
|
||||
|
||||
Double dia_ago = time - profile.getDia() * 60 * 60 * 1000;
|
||||
double netBasalRate = 0d;
|
||||
double dia = profile.getDia();
|
||||
double dia_ago = time - dia * 60 * 60 * 1000;
|
||||
int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
|
||||
double tempBolusSpacing = realDuration / aboutFiveMinIntervals;
|
||||
|
||||
for (Long j = 0L; j < aboutFiveMinIntervals; j++) {
|
||||
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);
|
||||
long calcdate = (long) (date + j * tempBolusSpacing * 60 * 1000 + 0.5d * tempBolusSpacing * 60 * 1000);
|
||||
|
||||
Double basalRate = profile.getBasal(calcdate);
|
||||
|
||||
|
@ -202,11 +223,11 @@ public class TemporaryBasal implements Interval {
|
|||
double tempBolusSize = netBasalRate * tempBolusSpacing / 60d;
|
||||
netBasalAmount += tempBolusSize;
|
||||
|
||||
Treatment tempBolusPart = new Treatment(insulinInterface);
|
||||
Treatment tempBolusPart = new Treatment(insulinInterface, dia);
|
||||
tempBolusPart.insulin = tempBolusSize;
|
||||
tempBolusPart.date = calcdate;
|
||||
|
||||
Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, profile.getDia());
|
||||
Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, dia);
|
||||
result.basaliob += aIOB.iobContrib;
|
||||
result.activity += aIOB.activityContrib;
|
||||
result.netbasalinsulin += tempBolusPart.insulin;
|
||||
|
@ -222,7 +243,7 @@ public class TemporaryBasal implements Interval {
|
|||
}
|
||||
|
||||
public int getRealDuration() {
|
||||
return getDurationToTime(new Date().getTime());
|
||||
return getDurationToTime(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private int getDurationToTime(long time) {
|
||||
|
@ -232,13 +253,16 @@ public class TemporaryBasal implements Interval {
|
|||
}
|
||||
|
||||
public int getPlannedRemainingMinutes() {
|
||||
float remainingMin = (end() - new Date().getTime()) / 1000f / 60;
|
||||
float remainingMin = (end() - System.currentTimeMillis()) / 1000f / 60;
|
||||
return (remainingMin < 0) ? 0 : Math.round(remainingMin);
|
||||
}
|
||||
|
||||
public double tempBasalConvertedToAbsolute(long time) {
|
||||
if (isAbsolute) return absoluteRate;
|
||||
else {
|
||||
if(isFakeExtended){
|
||||
return MainApp.getConfigBuilder().getProfile(time).getBasal(time) + netExtendedRate;
|
||||
} else if (isAbsolute) {
|
||||
return absoluteRate;
|
||||
} else {
|
||||
return MainApp.getConfigBuilder().getProfile(time).getBasal(time) * percentRate / 100;
|
||||
}
|
||||
}
|
||||
|
@ -254,35 +278,97 @@ public class TemporaryBasal implements Interval {
|
|||
", absoluteRate=" + absoluteRate +
|
||||
", durationInMinutes=" + durationInMinutes +
|
||||
", isAbsolute=" + isAbsolute +
|
||||
", isFakeExtended=" + isFakeExtended +
|
||||
", netExtendedRate=" + netExtendedRate +
|
||||
'}';
|
||||
}
|
||||
|
||||
public String toStringFull() {
|
||||
if (isAbsolute) {
|
||||
if(isFakeExtended){
|
||||
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
Double currentBasalRate = profile.getBasal();
|
||||
double rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
|
||||
return getCalcuatedPercentageIfNeeded() + DecimalFormatter.to2Decimal(rate) + "U/h ("+DecimalFormatter.to2Decimal(netExtendedRate)+"E) @" +
|
||||
DateUtil.timeString(date) +
|
||||
" " + getRealDuration() + "/" + durationInMinutes + "'";
|
||||
} else if (isAbsolute) {
|
||||
return DecimalFormatter.to2Decimal(absoluteRate) + "U/h @" +
|
||||
DateUtil.timeString(date) +
|
||||
" " + getRealDuration() + "/" + durationInMinutes + "min";
|
||||
" " + getRealDuration() + "/" + durationInMinutes + "'";
|
||||
} else { // percent
|
||||
return percentRate + "% @" +
|
||||
DateUtil.timeString(date) +
|
||||
" " + getRealDuration() + "/" + durationInMinutes + "min";
|
||||
" " + getRealDuration() + "/" + durationInMinutes + "'";
|
||||
}
|
||||
}
|
||||
|
||||
public String toStringShort() {
|
||||
if (isAbsolute) {
|
||||
return DecimalFormatter.to2Decimal(absoluteRate) + "U/h ";
|
||||
if (isAbsolute || isFakeExtended) {
|
||||
|
||||
double rate = 0d;
|
||||
if (isFakeExtended) {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
Double currentBasalRate = profile.getBasal();
|
||||
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
|
||||
} else if (isAbsolute){
|
||||
rate = absoluteRate;
|
||||
}
|
||||
|
||||
if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
if(profile != null) {
|
||||
double basal = profile.getBasal();
|
||||
if(basal != 0){
|
||||
return Math.round(rate*100d/basal) + "% ";
|
||||
}
|
||||
}
|
||||
}
|
||||
return DecimalFormatter.to2Decimal(rate) + "U/h ";
|
||||
} else { // percent
|
||||
return percentRate + "% ";
|
||||
}
|
||||
}
|
||||
|
||||
public String toStringMedium() {
|
||||
if (isAbsolute) {
|
||||
return DecimalFormatter.to2Decimal(absoluteRate) + "U/h ("
|
||||
+ getRealDuration() + "/" + durationInMinutes + ") ";
|
||||
private String getCalcuatedPercentageIfNeeded(){
|
||||
if (isAbsolute || isFakeExtended) {
|
||||
|
||||
double rate = 0d;
|
||||
if (isFakeExtended) {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
Double currentBasalRate = profile.getBasal();
|
||||
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
|
||||
} else if (isAbsolute){
|
||||
rate = absoluteRate;
|
||||
}
|
||||
|
||||
if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
if(profile != null) {
|
||||
double basal = profile.getBasal();
|
||||
if(basal != 0){
|
||||
return Math.round(rate*100d/basal) + "% ";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public String toStringVeryShort() {
|
||||
if (isAbsolute || isFakeExtended) {
|
||||
|
||||
double rate = 0d;
|
||||
if (isFakeExtended) {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
Double currentBasalRate = profile.getBasal();
|
||||
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
|
||||
} else if (isAbsolute){
|
||||
rate = absoluteRate;
|
||||
}
|
||||
return DecimalFormatter.to2Decimal(rate) + "U/h ";
|
||||
} else { // percent
|
||||
return percentRate + "% (" + getRealDuration() + "/" + durationInMinutes + ") ";
|
||||
return percentRate + "% ";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -47,6 +47,8 @@ public class Treatment implements DataPointWithLabelInterface {
|
|||
public double carbs = 0d;
|
||||
@DatabaseField
|
||||
public boolean mealBolus = true; // true for meal bolus , false for correction bolus
|
||||
@DatabaseField
|
||||
public boolean isSMB = false;
|
||||
|
||||
@DatabaseField
|
||||
public int insulinInterfaceID = InsulinInterface.FASTACTINGINSULIN;
|
||||
|
@ -65,8 +67,13 @@ public class Treatment implements DataPointWithLabelInterface {
|
|||
dia = insulin.getDia();
|
||||
}
|
||||
|
||||
public Treatment(InsulinInterface insulin, double dia) {
|
||||
insulinInterfaceID = insulin.getId();
|
||||
this.dia = dia;
|
||||
}
|
||||
|
||||
public long getMillisecondsFromStart() {
|
||||
return new Date().getTime() - date;
|
||||
return System.currentTimeMillis() - date;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
|
@ -74,6 +81,7 @@ public class Treatment implements DataPointWithLabelInterface {
|
|||
"date= " + date +
|
||||
", date= " + DateUtil.dateAndTimeString(date) +
|
||||
", isValid= " + isValid +
|
||||
", isSMB= " + isSMB +
|
||||
", _id= " + _id +
|
||||
", pumpId= " + pumpId +
|
||||
", insulin= " + insulin +
|
||||
|
@ -105,6 +113,8 @@ public class Treatment implements DataPointWithLabelInterface {
|
|||
return false;
|
||||
if (pumpId != other.pumpId)
|
||||
return false;
|
||||
if (isSMB != other.isSMB)
|
||||
return false;
|
||||
if (!Objects.equals(_id, other._id))
|
||||
return false;
|
||||
return true;
|
||||
|
@ -117,6 +127,7 @@ public class Treatment implements DataPointWithLabelInterface {
|
|||
carbs = t.carbs;
|
||||
mealBolus = t.mealBolus;
|
||||
pumpId = t.pumpId;
|
||||
isSMB = t.isSMB;
|
||||
}
|
||||
|
||||
// ----------------- DataPointInterface --------------------
|
||||
|
|
|
@ -4,15 +4,4 @@ package info.nightscout.androidaps.events;
|
|||
* Created by mike on 13.06.2016.
|
||||
*/
|
||||
public class EventRefreshGui {
|
||||
|
||||
public boolean isSwitchToLast() {
|
||||
return switchToLast;
|
||||
}
|
||||
|
||||
private final boolean switchToLast;
|
||||
|
||||
public EventRefreshGui(boolean switchToLast){
|
||||
this.switchToLast = switchToLast;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package info.nightscout.androidaps.events;
|
||||
|
||||
/**
|
||||
* Created by mike on 16.06.2017.
|
||||
*/
|
||||
|
||||
public class EventRefreshOverview {
|
||||
public String from;
|
||||
|
||||
public EventRefreshOverview(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package info.nightscout.androidaps.events;
|
||||
|
||||
/**
|
||||
* Created by mike on 12.06.2017.
|
||||
*/
|
||||
|
||||
public class EventReloadProfileSwitchData {
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package info.nightscout.androidaps.interfaces;
|
||||
|
||||
/**
|
||||
* Created by mike on 12.06.2017.
|
||||
*/
|
||||
|
||||
public interface DanaRInterface {
|
||||
boolean loadHistory(byte type);
|
||||
}
|
|
@ -8,7 +8,7 @@ import java.util.Date;
|
|||
public interface PluginBase {
|
||||
int GENERAL = 1;
|
||||
int TREATMENT = 2;
|
||||
//int TEMPBASAL = 3;
|
||||
int SENSITIVITY = 3;
|
||||
int PROFILE = 4;
|
||||
int APS = 5;
|
||||
int PUMP = 6;
|
||||
|
|
|
@ -10,5 +10,6 @@ import info.nightscout.androidaps.data.ProfileStore;
|
|||
public interface ProfileInterface {
|
||||
@Nullable
|
||||
ProfileStore getProfile();
|
||||
String getUnits();
|
||||
String getProfileName();
|
||||
}
|
||||
|
|
|
@ -34,7 +34,9 @@ public interface PumpInterface {
|
|||
PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes);
|
||||
PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes);
|
||||
PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes);
|
||||
PumpEnactResult cancelTempBasal();
|
||||
//some pumps might set a very short temp close to 100% as canecelling a temp can be noisy
|
||||
//when the cancel request is requested by the user, the pump should always do a real cancel
|
||||
PumpEnactResult cancelTempBasal(boolean userRequested);
|
||||
PumpEnactResult cancelExtendedBolus();
|
||||
|
||||
// Status to be passed to NS
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
package info.nightscout.androidaps.interfaces;
|
||||
|
||||
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
|
||||
|
||||
/**
|
||||
* Created by mike on 24.06.2017.
|
||||
*/
|
||||
|
||||
public interface SensitivityInterface {
|
||||
AutosensResult detectSensitivity(long fromTime, long toTime);
|
||||
}
|
|
@ -10,7 +10,7 @@ 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.Intervals;
|
||||
import info.nightscout.androidaps.data.ProfileIntervals;
|
||||
|
||||
/**
|
||||
|
@ -42,18 +42,18 @@ public interface TreatmentsInterface {
|
|||
TemporaryBasal getTempBasalFromHistory(long time);
|
||||
double getTempBasalAbsoluteRateHistory();
|
||||
double getTempBasalRemainingMinutesFromHistory();
|
||||
OverlappingIntervals<TemporaryBasal> getTemporaryBasalsFromHistory();
|
||||
Intervals<TemporaryBasal> getTemporaryBasalsFromHistory();
|
||||
|
||||
boolean isInHistoryExtendedBoluslInProgress();
|
||||
ExtendedBolus getExtendedBolusFromHistory(long time);
|
||||
OverlappingIntervals<ExtendedBolus> getExtendedBolusesFromHistory();
|
||||
Intervals<ExtendedBolus> getExtendedBolusesFromHistory();
|
||||
|
||||
boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus);
|
||||
|
||||
boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo);
|
||||
|
||||
TempTarget getTempTargetFromHistory(long time);
|
||||
OverlappingIntervals<TempTarget> getTempTargetsFromHistory();
|
||||
Intervals<TempTarget> getTempTargetsFromHistory();
|
||||
|
||||
ProfileSwitch getProfileSwitchFromHistory(long time);
|
||||
ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory();
|
||||
|
|
|
@ -16,28 +16,28 @@ 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.db.TemporaryBasal;
|
||||
import info.nightscout.androidaps.events.EventExtendedBolusChange;
|
||||
import info.nightscout.androidaps.events.EventInitializationChanged;
|
||||
import info.nightscout.androidaps.events.EventRefreshGui;
|
||||
import info.nightscout.androidaps.events.EventRefreshOverview;
|
||||
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.Actions.dialogs.NewExtendedBolusDialog;
|
||||
import info.nightscout.androidaps.plugins.Actions.dialogs.NewTempBasalDialog;
|
||||
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.PumpDanaRv2.DanaRv2Plugin;
|
||||
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
|
||||
|
||||
/**
|
||||
* A simple {@link Fragment} subclass.
|
||||
*/
|
||||
public class ActionsFragment extends Fragment implements View.OnClickListener {
|
||||
public class ActionsFragment extends SubscriberFragment implements View.OnClickListener {
|
||||
|
||||
static ActionsPlugin actionsPlugin = new ActionsPlugin();
|
||||
|
||||
|
@ -50,6 +50,7 @@ public class ActionsFragment extends Fragment implements View.OnClickListener {
|
|||
Button extendedBolus;
|
||||
Button extendedBolusCancel;
|
||||
Button tempBasal;
|
||||
Button tempBasalCancel;
|
||||
Button fill;
|
||||
|
||||
private static Handler sHandler;
|
||||
|
@ -75,6 +76,7 @@ public class ActionsFragment extends Fragment implements View.OnClickListener {
|
|||
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);
|
||||
tempBasalCancel = (Button) view.findViewById(R.id.actions_canceltempbasal);
|
||||
fill = (Button) view.findViewById(R.id.actions_fill);
|
||||
|
||||
profileSwitch.setOnClickListener(this);
|
||||
|
@ -82,77 +84,93 @@ public class ActionsFragment extends Fragment implements View.OnClickListener {
|
|||
extendedBolus.setOnClickListener(this);
|
||||
extendedBolusCancel.setOnClickListener(this);
|
||||
tempBasal.setOnClickListener(this);
|
||||
tempBasalCancel.setOnClickListener(this);
|
||||
fill.setOnClickListener(this);
|
||||
|
||||
updateGUIIfVisible();
|
||||
updateGUI();
|
||||
return view;
|
||||
}
|
||||
|
||||
@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 EventInitializationChanged ev) {
|
||||
updateGUIIfVisible();
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventRefreshGui ev) {
|
||||
updateGUIIfVisible();
|
||||
public void onStatusEvent(final EventRefreshOverview ev) {
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventExtendedBolusChange ev) {
|
||||
updateGUIIfVisible();
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventTempBasalChange ev) {
|
||||
updateGUIIfVisible();
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
void updateGUIIfVisible() {
|
||||
@Override
|
||||
protected void updateGUI() {
|
||||
Activity activity = getActivity();
|
||||
if (activity != null)
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() == null)
|
||||
if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() == null) {
|
||||
tempTarget.setVisibility(View.GONE);
|
||||
profileSwitch.setVisibility(View.GONE);
|
||||
extendedBolus.setVisibility(View.GONE);
|
||||
extendedBolusCancel.setVisibility(View.GONE);
|
||||
tempBasal.setVisibility(View.GONE);
|
||||
tempBasalCancel.setVisibility(View.GONE);
|
||||
fill.setVisibility(View.GONE);
|
||||
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() || MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress() || MainApp.getConfigBuilder().isFakingTempsByExtendedBoluses())
|
||||
|
||||
|
||||
if (!MainApp.getConfigBuilder().getPumpDescription().isExtendedBolusCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || MainApp.getConfigBuilder().isFakingTempsByExtendedBoluses()) {
|
||||
extendedBolus.setVisibility(View.GONE);
|
||||
else {
|
||||
extendedBolus.setVisibility(View.VISIBLE);
|
||||
}
|
||||
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());
|
||||
} else {
|
||||
if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) {
|
||||
extendedBolus.setVisibility(View.GONE);
|
||||
extendedBolusCancel.setVisibility(View.VISIBLE);
|
||||
ExtendedBolus running = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
|
||||
extendedBolusCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + running.toString());
|
||||
} else {
|
||||
extendedBolus.setVisibility(View.VISIBLE);
|
||||
extendedBolusCancel.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
if (!MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || MainApp.getConfigBuilder().isTempBasalInProgress())
|
||||
|
||||
|
||||
if (!MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended()) {
|
||||
tempBasal.setVisibility(View.GONE);
|
||||
else
|
||||
tempBasal.setVisibility(View.VISIBLE);
|
||||
tempBasalCancel.setVisibility(View.GONE);
|
||||
} else {
|
||||
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
|
||||
tempBasal.setVisibility(View.GONE);
|
||||
tempBasalCancel.setVisibility(View.VISIBLE);
|
||||
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
|
||||
tempBasalCancel.setText(MainApp.instance().getString(R.string.cancel) + "\n" + activeTemp.toStringShort());
|
||||
} else {
|
||||
tempBasal.setVisibility(View.VISIBLE);
|
||||
tempBasalCancel.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
if (!MainApp.getConfigBuilder().getPumpDescription().isRefillingCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended())
|
||||
fill.setVisibility(View.GONE);
|
||||
else
|
||||
fill.setVisibility(View.VISIBLE);
|
||||
|
||||
if (!Config.APS)
|
||||
tempTarget.setVisibility(View.GONE);
|
||||
else
|
||||
|
@ -169,16 +187,16 @@ public class ActionsFragment extends Fragment implements View.OnClickListener {
|
|||
switch (view.getId()) {
|
||||
case R.id.actions_profileswitch:
|
||||
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
|
||||
final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, false, false, false, true, false, false);
|
||||
final OptionsToShow profileswitch = CareportalFragment.profileswitch;
|
||||
profileswitch.executeProfileSwitch = true;
|
||||
newDialog.setOptions(profileswitch);
|
||||
newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
|
||||
newDialog.show(manager, "NewNSTreatmentDialog");
|
||||
break;
|
||||
case R.id.actions_temptarget:
|
||||
NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog();
|
||||
final OptionsToShow temptarget = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget, false, false, false, false, true, false, false, false, false, true);
|
||||
final OptionsToShow temptarget = CareportalFragment.temptarget;
|
||||
temptarget.executeTempTarget = true;
|
||||
newTTDialog.setOptions(temptarget);
|
||||
newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
|
||||
newTTDialog.show(manager, "NewNSTreatmentDialog");
|
||||
break;
|
||||
case R.id.actions_extendedbolus:
|
||||
|
@ -196,6 +214,17 @@ public class ActionsFragment extends Fragment implements View.OnClickListener {
|
|||
});
|
||||
}
|
||||
break;
|
||||
case R.id.actions_canceltempbasal:
|
||||
if (MainApp.getConfigBuilder().isInHistoryRealTempBasalInProgress()) {
|
||||
sHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
pump.cancelTempBasal(true);
|
||||
Answers.getInstance().logCustom(new CustomEvent("CancelTemp"));
|
||||
}
|
||||
});
|
||||
}
|
||||
break;
|
||||
case R.id.actions_settempbasal:
|
||||
NewTempBasalDialog newTempDialog = new NewTempBasalDialog();
|
||||
newTempDialog.show(manager, "NewTempDialog");
|
||||
|
|
|
@ -27,6 +27,7 @@ import info.nightscout.androidaps.data.PumpEnactResult;
|
|||
import info.nightscout.androidaps.interfaces.PumpDescription;
|
||||
import info.nightscout.androidaps.interfaces.PumpInterface;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.utils.NumberPicker;
|
||||
import info.nightscout.utils.PlusMinusEditText;
|
||||
import info.nightscout.utils.SafeParse;
|
||||
|
||||
|
@ -35,14 +36,14 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
|
|||
RadioButton percentRadio;
|
||||
RadioButton absoluteRadio;
|
||||
RadioGroup basalTypeRadioGroup;
|
||||
RelativeLayout typeSelectorLayout;
|
||||
LinearLayout typeSelectorLayout;
|
||||
|
||||
LinearLayout percentLayout;
|
||||
LinearLayout absoluteLayout;
|
||||
|
||||
PlusMinusEditText basalPercent;
|
||||
PlusMinusEditText basalAbsolute;
|
||||
PlusMinusEditText duration;
|
||||
NumberPicker basalPercent;
|
||||
NumberPicker basalAbsolute;
|
||||
NumberPicker duration;
|
||||
|
||||
Handler mHandler;
|
||||
public static HandlerThread mHandlerThread;
|
||||
|
@ -65,22 +66,24 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
|
|||
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);
|
||||
typeSelectorLayout = (RelativeLayout) view.findViewById(R.id.overview_newtempbasal_typeselector_layout);
|
||||
typeSelectorLayout = (LinearLayout) view.findViewById(R.id.overview_newtempbasal_typeselector_layout);
|
||||
|
||||
PumpDescription pumpDescription = MainApp.getConfigBuilder().getPumpDescription();
|
||||
|
||||
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);
|
||||
basalPercent = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalpercentinput);
|
||||
double maxTempPercent = pumpDescription.maxTempPercent;
|
||||
double tempPercentStep = pumpDescription.tempPercentStep;
|
||||
basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true);
|
||||
|
||||
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 currentBasal = profile != null ? profile.getBasal() : 0d;
|
||||
basalAbsolute = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalabsoluteinput);
|
||||
basalAbsolute.setParams(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);
|
||||
double tempDurationStep = pumpDescription.tempDurationStep;
|
||||
double tempMaxDuration = pumpDescription.tempMaxDuration;
|
||||
duration = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_duration);
|
||||
duration.setParams(tempDurationStep, tempDurationStep, tempMaxDuration, tempDurationStep, new DecimalFormat("0"), false);
|
||||
|
||||
if ((pumpDescription.tempBasalStyle & PumpDescription.PERCENT) == PumpDescription.PERCENT && (pumpDescription.tempBasalStyle & PumpDescription.ABSOLUTE) == PumpDescription.ABSOLUTE) {
|
||||
// Both allowed
|
||||
|
@ -107,13 +110,6 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
|
|||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
if (getDialog() != null)
|
||||
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
switch (view.getId()) {
|
||||
|
|
|
@ -5,6 +5,7 @@ import android.app.Activity;
|
|||
import android.os.Bundle;
|
||||
import android.support.v4.app.Fragment;
|
||||
import android.support.v4.app.FragmentManager;
|
||||
import android.text.Layout;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
@ -12,13 +13,16 @@ import android.widget.TextView;
|
|||
|
||||
import com.squareup.otto.Subscribe;
|
||||
|
||||
import info.nightscout.androidaps.BuildConfig;
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.db.CareportalEvent;
|
||||
import info.nightscout.androidaps.events.EventCareportalEventChange;
|
||||
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
|
||||
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
|
||||
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
|
||||
|
||||
public class CareportalFragment extends Fragment implements View.OnClickListener {
|
||||
public class CareportalFragment extends SubscriberFragment implements View.OnClickListener {
|
||||
|
||||
static CareportalPlugin careportalPlugin;
|
||||
|
||||
|
@ -27,6 +31,8 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
|
|||
TextView sage;
|
||||
TextView pbage;
|
||||
|
||||
View statsLayout;
|
||||
|
||||
static public CareportalPlugin getPlugin() {
|
||||
if (careportalPlugin == null) {
|
||||
careportalPlugin = new CareportalPlugin();
|
||||
|
@ -35,26 +41,26 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
|
|||
}
|
||||
|
||||
// bg,insulin,carbs,prebolus,duration,percent,absolute,profile,split,temptarget
|
||||
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);
|
||||
public static final OptionsToShow bgcheck = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck, true, true, true, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow snackbolus = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus, true, true, true, true, false, false, false, false, false, false);
|
||||
public static final OptionsToShow mealbolus = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus, true, true, true, true, false, false, false, false, false, false);
|
||||
public static final OptionsToShow correctionbolus = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus, true, true, true, true, false, false, false, false, false, false);
|
||||
public static final OptionsToShow carbcorrection = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection, true, false, true, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow combobolus = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus, true, true, true, true, true, false, false, false, true, false);
|
||||
public static final OptionsToShow announcement = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow note = new OptionsToShow(R.id.careportal_note, R.string.careportal_note, true, false, false, false, true, false, false, false, false, false);
|
||||
public static final OptionsToShow question = new OptionsToShow(R.id.careportal_question, R.string.careportal_question, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow exercise = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise, false, false, false, false, true, false, false, false, false, false);
|
||||
public static final OptionsToShow sitechange = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange, true, true, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow sensorstart = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow sensorchange = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow insulinchange = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow pumpbatterychange = new OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow tempbasalstart = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart, true, false, false, false, true, true, true, false, false, false);
|
||||
public static final OptionsToShow tempbasalend = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend, true, false, false, false, false, false, false, false, false, false);
|
||||
public static final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, true, false, false, true, false, false);
|
||||
public static final OptionsToShow openapsoffline = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline, false, false, false, false, true, false, false, false, false, false);
|
||||
public 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,
|
||||
|
@ -87,6 +93,11 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
|
|||
sage = (TextView) view.findViewById(R.id.careportal_sensorage);
|
||||
pbage = (TextView) view.findViewById(R.id.careportal_pbage);
|
||||
|
||||
statsLayout = (View) view.findViewById(R.id.careportal_stats);
|
||||
|
||||
if (BuildConfig.NSCLIENTOLNY)
|
||||
statsLayout.setVisibility(View.GONE); // visible on overview
|
||||
|
||||
updateGUI();
|
||||
return view;
|
||||
}
|
||||
|
@ -100,64 +111,66 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
|
|||
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
|
||||
switch (id) {
|
||||
case R.id.careportal_bgcheck:
|
||||
newDialog.setOptions(bgcheck);
|
||||
newDialog.setOptions(bgcheck, R.string.careportal_bgcheck);
|
||||
break;
|
||||
case R.id.careportal_announcement:
|
||||
newDialog.setOptions(announcement);
|
||||
newDialog.setOptions(announcement, R.string.careportal_announcement);
|
||||
break;
|
||||
case R.id.careportal_cgmsensorinsert:
|
||||
newDialog.setOptions(sensorchange);
|
||||
newDialog.setOptions(sensorchange, R.string.careportal_cgmsensorinsert);
|
||||
break;
|
||||
case R.id.careportal_cgmsensorstart:
|
||||
newDialog.setOptions(sensorstart);
|
||||
newDialog.setOptions(sensorstart, R.string.careportal_cgmsensorstart);
|
||||
break;
|
||||
case R.id.careportal_combobolus:
|
||||
newDialog.setOptions(combobolus);
|
||||
newDialog.setOptions(combobolus, R.string.careportal_combobolus);
|
||||
break;
|
||||
case R.id.careportal_correctionbolus:
|
||||
newDialog.setOptions(correctionbolus);
|
||||
newDialog.setOptions(correctionbolus, R.string.careportal_correctionbolus);
|
||||
break;
|
||||
case R.id.careportal_carbscorrection:
|
||||
newDialog.setOptions(carbcorrection);
|
||||
newDialog.setOptions(carbcorrection, R.string.careportal_carbscorrection);
|
||||
break;
|
||||
case R.id.careportal_exercise:
|
||||
newDialog.setOptions(exercise);
|
||||
newDialog.setOptions(exercise, R.string.careportal_exercise);
|
||||
break;
|
||||
case R.id.careportal_insulincartridgechange:
|
||||
newDialog.setOptions(insulinchange);
|
||||
newDialog.setOptions(insulinchange, R.string.careportal_insulincartridgechange);
|
||||
break;
|
||||
case R.id.careportal_pumpbatterychange:
|
||||
newDialog.setOptions(pumpbatterychange);
|
||||
newDialog.setOptions(pumpbatterychange, R.string.careportal_pumpbatterychange);
|
||||
break;
|
||||
case R.id.careportal_mealbolus:
|
||||
newDialog.setOptions(mealbolus);
|
||||
newDialog.setOptions(mealbolus, R.string.careportal_mealbolus);
|
||||
break;
|
||||
case R.id.careportal_note:
|
||||
newDialog.setOptions(note);
|
||||
newDialog.setOptions(note, R.string.careportal_note);
|
||||
break;
|
||||
case R.id.careportal_profileswitch:
|
||||
newDialog.setOptions(profileswitch);
|
||||
profileswitch.executeProfileSwitch = false;
|
||||
newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
|
||||
break;
|
||||
case R.id.careportal_pumpsitechange:
|
||||
newDialog.setOptions(sitechange);
|
||||
newDialog.setOptions(sitechange, R.string.careportal_pumpsitechange);
|
||||
break;
|
||||
case R.id.careportal_question:
|
||||
newDialog.setOptions(question);
|
||||
newDialog.setOptions(question, R.string.careportal_question);
|
||||
break;
|
||||
case R.id.careportal_snackbolus:
|
||||
newDialog.setOptions(snackbolus);
|
||||
newDialog.setOptions(snackbolus, R.string.careportal_snackbolus);
|
||||
break;
|
||||
case R.id.careportal_tempbasalstart:
|
||||
newDialog.setOptions(tempbasalstart);
|
||||
newDialog.setOptions(tempbasalstart, R.string.careportal_tempbasalstart);
|
||||
break;
|
||||
case R.id.careportal_tempbasalend:
|
||||
newDialog.setOptions(tempbasalend);
|
||||
newDialog.setOptions(tempbasalend, R.string.careportal_tempbasalend);
|
||||
break;
|
||||
case R.id.careportal_openapsoffline:
|
||||
newDialog.setOptions(openapsoffline);
|
||||
newDialog.setOptions(openapsoffline, R.string.careportal_openapsoffline);
|
||||
break;
|
||||
case R.id.careportal_temporarytarget:
|
||||
newDialog.setOptions(temptarget);
|
||||
temptarget.executeTempTarget = false;
|
||||
newDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
|
||||
break;
|
||||
default:
|
||||
newDialog = null;
|
||||
|
@ -166,24 +179,13 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
|
|||
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() {
|
||||
@Override
|
||||
protected void updateGUI() {
|
||||
Activity activity = getActivity();
|
||||
updateAge(activity, sage, iage, cage, pbage);
|
||||
}
|
||||
|
@ -195,21 +197,22 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
|
|||
@Override
|
||||
public void run() {
|
||||
CareportalEvent careportalEvent;
|
||||
String notavailable = OverviewFragment.shorttextmode ? "-" : MainApp.sResources.getString(R.string.notavailable);
|
||||
if (sage != null) {
|
||||
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
|
||||
sage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
|
||||
sage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
|
||||
}
|
||||
if (iage != null) {
|
||||
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
|
||||
iage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
|
||||
iage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
|
||||
}
|
||||
if (cage != null) {
|
||||
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SITECHANGE);
|
||||
cage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
|
||||
cage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
|
||||
}
|
||||
if (pbage != null) {
|
||||
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.PUMPBATTERYCHANGE);
|
||||
pbage.setText(careportalEvent != null ? careportalEvent.age() : MainApp.sResources.getString(R.string.notavailable));
|
||||
pbage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -15,12 +15,10 @@ import android.view.LayoutInflater;
|
|||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
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;
|
||||
|
||||
|
@ -44,6 +42,8 @@ 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.Profile;
|
||||
import info.nightscout.androidaps.data.ProfileStore;
|
||||
import info.nightscout.androidaps.db.CareportalEvent;
|
||||
import info.nightscout.androidaps.db.ProfileSwitch;
|
||||
import info.nightscout.androidaps.db.Source;
|
||||
|
@ -52,12 +52,10 @@ import info.nightscout.androidaps.events.EventNewBasalProfile;
|
|||
import info.nightscout.androidaps.interfaces.PumpInterface;
|
||||
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
|
||||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
|
||||
import info.nightscout.androidaps.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.NumberPicker;
|
||||
import info.nightscout.utils.SP;
|
||||
import info.nightscout.utils.SafeParse;
|
||||
import info.nightscout.utils.Translator;
|
||||
|
@ -68,53 +66,44 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
private Activity context;
|
||||
|
||||
private static OptionsToShow options;
|
||||
private static String event;
|
||||
|
||||
Profile profile;
|
||||
ProfileStore profileStore;
|
||||
String units;
|
||||
|
||||
RelativeLayout layoutBg;
|
||||
TextView eventTypeText;
|
||||
LinearLayout layoutBg;
|
||||
LinearLayout layoutBgSource;
|
||||
RelativeLayout layoutInsulin;
|
||||
RelativeLayout layoutCarbs;
|
||||
RelativeLayout layoutSplit;
|
||||
RelativeLayout layoutDuration;
|
||||
RelativeLayout layoutPercent;
|
||||
RelativeLayout layoutAbsolute;
|
||||
RelativeLayout layoutCarbTime;
|
||||
RelativeLayout layoutProfile;
|
||||
LinearLayout layoutInsulin;
|
||||
LinearLayout layoutCarbs;
|
||||
LinearLayout layoutSplit;
|
||||
LinearLayout layoutDuration;
|
||||
LinearLayout layoutPercent;
|
||||
LinearLayout layoutAbsolute;
|
||||
LinearLayout layoutCarbTime;
|
||||
LinearLayout layoutProfile;
|
||||
LinearLayout layoutTempTarget;
|
||||
Button dateButton;
|
||||
Button timeButton;
|
||||
Button okButton;
|
||||
Button cancelButton;
|
||||
TextView dateButton;
|
||||
TextView timeButton;
|
||||
|
||||
TextView bgUnitsView;
|
||||
RadioButton meterRadioButton;
|
||||
RadioButton sensorRadioButton;
|
||||
RadioButton otherRadioButton;
|
||||
EditText notesEdit;
|
||||
EditText bgInputEdit;
|
||||
EditText insulinEdit;
|
||||
EditText carbsEdit;
|
||||
EditText percentEdit;
|
||||
EditText absoluteEdit;
|
||||
EditText durationeEdit;
|
||||
EditText carbTimeEdit;
|
||||
EditText splitEdit;
|
||||
Spinner profileSpinner;
|
||||
EditText low;
|
||||
EditText high;
|
||||
Spinner reasonSpinner;
|
||||
|
||||
PlusMinusEditText editBg;
|
||||
PlusMinusEditText editCarbs;
|
||||
PlusMinusEditText editInsulin;
|
||||
PlusMinusEditText editSplit;
|
||||
PlusMinusEditText editDuration;
|
||||
PlusMinusEditText editPercent;
|
||||
PlusMinusEditText editAbsolute;
|
||||
PlusMinusEditText editCarbTime;
|
||||
NumberPicker editBg;
|
||||
NumberPicker editCarbs;
|
||||
NumberPicker editInsulin;
|
||||
NumberPicker editSplit;
|
||||
NumberPicker editDuration;
|
||||
NumberPicker editPercent;
|
||||
NumberPicker editAbsolute;
|
||||
NumberPicker editCarbTime;
|
||||
NumberPicker editTemptarget;
|
||||
|
||||
Date eventTime;
|
||||
|
||||
|
@ -122,8 +111,9 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
private static HandlerThread sHandlerThread;
|
||||
|
||||
|
||||
public void setOptions(OptionsToShow options) {
|
||||
public void setOptions(OptionsToShow options, int event) {
|
||||
this.options = options;
|
||||
this.event = MainApp.sResources.getString(event);
|
||||
}
|
||||
|
||||
public NewNSTreatmentDialog() {
|
||||
|
@ -141,6 +131,12 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
super.onAttach(activity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetach() {
|
||||
super.onDetach();
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
|
@ -148,91 +144,46 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
setStyle(DialogFragment.STYLE_NORMAL, getTheme());
|
||||
View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false);
|
||||
|
||||
layoutBg = (RelativeLayout) view.findViewById(R.id.careportal_newnstreatment_bg_layout);
|
||||
layoutBg = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_bg_layout);
|
||||
layoutBgSource = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_bgsource_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);
|
||||
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);
|
||||
layoutTempTarget = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_temptarget_layout);
|
||||
|
||||
eventTypeText = (TextView) view.findViewById(R.id.careportal_newnstreatment_eventtype);
|
||||
eventTypeText.setText(event);
|
||||
bgUnitsView = (TextView) view.findViewById(R.id.careportal_newnstreatment_bgunits);
|
||||
meterRadioButton = (RadioButton) view.findViewById(R.id.careportal_newnstreatment_meter);
|
||||
sensorRadioButton = (RadioButton) view.findViewById(R.id.careportal_newnstreatment_sensor);
|
||||
otherRadioButton = (RadioButton) view.findViewById(R.id.careportal_newnstreatment_other);
|
||||
profileSpinner = (Spinner) view.findViewById(R.id.careportal_newnstreatment_profile);
|
||||
|
||||
bgInputEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_bginput);
|
||||
insulinEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_insulininput);
|
||||
carbsEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_carbsinput);
|
||||
percentEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_percentinput);
|
||||
percentEdit.addTextChangedListener(new TextWatcher() {
|
||||
@Override
|
||||
public void afterTextChanged(Editable s) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTextChanged(CharSequence s, int start,
|
||||
int count, int after) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTextChanged(CharSequence s, int start,
|
||||
int before, int count) {
|
||||
layoutPercent.setVisibility(View.VISIBLE);
|
||||
layoutAbsolute.setVisibility(View.GONE);
|
||||
}
|
||||
});
|
||||
absoluteEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_absoluteinput);
|
||||
absoluteEdit.addTextChangedListener(new TextWatcher() {
|
||||
@Override
|
||||
public void afterTextChanged(Editable s) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTextChanged(CharSequence s, int start,
|
||||
int count, int after) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTextChanged(CharSequence s, int start,
|
||||
int before, int count) {
|
||||
layoutPercent.setVisibility(View.GONE);
|
||||
layoutAbsolute.setVisibility(View.VISIBLE);
|
||||
}
|
||||
});
|
||||
durationeEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_durationinput);
|
||||
carbTimeEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_carbtimeinput);
|
||||
notesEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_notes);
|
||||
splitEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_splitinput);
|
||||
|
||||
reasonSpinner = (Spinner) view.findViewById(R.id.careportal_newnstreatment_temptarget_reason);
|
||||
low = (EditText) view.findViewById(R.id.careportal_temptarget_low);
|
||||
high = (EditText) view.findViewById(R.id.careportal_temptarget_high);
|
||||
|
||||
eventTime = new Date();
|
||||
dateButton = (Button) view.findViewById(R.id.careportal_newnstreatment_eventdate);
|
||||
timeButton = (Button) view.findViewById(R.id.careportal_newnstreatment_eventtime);
|
||||
dateButton = (TextView) view.findViewById(R.id.careportal_newnstreatment_eventdate);
|
||||
timeButton = (TextView) view.findViewById(R.id.careportal_newnstreatment_eventtime);
|
||||
dateButton.setText(DateUtil.dateString(eventTime));
|
||||
timeButton.setText(DateUtil.timeString(eventTime));
|
||||
dateButton.setOnClickListener(this);
|
||||
timeButton.setOnClickListener(this);
|
||||
|
||||
okButton = (Button) view.findViewById(R.id.ok);
|
||||
okButton.setOnClickListener(this);
|
||||
cancelButton = (Button) view.findViewById(R.id.cancel);
|
||||
cancelButton.setOnClickListener(this);
|
||||
view.findViewById(R.id.ok).setOnClickListener(this);
|
||||
view.findViewById(R.id.cancel).setOnClickListener(this);
|
||||
|
||||
// profile
|
||||
profile = MainApp.getConfigBuilder().getProfile();
|
||||
profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
|
||||
profileStore = ConfigBuilderPlugin.getActiveProfileInterface().getProfile();
|
||||
ArrayList<CharSequence> profileList;
|
||||
units = Constants.MGDL;
|
||||
units = profile.getUnits();
|
||||
units = profile != null ? profile.getUnits() : Constants.MGDL;
|
||||
profileList = profileStore.getProfileList();
|
||||
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
|
||||
R.layout.spinner_centered, profileList);
|
||||
|
@ -255,25 +206,20 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
// bg
|
||||
bgUnitsView.setText(units);
|
||||
|
||||
// Set BG if not old
|
||||
// BgReading lastBg = MainApp.getDbHelper().lastBg();
|
||||
// Double lastBgValue = 0d;
|
||||
// if (lastBg != null) {
|
||||
// lastBgValue = lastBg.valueToUnits(units);
|
||||
// sensorRadioButton.setChecked(true);
|
||||
// } else {
|
||||
// meterRadioButton.setChecked(true);
|
||||
// }
|
||||
|
||||
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))
|
||||
editBg = new PlusMinusEditText(view, R.id.careportal_newnstreatment_bginput, R.id.careportal_newnstreatment_bg_plus, R.id.careportal_newnstreatment_bg_minus, bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
else
|
||||
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() {
|
||||
|
||||
editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput);
|
||||
editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget);
|
||||
if (profile == null) {
|
||||
editBg.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
editTemptarget.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
} else if (profile.getUnits().equals(Constants.MMOL)) {
|
||||
editBg.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
editTemptarget.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
} else {
|
||||
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
|
||||
editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
|
||||
}
|
||||
editBg.addTextChangedListener(new TextWatcher() {
|
||||
public void afterTextChanged(Editable s) {
|
||||
}
|
||||
|
||||
|
@ -284,6 +230,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true);
|
||||
}
|
||||
});
|
||||
|
||||
sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
|
||||
@Override
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
|
||||
|
@ -293,21 +240,63 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
});
|
||||
|
||||
Integer maxCarbs = MainApp.getConfigBuilder().applyCarbsConstraints(Constants.carbsOnlyForCheckLimit);
|
||||
editCarbs = new PlusMinusEditText(view, R.id.careportal_newnstreatment_carbsinput, R.id.careportal_newnstreatment_carbs_plus, R.id.careportal_newnstreatment_carbs_minus, 0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false);
|
||||
editCarbs = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_carbsinput);
|
||||
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false);
|
||||
|
||||
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
|
||||
editInsulin = new PlusMinusEditText(view, R.id.careportal_newnstreatment_insulininput, R.id.careportal_newnstreatment_insulin_plus, R.id.careportal_newnstreatment_insulin_minus, 0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false);
|
||||
editInsulin = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_insulininput);
|
||||
editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false);
|
||||
|
||||
editSplit = new PlusMinusEditText(view, R.id.careportal_newnstreatment_splitinput, R.id.careportal_newnstreatment_split_plus, R.id.careportal_newnstreatment_split_minus, 100d, 0d, 100d, 5d, new DecimalFormat("0"), true);
|
||||
editDuration = new PlusMinusEditText(view, R.id.careportal_newnstreatment_durationinput, R.id.careportal_newnstreatment_duration_plus, R.id.careportal_newnstreatment_duration_minus, 0d, 0d, 24 * 60d, 10d, new DecimalFormat("0"), false);
|
||||
editSplit = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_splitinput);
|
||||
editSplit.setParams(100d, 0d, 100d, 5d, new DecimalFormat("0"), true);
|
||||
editDuration = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_durationinput);
|
||||
editDuration.setParams(0d, 0d, 24 * 60d, 10d, new DecimalFormat("0"), false);
|
||||
|
||||
Integer maxPercent = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalPercentOnlyForCheckLimit);
|
||||
editPercent = new PlusMinusEditText(view, R.id.careportal_newnstreatment_percentinput, R.id.careportal_newnstreatment_percent_plus, R.id.careportal_newnstreatment_percent_minus, 0d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true);
|
||||
editPercent = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentinput);
|
||||
editPercent.setParams(0d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true);
|
||||
editPercent.addTextChangedListener(new TextWatcher() {
|
||||
@Override
|
||||
public void afterTextChanged(Editable s) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTextChanged(CharSequence s, int start,
|
||||
int count, int after) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTextChanged(CharSequence s, int start,
|
||||
int before, int count) {
|
||||
layoutPercent.setVisibility(View.VISIBLE);
|
||||
layoutAbsolute.setVisibility(View.GONE);
|
||||
}
|
||||
});
|
||||
|
||||
Double maxAbsolute = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalAbsoluteOnlyForCheckLimit);
|
||||
editAbsolute = new PlusMinusEditText(view, R.id.careportal_newnstreatment_absoluteinput, R.id.careportal_newnstreatment_absolute_plus, R.id.careportal_newnstreatment_absolute_minus, 0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true);
|
||||
editAbsolute = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_absoluteinput);
|
||||
editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true);
|
||||
editAbsolute.addTextChangedListener(new TextWatcher() {
|
||||
@Override
|
||||
public void afterTextChanged(Editable s) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTextChanged(CharSequence s, int start,
|
||||
int count, int after) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTextChanged(CharSequence s, int start,
|
||||
int before, int count) {
|
||||
layoutPercent.setVisibility(View.GONE);
|
||||
layoutAbsolute.setVisibility(View.VISIBLE);
|
||||
}
|
||||
});
|
||||
|
||||
editCarbTime = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_carbtimeinput);
|
||||
editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false);
|
||||
|
||||
editCarbTime = new PlusMinusEditText(view, R.id.careportal_newnstreatment_carbtimeinput, R.id.careportal_newnstreatment_carbtime_plus, R.id.careportal_newnstreatment_carbtime_minus, 0d, -60d, 60d, 5d, new DecimalFormat("0"), false);
|
||||
|
||||
showOrHide(layoutBg, options.bg);
|
||||
showOrHide(layoutBgSource, options.bg);
|
||||
|
@ -324,13 +313,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
if (getDialog() != null)
|
||||
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
|
@ -348,7 +330,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
dpd.show(context.getFragmentManager(), "Datepickerdialog");
|
||||
break;
|
||||
case R.id.careportal_newnstreatment_eventtime:
|
||||
android.text.format.DateFormat df = new android.text.format.DateFormat();
|
||||
TimePickerDialog tpd = TimePickerDialog.newInstance(
|
||||
this,
|
||||
calendar.get(Calendar.HOUR_OF_DAY),
|
||||
|
@ -412,8 +393,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
data.put("eventType", "Sensor Start");
|
||||
break;
|
||||
case R.id.careportal_combobolus:
|
||||
data.put("splitNow", SafeParse.stringToDouble(splitEdit.getText().toString()));
|
||||
data.put("splitExt", 100 - SafeParse.stringToDouble(splitEdit.getText().toString()));
|
||||
data.put("splitNow", SafeParse.stringToDouble(editSplit.getText()));
|
||||
data.put("splitExt", 100 - SafeParse.stringToDouble(editSplit.getText()));
|
||||
data.put("eventType", CareportalEvent.COMBOBOLUS);
|
||||
break;
|
||||
case R.id.careportal_correctionbolus:
|
||||
|
@ -463,42 +444,42 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
data.put("eventType", CareportalEvent.TEMPORARYTARGET);
|
||||
if (!reasonSpinner.getSelectedItem().toString().equals(""))
|
||||
data.put("reason", reasonSpinner.getSelectedItem().toString());
|
||||
if (SafeParse.stringToDouble(low.getText().toString()) != 0d)
|
||||
data.put("targetBottom", SafeParse.stringToDouble(low.getText().toString()));
|
||||
if (SafeParse.stringToDouble(high.getText().toString()) != 0d)
|
||||
data.put("targetTop", SafeParse.stringToDouble(high.getText().toString()));
|
||||
if (SafeParse.stringToDouble(editTemptarget.getText()) != 0d) {
|
||||
data.put("targetBottom", SafeParse.stringToDouble(editTemptarget.getText()));
|
||||
data.put("targetTop", SafeParse.stringToDouble(editTemptarget.getText()));
|
||||
}
|
||||
allowZeroDuration = true;
|
||||
break;
|
||||
}
|
||||
if (SafeParse.stringToDouble(bgInputEdit.getText().toString()) != 0d) {
|
||||
data.put("glucose", SafeParse.stringToDouble(bgInputEdit.getText().toString()));
|
||||
if (SafeParse.stringToDouble(editBg.getText()) != 0d) {
|
||||
data.put("glucose", SafeParse.stringToDouble(editBg.getText()));
|
||||
if (meterRadioButton.isChecked()) data.put("glucoseType", "Finger");
|
||||
if (sensorRadioButton.isChecked()) data.put("glucoseType", "Sensor");
|
||||
if (otherRadioButton.isChecked()) data.put("glucoseType", "Manual");
|
||||
}
|
||||
if (SafeParse.stringToDouble(carbsEdit.getText().toString()) != 0d)
|
||||
data.put("carbs", SafeParse.stringToDouble(carbsEdit.getText().toString()));
|
||||
if (SafeParse.stringToDouble(insulinEdit.getText().toString()) != 0d)
|
||||
data.put("insulin", SafeParse.stringToDouble(insulinEdit.getText().toString()));
|
||||
if (allowZeroDuration || SafeParse.stringToDouble(durationeEdit.getText().toString()) != 0d)
|
||||
data.put("duration", SafeParse.stringToDouble(durationeEdit.getText().toString()));
|
||||
if (SafeParse.stringToDouble(editCarbs.getText()) != 0d)
|
||||
data.put("carbs", SafeParse.stringToDouble(editCarbs.getText()));
|
||||
if (SafeParse.stringToDouble(editInsulin.getText()) != 0d)
|
||||
data.put("insulin", SafeParse.stringToDouble(editInsulin.getText()));
|
||||
if (allowZeroDuration || SafeParse.stringToDouble(editDuration.getText()) != 0d)
|
||||
data.put("duration", SafeParse.stringToDouble(editDuration.getText()));
|
||||
if (layoutPercent.getVisibility() != View.GONE)
|
||||
data.put("percent", SafeParse.stringToDouble(percentEdit.getText().toString()));
|
||||
data.put("percent", SafeParse.stringToDouble(editPercent.getText()));
|
||||
if (layoutAbsolute.getVisibility() != View.GONE)
|
||||
data.put("absolute", SafeParse.stringToDouble(absoluteEdit.getText().toString()));
|
||||
data.put("absolute", SafeParse.stringToDouble(editAbsolute.getText()));
|
||||
if (options.profile && profileSpinner.getSelectedItem() != null)
|
||||
data.put("profile", profileSpinner.getSelectedItem().toString());
|
||||
if (SafeParse.stringToDouble(carbTimeEdit.getText().toString()) != 0d)
|
||||
data.put("preBolus", SafeParse.stringToDouble(carbTimeEdit.getText().toString()));
|
||||
if (SafeParse.stringToDouble(editCarbTime.getText()) != 0d)
|
||||
data.put("preBolus", SafeParse.stringToDouble(editCarbTime.getText()));
|
||||
if (!notesEdit.getText().toString().equals(""))
|
||||
data.put("notes", notesEdit.getText().toString());
|
||||
data.put("units", units);
|
||||
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
|
||||
if (options.eventType == R.id.careportal_combobolus) {
|
||||
Double enteredInsulin = SafeParse.stringToDouble(insulinEdit.getText().toString());
|
||||
Double enteredInsulin = SafeParse.stringToDouble(editInsulin.getText());
|
||||
data.put("enteredinsulin", enteredInsulin);
|
||||
data.put("insulin", enteredInsulin * SafeParse.stringToDouble(splitEdit.getText().toString()) / 100);
|
||||
data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(splitEdit.getText().toString())) / 100 / SafeParse.stringToDouble(durationeEdit.getText().toString()) * 60);
|
||||
data.put("insulin", enteredInsulin * SafeParse.stringToDouble(editInsulin.getText()) / 100);
|
||||
data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(editSplit.getText())) / 100 / SafeParse.stringToDouble(editDuration.getText()) * 60);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
|
@ -612,40 +593,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
public void onClick(DialogInterface dialog, int id) {
|
||||
if (options.executeProfileSwitch) {
|
||||
if (data.has("profile")) {
|
||||
sHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
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(profileStore.getSpecificProfile(profileName));
|
||||
log.debug("Setting new profile: " + profile);
|
||||
MainApp.bus().post(new EventNewBasalProfile());
|
||||
} else {
|
||||
log.error("No active pump selected");
|
||||
}
|
||||
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
try {
|
||||
doProfileSwitch(profileStore, data.getString("profile"), data.getInt("duration"));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} else if (options.executeTempTarget) {
|
||||
try {
|
||||
|
@ -689,4 +641,35 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
|
|||
builder.show();
|
||||
}
|
||||
|
||||
public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration) {
|
||||
sHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ProfileSwitch profileSwitch = new ProfileSwitch();
|
||||
profileSwitch.date = System.currentTimeMillis();
|
||||
profileSwitch.source = Source.USER;
|
||||
profileSwitch.profileName = profileName;
|
||||
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
|
||||
profileSwitch.profilePlugin = ConfigBuilderPlugin.getActiveProfileInterface().getClass().getName();
|
||||
profileSwitch.durationInMinutes = duration;
|
||||
if (ConfigBuilderPlugin.getActiveProfileInterface() instanceof CircadianPercentageProfilePlugin) {
|
||||
CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) ConfigBuilderPlugin.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(profileStore.getSpecificProfile(profileName));
|
||||
MainApp.bus().post(new EventNewBasalProfile());
|
||||
} else {
|
||||
log.error("No active pump selected");
|
||||
}
|
||||
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
package info.nightscout.androidaps.plugins.Common;
|
||||
|
||||
import android.support.v4.app.Fragment;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
|
||||
abstract public class SubscriberFragment extends Fragment {
|
||||
@Override
|
||||
public void onPause() {
|
||||
super.onPause();
|
||||
MainApp.bus().unregister(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
MainApp.bus().register(this);
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
protected abstract void updateGUI();
|
||||
}
|
|
@ -34,9 +34,11 @@ 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.interfaces.SensitivityInterface;
|
||||
import info.nightscout.androidaps.plugins.InsulinFastacting.InsulinFastactingPlugin;
|
||||
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
|
||||
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
|
||||
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
|
||||
import info.nightscout.utils.PasswordProtection;
|
||||
|
||||
|
||||
|
@ -49,6 +51,7 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
}
|
||||
|
||||
ListView insulinListView;
|
||||
ListView sensitivityListView;
|
||||
ListView bgsourceListView;
|
||||
TextView bgsourceLabel;
|
||||
ListView pumpListView;
|
||||
|
@ -64,13 +67,12 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
ListView constraintsListView;
|
||||
TextView constraintsLabel;
|
||||
ListView generalListView;
|
||||
TextView nsclientVerView;
|
||||
TextView nightscoutVerView;
|
||||
|
||||
LinearLayout mainLayout;
|
||||
Button unlock;
|
||||
|
||||
PluginCustomAdapter insulinDataAdapter = null;
|
||||
PluginCustomAdapter sensivityDataAdapter = null;
|
||||
PluginCustomAdapter bgsourceDataAdapter = null;
|
||||
PluginCustomAdapter pumpDataAdapter = null;
|
||||
PluginCustomAdapter loopDataAdapter = null;
|
||||
|
@ -96,6 +98,7 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
smallWidth = screen_width < Constants.SMALL_WIDTH;
|
||||
|
||||
insulinListView = (ListView) view.findViewById(R.id.configbuilder_insulinlistview);
|
||||
sensitivityListView = (ListView) view.findViewById(R.id.configbuilder_sensitivitylistview);
|
||||
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
|
||||
bgsourceLabel = (TextView) view.findViewById(R.id.configbuilder_bgsourcelabel);
|
||||
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
|
||||
|
@ -111,17 +114,10 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
|
||||
constraintsLabel = (TextView) view.findViewById(R.id.configbuilder_constraintslabel);
|
||||
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
|
||||
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);
|
||||
if (ConfigBuilderPlugin.nightscoutVersionCode < 900)
|
||||
nightscoutVerView.setTextColor(Color.RED);
|
||||
setViews();
|
||||
|
||||
if (PasswordProtection.isLocked("settings_password")) {
|
||||
|
@ -168,7 +164,7 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT).size() == 0)
|
||||
treatmentsLabel.setVisibility(View.GONE);
|
||||
setListViewHeightBasedOnChildren(treatmentsListView);
|
||||
profileDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.BGSOURCE), PluginBase.PROFILE);
|
||||
profileDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.PROFILE), PluginBase.PROFILE);
|
||||
profileListView.setAdapter(profileDataAdapter);
|
||||
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PROFILE).size() == 0)
|
||||
profileLabel.setVisibility(View.GONE);
|
||||
|
@ -178,7 +174,10 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
setListViewHeightBasedOnChildren(apsListView);
|
||||
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.APS).size() == 0)
|
||||
apsLabel.setVisibility(View.GONE);
|
||||
constraintsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginBase.BGSOURCE), PluginBase.CONSTRAINTS);
|
||||
sensivityDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface.class, PluginBase.SENSITIVITY), PluginBase.SENSITIVITY);
|
||||
sensitivityListView.setAdapter(sensivityDataAdapter);
|
||||
setListViewHeightBasedOnChildren(sensitivityListView);
|
||||
constraintsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginBase.CONSTRAINTS), PluginBase.CONSTRAINTS);
|
||||
constraintsListView.setAdapter(constraintsDataAdapter);
|
||||
setListViewHeightBasedOnChildren(constraintsListView);
|
||||
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.CONSTRAINTS).size() == 0)
|
||||
|
@ -234,7 +233,7 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
plugin.setFragmentVisible(type, cb.isChecked());
|
||||
onEnabledCategoryChanged(plugin, type);
|
||||
configBuilderPlugin.storeSettings();
|
||||
MainApp.bus().post(new EventRefreshGui(true));
|
||||
MainApp.bus().post(new EventRefreshGui());
|
||||
MainApp.bus().post(new EventConfigBuilderChange());
|
||||
getPlugin().logPluginStatus();
|
||||
Answers.getInstance().logCustom(new CustomEvent("ConfigurationChange"));
|
||||
|
@ -247,7 +246,7 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
PluginBase plugin = (PluginBase) cb.getTag();
|
||||
plugin.setFragmentVisible(type, cb.isChecked());
|
||||
configBuilderPlugin.storeSettings();
|
||||
MainApp.bus().post(new EventRefreshGui(true));
|
||||
MainApp.bus().post(new EventRefreshGui());
|
||||
getPlugin().logPluginStatus();
|
||||
}
|
||||
});
|
||||
|
@ -277,7 +276,7 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
}
|
||||
|
||||
// Hide enabled control and force enabled plugin if there is only one plugin available
|
||||
if (type == PluginBase.INSULIN || type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.PROFILE)
|
||||
if (type == PluginBase.INSULIN || type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.PROFILE || type == PluginBase.SENSITIVITY)
|
||||
if (pluginList.size() < 2) {
|
||||
holder.checkboxEnabled.setEnabled(false);
|
||||
plugin.setFragmentEnabled(type, true);
|
||||
|
@ -326,6 +325,9 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
case PluginBase.INSULIN:
|
||||
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
|
||||
break;
|
||||
case PluginBase.SENSITIVITY:
|
||||
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class);
|
||||
break;
|
||||
case PluginBase.APS:
|
||||
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class);
|
||||
break;
|
||||
|
@ -356,6 +358,8 @@ public class ConfigBuilderFragment extends Fragment {
|
|||
MainApp.getSpecificPlugin(VirtualPumpPlugin.class).setFragmentEnabled(type, true);
|
||||
else if (type == PluginBase.INSULIN)
|
||||
MainApp.getSpecificPlugin(InsulinFastactingPlugin.class).setFragmentEnabled(type, true);
|
||||
else if (type == PluginBase.SENSITIVITY)
|
||||
MainApp.getSpecificPlugin(SensitivityOref0Plugin.class).setFragmentEnabled(type, true);
|
||||
else if (type == PluginBase.PROFILE)
|
||||
MainApp.getSpecificPlugin(NSProfilePlugin.class).setFragmentEnabled(type, true);
|
||||
else
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package info.nightscout.androidaps.plugins.ConfigBuilder;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.PowerManager;
|
||||
import android.preference.PreferenceManager;
|
||||
|
@ -22,7 +23,7 @@ import info.nightscout.androidaps.R;
|
|||
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.Intervals;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.androidaps.data.ProfileIntervals;
|
||||
import info.nightscout.androidaps.data.PumpEnactResult;
|
||||
|
@ -40,16 +41,19 @@ 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.SensitivityInterface;
|
||||
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
|
||||
import info.nightscout.androidaps.plugins.Loop.APSResult;
|
||||
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
|
||||
import info.nightscout.androidaps.plugins.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.PumpVirtual.VirtualPumpPlugin;
|
||||
import info.nightscout.utils.NSUpload;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 05.08.2016.
|
||||
|
@ -64,6 +68,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
private static APSInterface activeAPS;
|
||||
private static LoopPlugin activeLoop;
|
||||
private static InsulinInterface activeInsulin;
|
||||
private static SensitivityInterface activeSensitivity;
|
||||
|
||||
static public String nightscoutVersionName = "";
|
||||
static public Integer nightscoutVersionCode = 0;
|
||||
|
@ -78,7 +83,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
MainApp.bus().register(this);
|
||||
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
|
||||
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ConfigBuilderPlugin");
|
||||
;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -208,11 +212,20 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
return activeLoop;
|
||||
}
|
||||
|
||||
public static PumpInterface getActivePump() {
|
||||
return activePump;
|
||||
}
|
||||
|
||||
public static SensitivityInterface getActiveSensitivity() {
|
||||
return activeSensitivity;
|
||||
}
|
||||
|
||||
void logPluginStatus() {
|
||||
for (PluginBase p : pluginList) {
|
||||
log.debug(p.getName() + ":" +
|
||||
(p.isEnabled(1) ? " GENERAL" : "") +
|
||||
(p.isEnabled(2) ? " TREATMENT" : "") +
|
||||
(p.isEnabled(3) ? " SENSITIVITY" : "") +
|
||||
(p.isEnabled(4) ? " PROFILE" : "") +
|
||||
(p.isEnabled(5) ? " APS" : "") +
|
||||
(p.isEnabled(6) ? " PUMP" : "") +
|
||||
|
@ -251,6 +264,17 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
}
|
||||
|
||||
// PluginBase.SENSITIVITY
|
||||
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class);
|
||||
activeSensitivity = (SensitivityInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.SENSITIVITY);
|
||||
if (Config.logConfigBuilder)
|
||||
log.debug("Selected sensitivity interface: " + ((PluginBase) activeSensitivity).getName());
|
||||
for (PluginBase p : pluginsInCategory) {
|
||||
if (!p.getName().equals(((PluginBase) activeSensitivity).getName())) {
|
||||
p.setFragmentVisible(PluginBase.SENSITIVITY, false);
|
||||
}
|
||||
}
|
||||
|
||||
// PluginBase.PROFILE
|
||||
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
|
||||
activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
|
||||
|
@ -406,43 +430,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
return 0d;
|
||||
}
|
||||
|
||||
/*
|
||||
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);
|
||||
|
||||
BolusProgressDialog bolusProgressDialog = null;
|
||||
if (context != null) {
|
||||
bolusProgressDialog = new BolusProgressDialog();
|
||||
bolusProgressDialog.setInsulin(insulin);
|
||||
bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress");
|
||||
}
|
||||
|
||||
MainApp.bus().post(new EventBolusRequested(insulin));
|
||||
|
||||
result = activePump.deliverTreatment(insulinType, insulin, carbs, context);
|
||||
|
||||
BolusProgressDialog.bolusEnded = true;
|
||||
|
||||
MainApp.bus().post(new EventDismissBolusprogressIfRunning(result));
|
||||
|
||||
if (result.success) {
|
||||
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.date = new Date().getTime();
|
||||
t.mealBolus = result.carbsDelivered > 0;
|
||||
addToHistoryTreatment(t);
|
||||
t.carbs = (double) result.carbsDelivered;
|
||||
NSUpload.uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
|
||||
}
|
||||
mWakeLock.release();
|
||||
return result;
|
||||
}
|
||||
*/
|
||||
@Override
|
||||
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
|
||||
mWakeLock.acquire();
|
||||
|
@ -455,8 +442,15 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
bolusProgressDialog = new BolusProgressDialog();
|
||||
bolusProgressDialog.setInsulin(detailedBolusInfo.insulin);
|
||||
bolusProgressDialog.show(((AppCompatActivity) detailedBolusInfo.context).getSupportFragmentManager(), "BolusProgress");
|
||||
} else {
|
||||
Intent i = new Intent();
|
||||
i.putExtra("insulin", detailedBolusInfo.insulin);
|
||||
i.setClass(MainApp.instance(), BolusProgressHelperActivity.class);
|
||||
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
MainApp.instance().startActivity(i);
|
||||
}
|
||||
|
||||
|
||||
MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin));
|
||||
|
||||
result = activePump.deliverTreatment(detailedBolusInfo);
|
||||
|
@ -468,56 +462,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context) {
|
||||
return deliverTreatment(insulinType, insulin, carbs, context, true);
|
||||
}
|
||||
|
||||
public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context, boolean createTreatment) {
|
||||
mWakeLock.acquire();
|
||||
PumpEnactResult result;
|
||||
insulin = applyBolusConstraints(insulin);
|
||||
carbs = applyCarbsConstraints(carbs);
|
||||
|
||||
BolusProgressDialog bolusProgressDialog = null;
|
||||
if (context != null) {
|
||||
bolusProgressDialog = new BolusProgressDialog();
|
||||
bolusProgressDialog.setInsulin(insulin);
|
||||
bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress");
|
||||
} else {
|
||||
Intent i = new Intent();
|
||||
i.putExtra("insulin", insulin.doubleValue());
|
||||
i.setClass(MainApp.instance(), BolusProgressHelperActivity.class);
|
||||
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
MainApp.instance().startActivity(i);
|
||||
}
|
||||
|
||||
MainApp.bus().post(new EventBolusRequested(insulin));
|
||||
|
||||
result = activePump.deliverTreatment(insulinType, insulin, carbs, context);
|
||||
|
||||
BolusProgressDialog.bolusEnded = true;
|
||||
|
||||
MainApp.bus().post(new EventDismissBolusprogressIfRunning(result));
|
||||
|
||||
if (Config.logCongigBuilderActions)
|
||||
log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
|
||||
|
||||
if (result.success && createTreatment) {
|
||||
Treatment t = new Treatment(insulinType);
|
||||
t.insulin = result.bolusDelivered;
|
||||
t.carbs = (double) result.carbsDelivered;
|
||||
t.date = new Date().getTime();
|
||||
t.mealBolus = t.carbs > 0;
|
||||
addToHistoryTreatment(t);
|
||||
NSUpload.uploadTreatment(t);
|
||||
}
|
||||
mWakeLock.release();
|
||||
return result;
|
||||
}
|
||||
|
||||
*/
|
||||
@Override
|
||||
public void stopBolusDelivering() {
|
||||
activePump.stopBolusDelivering();
|
||||
|
@ -565,8 +509,8 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
|
||||
@Override
|
||||
public PumpEnactResult cancelTempBasal() {
|
||||
PumpEnactResult result = activePump.cancelTempBasal();
|
||||
public PumpEnactResult cancelTempBasal(boolean userRequested) {
|
||||
PumpEnactResult result = activePump.cancelTempBasal(userRequested);
|
||||
if (Config.logCongigBuilderActions)
|
||||
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
|
||||
return result;
|
||||
|
@ -615,7 +559,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
if (isTempBasalInProgress()) {
|
||||
if (Config.logCongigBuilderActions)
|
||||
log.debug("applyAPSRequest: cancelTempBasal()");
|
||||
result = cancelTempBasal();
|
||||
result = cancelTempBasal(false);
|
||||
} else {
|
||||
result = new PumpEnactResult();
|
||||
result.absolute = request.rate;
|
||||
|
@ -629,7 +573,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
} else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRateHistory()) < 0.05) {
|
||||
result = new PumpEnactResult();
|
||||
result.absolute = getTempBasalAbsoluteRateHistory();
|
||||
result.duration = getTempBasalFromHistory(new Date().getTime()).getPlannedRemainingMinutes();
|
||||
result.duration = getTempBasalFromHistory(System.currentTimeMillis()).getPlannedRemainingMinutes();
|
||||
result.enacted = false;
|
||||
result.comment = "Temp basal set correctly";
|
||||
result.success = true;
|
||||
|
@ -684,8 +628,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
|
||||
@Override
|
||||
public boolean isFakingTempsByExtendedBoluses() {
|
||||
if (Config.NSCLIENT)
|
||||
return false;
|
||||
return activePump.isFakingTempsByExtendedBoluses();
|
||||
}
|
||||
|
||||
|
@ -884,7 +826,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
|
||||
@Override
|
||||
public OverlappingIntervals<TemporaryBasal> getTemporaryBasalsFromHistory() {
|
||||
public Intervals<TemporaryBasal> getTemporaryBasalsFromHistory() {
|
||||
return activeTreatments.getTemporaryBasalsFromHistory();
|
||||
}
|
||||
|
||||
|
@ -931,7 +873,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
|
||||
@Override
|
||||
public OverlappingIntervals<ExtendedBolus> getExtendedBolusesFromHistory() {
|
||||
public Intervals<ExtendedBolus> getExtendedBolusesFromHistory() {
|
||||
return activeTreatments.getExtendedBolusesFromHistory();
|
||||
}
|
||||
|
||||
|
@ -953,7 +895,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
|
||||
@Override
|
||||
public OverlappingIntervals<TempTarget> getTempTargetsFromHistory() {
|
||||
public Intervals<TempTarget> getTempTargetsFromHistory() {
|
||||
return activeTreatments.getTempTargetsFromHistory();
|
||||
}
|
||||
|
||||
|
@ -980,7 +922,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
|
||||
public String getProfileName() {
|
||||
return getProfileName(new Date().getTime());
|
||||
return getProfileName(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public String getProfileName(long time) {
|
||||
|
@ -1003,28 +945,33 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
|
|||
}
|
||||
|
||||
public Profile getProfile() {
|
||||
return getProfile(new Date().getTime());
|
||||
return getProfile(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public String getProfileUnits() {
|
||||
return activeProfile.getUnits();
|
||||
}
|
||||
|
||||
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 {
|
||||
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
|
||||
if (profile != null)
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
// Unable to determine profile, failover to default
|
||||
if (activeProfile.getProfile() == null)
|
||||
if (activeTreatments == null)
|
||||
return null; //app not initialized
|
||||
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
|
||||
boolean ignoreProfileSwitchEvents = SP.getBoolean(R.string.key_do_not_track_profile_switch, false);
|
||||
if (!ignoreProfileSwitchEvents) {
|
||||
ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time);
|
||||
if (profileSwitch != null) {
|
||||
if (profileSwitch.profileJson != null) {
|
||||
return profileSwitch.getProfileObject();
|
||||
} else if (activeProfile.getProfile() != null) {
|
||||
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
|
||||
if (profile != null)
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package info.nightscout.androidaps.plugins.ConfigBuilder;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.data.DetailedBolusInfo;
|
||||
|
||||
/**
|
||||
* Created by mike on 08.08.2017.
|
||||
*/
|
||||
|
||||
public class DetailedBolusInfoStorage {
|
||||
private static Logger log = LoggerFactory.getLogger(DetailedBolusInfoStorage.class);
|
||||
private static List<DetailedBolusInfo> store = new ArrayList<>();
|
||||
|
||||
public static void add(DetailedBolusInfo detailedBolusInfo) {
|
||||
log.debug("Bolus info stored: " + new Date(detailedBolusInfo.date).toLocaleString());
|
||||
store.add(detailedBolusInfo);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static DetailedBolusInfo findDetailedBolusInfo(long bolustime) {
|
||||
DetailedBolusInfo found = null;
|
||||
for (int i = 0; i < store.size(); i++) {
|
||||
long infoTime = store.get(0).date;
|
||||
log.debug("Existing info: " + new Date(infoTime).toLocaleString());
|
||||
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
|
||||
found = store.get(i);
|
||||
store.remove(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
}
|
|
@ -91,7 +91,7 @@ public class ObjectivesFragment extends Fragment {
|
|||
}
|
||||
});
|
||||
|
||||
Long now = new Date().getTime();
|
||||
Long now = System.currentTimeMillis();
|
||||
if (position > 0 && objectives.get(position - 1).accomplished.getTime() == 0) {
|
||||
// Phase 0: previous not completed
|
||||
holder.startedLayout.setVisibility(View.GONE);
|
||||
|
|
|
@ -10,6 +10,7 @@ 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.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
|
@ -67,8 +68,7 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
|
|||
|
||||
@Override
|
||||
public boolean isVisibleInTabs(int type) {
|
||||
LoopPlugin loopPlugin = (LoopPlugin) MainApp.getSpecificPlugin(LoopPlugin.class);
|
||||
return type == CONSTRAINTS && fragmentVisible && loopPlugin != null && loopPlugin.isVisibleInTabs(LOOP);
|
||||
return type == CONSTRAINTS && fragmentVisible && !BuildConfig.NSCLIENTOLNY;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -1,17 +0,0 @@
|
|||
package info.nightscout.androidaps.plugins.ConstraintsSafety;
|
||||
|
||||
|
||||
import android.support.v4.app.Fragment;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SafetyFragment extends Fragment {
|
||||
private static Logger log = LoggerFactory.getLogger(SafetyFragment.class);
|
||||
|
||||
private static SafetyPlugin safetyPlugin = new SafetyPlugin();
|
||||
|
||||
public static SafetyPlugin getPlugin() {
|
||||
return safetyPlugin;
|
||||
}
|
||||
}
|
|
@ -21,9 +21,17 @@ import info.nightscout.utils.SP;
|
|||
public class SafetyPlugin implements PluginBase, ConstraintsInterface {
|
||||
private static Logger log = LoggerFactory.getLogger(SafetyPlugin.class);
|
||||
|
||||
static SafetyPlugin plugin = null;
|
||||
|
||||
public static SafetyPlugin getPlugin() {
|
||||
if (plugin == null)
|
||||
plugin = new SafetyPlugin();
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFragmentClass() {
|
||||
return SafetyFragment.class.getName();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -38,7 +38,7 @@ public class ActivityGraph extends GraphView {
|
|||
double dia = insulin.getDia();
|
||||
int hours = (int) Math.floor(dia + 1);
|
||||
|
||||
Treatment t = new Treatment(insulin);
|
||||
Treatment t = new Treatment(insulin, dia);
|
||||
t.date = 0;
|
||||
t.insulin = 1d;
|
||||
|
||||
|
@ -63,6 +63,7 @@ public class ActivityGraph extends GraphView {
|
|||
getViewport().setMaxX(hours * 60);
|
||||
getGridLabelRenderer().setNumHorizontalLabels(hours + 1);
|
||||
getGridLabelRenderer().setHorizontalAxisTitle("[min]");
|
||||
getGridLabelRenderer().setVerticalLabelsColor(activitySeries.getColor());
|
||||
|
||||
DataPoint[] iobDataPoints = new DataPoint[iobArray.size()];
|
||||
iobDataPoints = iobArray.toArray(iobDataPoints);
|
||||
|
@ -72,5 +73,6 @@ public class ActivityGraph extends GraphView {
|
|||
iobSeries.setBackgroundColor(Color.argb(70, 255, 0, 255));
|
||||
getSecondScale().setMinY(0);
|
||||
getSecondScale().setMaxY(1);
|
||||
getGridLabelRenderer().setVerticalLabelsSecondScaleColor(Color.MAGENTA);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -35,12 +35,22 @@ public class InsulinFastactingFragment extends Fragment {
|
|||
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);
|
||||
updateGUI();
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
private void updateGUI() {
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.InsulinFastacting;
|
||||
|
||||
import info.nightscout.androidaps.Constants;
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.data.Iob;
|
||||
|
@ -89,7 +90,7 @@ public class InsulinFastactingPlugin implements PluginBase, InsulinInterface {
|
|||
|
||||
@Override
|
||||
public double getDia() {
|
||||
return MainApp.getConfigBuilder().getProfile().getDia();
|
||||
return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : Constants.defaultDIA;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -36,12 +36,22 @@ public class InsulinFastactingProlongedFragment extends Fragment {
|
|||
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);
|
||||
updateGUI();
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
private void updateGUI() {
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.InsulinFastactingProlonged;
|
||||
|
||||
import info.nightscout.androidaps.Constants;
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.data.Iob;
|
||||
|
@ -89,7 +90,7 @@ public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInte
|
|||
|
||||
@Override
|
||||
public double getDia() {
|
||||
return MainApp.getConfigBuilder().getProfile().getDia();
|
||||
return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : Constants.defaultDIA;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -1,28 +1,95 @@
|
|||
package info.nightscout.androidaps.plugins.IobCobCalculator;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.androidaps.db.Treatment;
|
||||
import info.nightscout.androidaps.interfaces.PluginBase;
|
||||
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 25.04.2017.
|
||||
*/
|
||||
|
||||
public class AutosensData {
|
||||
long time = 0L;
|
||||
private static Logger log = LoggerFactory.getLogger(AutosensData.class);
|
||||
|
||||
static class CarbsInPast {
|
||||
long time = 0L;
|
||||
double carbs = 0d;
|
||||
double min5minCarbImpact = 0d;
|
||||
double remaining = 0d;
|
||||
|
||||
public CarbsInPast(Treatment t) {
|
||||
time = t.date;
|
||||
carbs = t.carbs;
|
||||
remaining = t.carbs;
|
||||
if (MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class) != null && MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class).isEnabled(PluginBase.SENSITIVITY)) {
|
||||
double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, 4d);
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile(t.date);
|
||||
double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits());
|
||||
double ic = profile.getIc(t.date);
|
||||
min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic;
|
||||
log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic);
|
||||
} else {
|
||||
min5minCarbImpact = SP.getDouble("openapsama_min_5m_carbimpact", 3.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public long time = 0L;
|
||||
public String pastSensitivity = "";
|
||||
public double deviation = 0d;
|
||||
boolean calculateWithDeviation = false;
|
||||
boolean nonCarbsDeviation = false;
|
||||
public boolean nonEqualDeviation = false;
|
||||
List<CarbsInPast> activeCarbsList = new ArrayList<>();
|
||||
double absorbed = 0d;
|
||||
public double carbsFromBolus = 0d;
|
||||
public double cob = 0;
|
||||
public double bgi = 0d;
|
||||
public double delta = 0d;
|
||||
|
||||
public double autosensRatio = 1d;
|
||||
|
||||
public String log(long time) {
|
||||
return "AutosensData: " + new Date(time).toLocaleString() + " " + pastSensitivity + " Delta=" + delta + " Bgi=" + bgi + " Deviation=" + deviation + " Absorbed=" + absorbed + " CarbsFromBolus=" + carbsFromBolus + " COB=" + cob;
|
||||
return "AutosensData: " + new Date(time).toLocaleString() + " " + pastSensitivity + " Delta=" + delta + " Bgi=" + bgi + " Deviation=" + deviation + " Absorbed=" + absorbed + " CarbsFromBolus=" + carbsFromBolus + " COB=" + cob + " autosensRatio=" + autosensRatio;
|
||||
}
|
||||
|
||||
public int minOld() {
|
||||
return (int) ((new Date().getTime() - time) / 1000 / 60);
|
||||
return (int) ((System.currentTimeMillis() - time) / 1000 / 60);
|
||||
}
|
||||
|
||||
// remove carbs older than 4h
|
||||
public void removeOldCarbs(long toTime) {
|
||||
for (int i = 0; i < activeCarbsList.size(); i++) {
|
||||
CarbsInPast c = activeCarbsList.get(i);
|
||||
if (c.time + 4 * 60 * 60 * 1000L < toTime) {
|
||||
activeCarbsList.remove(i--);
|
||||
if (c.remaining > 0)
|
||||
cob -= c.remaining;
|
||||
log.debug("Removing carbs at "+ new Date(toTime).toLocaleString() + " + after 4h :" + new Date(c.time).toLocaleString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void substractAbosorbedCarbs() {
|
||||
double ac = absorbed;
|
||||
for (int i = 0; i < activeCarbsList.size() && ac > 0; i++) {
|
||||
CarbsInPast c = activeCarbsList.get(i);
|
||||
if (c.remaining > 0) {
|
||||
double sub = Math.min(ac, c.remaining);
|
||||
c.remaining -= sub;
|
||||
ac -= sub;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,16 +0,0 @@
|
|||
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;
|
||||
}
|
||||
}
|
|
@ -12,27 +12,27 @@ 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.R;
|
||||
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.EventConfigBuilderChange;
|
||||
import info.nightscout.androidaps.events.EventNewBG;
|
||||
import info.nightscout.androidaps.events.EventNewBasalProfile;
|
||||
import info.nightscout.androidaps.events.EventPreferenceChange;
|
||||
import info.nightscout.androidaps.interfaces.PluginBase;
|
||||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
|
||||
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.
|
||||
|
@ -53,7 +53,23 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
private static Handler sHandler = null;
|
||||
private static HandlerThread sHandlerThread = null;
|
||||
|
||||
private static Object dataLock = new Object();
|
||||
private static final Object dataLock = new Object();
|
||||
|
||||
private static IobCobCalculatorPlugin plugin = null;
|
||||
|
||||
public static IobCobCalculatorPlugin getPlugin() {
|
||||
if (plugin == null)
|
||||
plugin = new IobCobCalculatorPlugin();
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public static LongSparseArray<AutosensData> getAutosensDataTable() {
|
||||
return autosensDataTable;
|
||||
}
|
||||
|
||||
public static List<BgReading> getBucketedData() {
|
||||
return bucketed_data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getType() {
|
||||
|
@ -62,7 +78,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
|
||||
@Override
|
||||
public String getFragmentClass() {
|
||||
return IobCobCalculatorFragment.class.getName();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -110,7 +126,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
|
||||
}
|
||||
|
||||
public IobCobCalculatorPlugin() {
|
||||
IobCobCalculatorPlugin() {
|
||||
MainApp.bus().register(this);
|
||||
if (sHandlerThread == null) {
|
||||
sHandlerThread = new HandlerThread(IobCobCalculatorPlugin.class.getSimpleName());
|
||||
|
@ -158,13 +174,102 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
//log.debug("Locking loadBgData");
|
||||
synchronized (dataLock) {
|
||||
onNewProfile(null);
|
||||
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (new Date().getTime() - 60 * 60 * 1000L * (24 + dia)), false);
|
||||
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (System.currentTimeMillis() - 60 * 60 * 1000L * (24 + dia)), false);
|
||||
log.debug("BG data loaded. Size: " + bgReadings.size());
|
||||
}
|
||||
//log.debug("Releasing loadBgData");
|
||||
}
|
||||
|
||||
public void createBucketedData() {
|
||||
private boolean isAbout5minData() {
|
||||
synchronized (dataLock) {
|
||||
if (bgReadings == null || bgReadings.size() < 3) {
|
||||
return true;
|
||||
}
|
||||
long totalDiff = 0;
|
||||
for (int i = 1; i < bgReadings.size(); ++i) {
|
||||
long bgTime = bgReadings.get(i).date;
|
||||
long lastbgTime = bgReadings.get(i - 1).date;
|
||||
long diff = lastbgTime - bgTime;
|
||||
totalDiff += diff;
|
||||
if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30
|
||||
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
double intervals = totalDiff / (5 * 60 * 1000d);
|
||||
double variability = Math.abs(intervals - Math.round(intervals));
|
||||
boolean is5mindata = variability < 0.02;
|
||||
log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata);
|
||||
return is5mindata;
|
||||
}
|
||||
}
|
||||
|
||||
private void createBucketedData() {
|
||||
if (isAbout5minData())
|
||||
createBucketedData5min();
|
||||
else
|
||||
createBucketedDataRecalculated();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private BgReading findNewer(long time) {
|
||||
BgReading lastFound = bgReadings.get(0);
|
||||
if (lastFound.date < time) return null;
|
||||
for (int i = 1; i < bgReadings.size(); ++i) {
|
||||
if (bgReadings.get(i).date > time) continue;
|
||||
lastFound = bgReadings.get(i);
|
||||
if (bgReadings.get(i).date < time) break;
|
||||
}
|
||||
return lastFound;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private BgReading findOlder(long time) {
|
||||
BgReading lastFound = bgReadings.get(bgReadings.size() - 1);
|
||||
if (lastFound.date > time) return null;
|
||||
for (int i = bgReadings.size() - 2; i >=0 ; --i) {
|
||||
if (bgReadings.get(i).date < time) continue;
|
||||
lastFound = bgReadings.get(i);
|
||||
if (bgReadings.get(i).date > time) break;
|
||||
}
|
||||
return lastFound;
|
||||
}
|
||||
|
||||
private void createBucketedDataRecalculated() {
|
||||
synchronized (dataLock) {
|
||||
if (bgReadings == null || bgReadings.size() < 3) {
|
||||
bucketed_data = null;
|
||||
return;
|
||||
}
|
||||
|
||||
bucketed_data = new ArrayList<>();
|
||||
long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L;
|
||||
//log.debug("First reading: " + new Date(currentTime).toLocaleString());
|
||||
|
||||
while (true) {
|
||||
// test if current value is older than current time
|
||||
BgReading newer = findNewer(currentTime);
|
||||
BgReading older = findOlder(currentTime);
|
||||
if (newer == null || older == null)
|
||||
break;
|
||||
|
||||
double bgDelta = newer.value - older.value;
|
||||
long timeDiffToNew = newer.date - currentTime;
|
||||
|
||||
double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta;
|
||||
BgReading newBgreading = new BgReading();
|
||||
newBgreading.date = currentTime;
|
||||
newBgreading.value = Math.round(currentBg);
|
||||
bucketed_data.add(newBgreading);
|
||||
//log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")");
|
||||
currentTime -= 5 * 60 * 1000L;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void createBucketedData5min() {
|
||||
//log.debug("Locking createBucketedData");
|
||||
synchronized (dataLock) {
|
||||
if (bgReadings == null || bgReadings.size() < 3) {
|
||||
|
@ -230,10 +335,14 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
//log.debug("Releasing createBucketedData");
|
||||
}
|
||||
|
||||
public void calculateSensitivityData() {
|
||||
private void calculateSensitivityData() {
|
||||
if (MainApp.getConfigBuilder() == null)
|
||||
return; // app still initializing
|
||||
if (MainApp.getConfigBuilder().getProfile() == null)
|
||||
return; // app still initializing
|
||||
//log.debug("Locking calculateSensitivityData");
|
||||
long oldestTimeWithData = oldestDataAvailable();
|
||||
|
||||
synchronized (dataLock) {
|
||||
|
||||
if (bucketed_data == null || bucketed_data.size() < 3) {
|
||||
|
@ -261,6 +370,10 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
|
||||
AutosensData autosensData = new AutosensData();
|
||||
autosensData.time = bgTime;
|
||||
if (previous != null)
|
||||
autosensData.activeCarbsList = new ArrayList<>(previous.activeCarbsList);
|
||||
else
|
||||
autosensData.activeCarbsList = new ArrayList<>();
|
||||
|
||||
//console.error(bgTime , bucketed_data[i].glucose);
|
||||
double bg;
|
||||
|
@ -273,7 +386,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
}
|
||||
delta = (bg - bucketed_data.get(i + 1).value);
|
||||
|
||||
IobTotal iob = calulateFromTreatmentsAndTemps(bgTime);
|
||||
IobTotal iob = calculateFromTreatmentsAndTemps(bgTime);
|
||||
|
||||
double bgi = -iob.activity * sens * 5;
|
||||
double deviation = delta - bgi;
|
||||
|
@ -281,17 +394,28 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
List<Treatment> recentTreatments = MainApp.getConfigBuilder().getTreatments5MinBackFromHistory(bgTime);
|
||||
for (int ir = 0; ir < recentTreatments.size(); ir++) {
|
||||
autosensData.carbsFromBolus += recentTreatments.get(ir).carbs;
|
||||
autosensData.activeCarbsList.add(new AutosensData.CarbsInPast(recentTreatments.get(ir)));
|
||||
}
|
||||
|
||||
|
||||
// if we are absorbing carbs
|
||||
if (previous != null && previous.cob > 0) {
|
||||
// calculate sum of min carb impact from all active treatments
|
||||
double totalMinCarbsImpact = 0d;
|
||||
for (int ii = 0; ii < autosensData.activeCarbsList.size(); ++ii) {
|
||||
AutosensData.CarbsInPast c = autosensData.activeCarbsList.get(ii);
|
||||
totalMinCarbsImpact += c.min5minCarbImpact;
|
||||
}
|
||||
|
||||
// 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));
|
||||
// but always assume at least 3mg/dL/5m (default) absorption per active treatment
|
||||
double ci = Math.max(deviation, totalMinCarbsImpact);
|
||||
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.substractAbosorbedCarbs();
|
||||
}
|
||||
autosensData.removeOldCarbs(bgTime);
|
||||
autosensData.cob += autosensData.carbsFromBolus;
|
||||
autosensData.deviation = deviation;
|
||||
autosensData.bgi = bgi;
|
||||
|
@ -301,12 +425,15 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
if (autosensData.cob <= 0) {
|
||||
if (Math.abs(deviation) < Constants.DEVIATION_TO_BE_EQUAL) {
|
||||
autosensData.pastSensitivity += "=";
|
||||
autosensData.nonEqualDeviation = true;
|
||||
} else if (deviation > 0) {
|
||||
autosensData.pastSensitivity += "+";
|
||||
autosensData.nonEqualDeviation = true;
|
||||
} else {
|
||||
autosensData.pastSensitivity += "-";
|
||||
autosensData.nonEqualDeviation = true;
|
||||
}
|
||||
autosensData.calculateWithDeviation = true;
|
||||
autosensData.nonCarbsDeviation = true;
|
||||
} else {
|
||||
autosensData.pastSensitivity += "C";
|
||||
}
|
||||
|
@ -314,6 +441,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
|
||||
previous = autosensData;
|
||||
autosensDataTable.put(bgTime, autosensData);
|
||||
autosensData.autosensRatio = detectSensitivity(oldestTimeWithData, bgTime).ratio;
|
||||
if (Config.logAutosensData)
|
||||
log.debug(autosensData.log(bgTime));
|
||||
}
|
||||
|
@ -322,29 +450,41 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
//log.debug("Releasing calculateSensitivityData");
|
||||
}
|
||||
|
||||
public static IobTotal calulateFromTreatmentsAndTemps(long time) {
|
||||
long now = new Date().getTime();
|
||||
public static long oldestDataAvailable() {
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
long oldestDataAvailable = MainApp.getConfigBuilder().oldestDataAvailable();
|
||||
long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - 60 * 60 * 1000L * (24 + MainApp.getConfigBuilder().getProfile().getDia())));
|
||||
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString());
|
||||
return getBGDataFrom;
|
||||
}
|
||||
|
||||
public static IobTotal calculateFromTreatmentsAndTempsSynchronized(long time) {
|
||||
synchronized (dataLock) {
|
||||
return calculateFromTreatmentsAndTemps(time);
|
||||
}
|
||||
}
|
||||
|
||||
public static IobTotal calculateFromTreatmentsAndTemps(long time) {
|
||||
long now = System.currentTimeMillis();
|
||||
time = roundUpTime(time);
|
||||
if (time < now && iobTable.get(time) != null) {
|
||||
//log.debug(">>> Cache hit");
|
||||
//og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString());
|
||||
return iobTable.get(time);
|
||||
} else {
|
||||
//log.debug(">>> Cache miss " + new Date(time).toLocaleString());
|
||||
//log.debug(">>> calculateFromTreatmentsAndTemps 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()) {
|
||||
if (time < System.currentTimeMillis()) {
|
||||
iobTable.put(time, iobTotal);
|
||||
}
|
||||
return iobTotal;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static Long findPreviousTimeFromBucketedData(long time) {
|
||||
if (bucketed_data == null)
|
||||
return null;
|
||||
|
@ -356,7 +496,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
}
|
||||
|
||||
public static BasalData getBasalData(long time) {
|
||||
long now = new Date().getTime();
|
||||
long now = System.currentTimeMillis();
|
||||
time = roundUpTime(time);
|
||||
BasalData retval = basalDataTable.get(time);
|
||||
if (retval == null) {
|
||||
|
@ -373,36 +513,40 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
if (time < now) {
|
||||
basalDataTable.append(time, retval);
|
||||
}
|
||||
//log.debug(">>> Cache miss " + new Date(time).toLocaleString());
|
||||
//log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString());
|
||||
} else {
|
||||
//log.debug(">>> Cache hit " + new Date(time).toLocaleString());
|
||||
//log.debug(">>> getBasalData Cache hit " + new Date(time).toLocaleString());
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
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;
|
||||
synchronized (dataLock) {
|
||||
long now = System.currentTimeMillis();
|
||||
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(">>> getAutosensData Cache hit " + data.log(time));
|
||||
return data;
|
||||
} else {
|
||||
//log.debug(">>> getAutosensData Cache miss " + new Date(time).toLocaleString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
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) {
|
||||
if (data.time < System.currentTimeMillis() - 5 * 60 * 1000) {
|
||||
return null;
|
||||
} else {
|
||||
return data;
|
||||
|
@ -412,117 +556,29 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
public static IobTotal[] calculateIobArrayInDia() {
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
// predict IOB out to DIA plus 30m
|
||||
long time = new Date().getTime();
|
||||
long time = System.currentTimeMillis();
|
||||
time = roundUpTime(time);
|
||||
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);
|
||||
IobTotal iob = calculateFromTreatmentsAndTempsSynchronized(t);
|
||||
array[pos] = iob;
|
||||
pos++;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public static AutosensResult detectSensitivity(long fromTime) {
|
||||
//log.debug("Locking detectSensitivity");
|
||||
public static AutosensResult detectSensitivityWithLock(long fromTime, long toTime) {
|
||||
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<Double> 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;
|
||||
return detectSensitivity(fromTime, toTime);
|
||||
}
|
||||
//log.debug("Releasing detectSensitivity");
|
||||
}
|
||||
|
||||
private static AutosensResult detectSensitivity(long fromTime, long toTime) {
|
||||
return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime);
|
||||
}
|
||||
|
||||
public static JSONArray convertToJSONArray(IobTotal[] iobArray) {
|
||||
JSONArray array = new JSONArray();
|
||||
|
@ -549,6 +605,8 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
if (MainApp.getConfigBuilder() == null)
|
||||
return; // app still initializing
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
if (profile == null)
|
||||
return; // app still initializing
|
||||
dia = profile.getDia();
|
||||
if (ev == null) { // on init no need of reset
|
||||
return;
|
||||
|
@ -566,6 +624,41 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
});
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(EventPreferenceChange ev) {
|
||||
if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
|
||||
ev.isChanged(R.string.key_age) ||
|
||||
ev.isChanged(R.string.key_absorption_maxtime)
|
||||
) {
|
||||
synchronized (dataLock) {
|
||||
log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
|
||||
iobTable = new LongSparseArray<>();
|
||||
autosensDataTable = new LongSparseArray<>();
|
||||
}
|
||||
sHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
calculateSensitivityData();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(EventConfigBuilderChange ev) {
|
||||
synchronized (dataLock) {
|
||||
log.debug("Invalidating cached data because of configuration change. 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) {
|
||||
|
@ -575,6 +668,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
|
|||
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)
|
||||
if (Config.logAutosensData)
|
||||
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
|
||||
iobTable.removeAt(index);
|
||||
|
|
|
@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.Loop;
|
|||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.app.Fragment;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
@ -19,10 +18,11 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
|
||||
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
|
||||
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
|
||||
|
||||
public class LoopFragment extends Fragment implements View.OnClickListener {
|
||||
public class LoopFragment extends SubscriberFragment implements View.OnClickListener {
|
||||
private static Logger log = LoggerFactory.getLogger(LoopFragment.class);
|
||||
|
||||
private static LoopPlugin loopPlugin;
|
||||
|
@ -61,18 +61,6 @@ public class LoopFragment extends Fragment implements View.OnClickListener {
|
|||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
super.onPause();
|
||||
MainApp.bus().unregister(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
MainApp.bus().register(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
switch (view.getId()) {
|
||||
|
@ -110,7 +98,8 @@ public class LoopFragment extends Fragment implements View.OnClickListener {
|
|||
}
|
||||
|
||||
|
||||
void updateGUI() {
|
||||
@Override
|
||||
protected void updateGUI() {
|
||||
Activity activity = getActivity();
|
||||
if (activity != null)
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
|
|
|
@ -167,7 +167,7 @@ public class LoopPlugin implements PluginBase {
|
|||
if (loopSuspendedTill == 0)
|
||||
return 0;
|
||||
|
||||
long now = new Date().getTime();
|
||||
long now = System.currentTimeMillis();
|
||||
long msecDiff = loopSuspendedTill - now;
|
||||
|
||||
if (loopSuspendedTill <= now) { // time exceeded
|
||||
|
@ -182,7 +182,7 @@ public class LoopPlugin implements PluginBase {
|
|||
if (loopSuspendedTill == 0)
|
||||
return false;
|
||||
|
||||
long now = new Date().getTime();
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
if (loopSuspendedTill <= now) { // time exceeded
|
||||
suspendTo(0L);
|
||||
|
@ -196,7 +196,7 @@ public class LoopPlugin implements PluginBase {
|
|||
if (loopSuspendedTill == 0)
|
||||
return false;
|
||||
|
||||
long now = new Date().getTime();
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
if (loopSuspendedTill <= now) { // time exceeded
|
||||
suspendTo(0L);
|
||||
|
@ -209,7 +209,7 @@ public class LoopPlugin implements PluginBase {
|
|||
public void invoke(String initiator, boolean allowNotification) {
|
||||
try {
|
||||
if (Config.logFunctionCalls)
|
||||
log.debug("invoke");
|
||||
log.debug("invoke from " + initiator);
|
||||
ConstraintsInterface constraintsInterface = MainApp.getConfigBuilder();
|
||||
if (!constraintsInterface.isLoopEnabled()) {
|
||||
log.debug(MainApp.sResources.getString(R.string.loopdisabled));
|
||||
|
@ -234,6 +234,12 @@ public class LoopPlugin implements PluginBase {
|
|||
return;
|
||||
}
|
||||
|
||||
if (configBuilder.getProfile() == null) {
|
||||
log.debug(MainApp.sResources.getString(R.string.noprofileselected));
|
||||
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.noprofileselected)));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if pump info is loaded
|
||||
if (configBuilder.getBaseBasalRate() < 0.01d) return;
|
||||
|
||||
|
|
|
@ -28,12 +28,13 @@ import org.slf4j.LoggerFactory;
|
|||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.events.EventPreferenceChange;
|
||||
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
|
||||
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 View.OnClickListener, CompoundButton.OnCheckedChangeListener {
|
||||
public class NSClientInternalFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
|
||||
private static Logger log = LoggerFactory.getLogger(NSClientInternalFragment.class);
|
||||
|
||||
static NSClientInternalPlugin nsClientInternalPlugin;
|
||||
|
@ -58,8 +59,6 @@ public class NSClientInternalFragment extends Fragment implements View.OnClickLi
|
|||
private CheckBox autoscrollCheckbox;
|
||||
private CheckBox pausedCheckbox;
|
||||
|
||||
String status = "";
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
|
@ -119,7 +118,7 @@ public class NSClientInternalFragment extends Fragment implements View.OnClickLi
|
|||
builder.setMessage("Clear queue? All data in queue will be lost!");
|
||||
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int id) {
|
||||
getPlugin().queue().clearQueue();
|
||||
UploadQueue.clearQueue();
|
||||
updateGUI();
|
||||
Answers.getInstance().logCustom(new CustomEvent("NSClientClearQueue"));
|
||||
}
|
||||
|
@ -152,36 +151,25 @@ public class NSClientInternalFragment extends Fragment implements View.OnClickLi
|
|||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
super.onPause();
|
||||
MainApp.bus().unregister(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
MainApp.bus().register(this);
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventNSClientUpdateGUI ev) {
|
||||
updateGUI();
|
||||
}
|
||||
|
||||
private void updateGUI() {
|
||||
@Override
|
||||
protected void updateGUI() {
|
||||
Activity activity = getActivity();
|
||||
if (activity != null)
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
logTextView.setText(getPlugin().textLog);
|
||||
NSClientInternalPlugin.updateLog();
|
||||
logTextView.setText(NSClientInternalPlugin.textLog);
|
||||
if (getPlugin().autoscroll) {
|
||||
logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
|
||||
}
|
||||
urlTextView.setText(getPlugin().url());
|
||||
Spanned queuetext = Html.fromHtml(MainApp.sResources.getString(R.string.queue) + " <b>" + getPlugin().queue().size() + "</b>");
|
||||
Spanned queuetext = Html.fromHtml(MainApp.sResources.getString(R.string.queue) + " <b>" + UploadQueue.size() + "</b>");
|
||||
queueTextView.setText(queuetext);
|
||||
statusTextView.setText(getPlugin().status);
|
||||
}
|
||||
|
|
|
@ -9,14 +9,12 @@ import android.os.HandlerThread;
|
|||
import android.os.IBinder;
|
||||
import android.text.Html;
|
||||
import android.text.Spanned;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.squareup.otto.Subscribe;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
@ -36,29 +34,28 @@ import info.nightscout.utils.ToastUtils;
|
|||
public class NSClientInternalPlugin implements PluginBase {
|
||||
private static Logger log = LoggerFactory.getLogger(NSClientInternalPlugin.class);
|
||||
|
||||
boolean fragmentEnabled = true;
|
||||
boolean fragmentVisible = true;
|
||||
private boolean fragmentEnabled = true;
|
||||
private boolean fragmentVisible = true;
|
||||
|
||||
static public Handler handler;
|
||||
static private HandlerThread handlerThread;
|
||||
|
||||
public List<EventNSClientNewLog> listLog = new ArrayList<EventNSClientNewLog>();
|
||||
public Spanned textLog = Html.fromHtml("");
|
||||
private static List<EventNSClientNewLog> listLog = new ArrayList<>();
|
||||
static Spanned textLog = Html.fromHtml("");
|
||||
|
||||
public boolean paused = false;
|
||||
public boolean autoscroll = true;
|
||||
boolean autoscroll = true;
|
||||
|
||||
public String status = "";
|
||||
|
||||
public NSClientService nsClientService = null;
|
||||
|
||||
public NSClientInternalPlugin() {
|
||||
NSClientInternalPlugin() {
|
||||
MainApp.bus().register(this);
|
||||
paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false);
|
||||
autoscroll = SP.getBoolean(R.string.key_nsclientinternal_autoscroll, true);
|
||||
|
||||
if (handler == null) {
|
||||
handlerThread = new HandlerThread(NSClientInternalPlugin.class.getSimpleName() + "Handler");
|
||||
HandlerThread handlerThread = new HandlerThread(NSClientInternalPlugin.class.getSimpleName() + "Handler");
|
||||
handlerThread.start();
|
||||
handler = new Handler(handlerThread.getLooper());
|
||||
}
|
||||
|
@ -129,7 +126,7 @@ public class NSClientInternalPlugin implements PluginBase {
|
|||
if (type == GENERAL) this.fragmentVisible = fragmentVisible;
|
||||
}
|
||||
|
||||
ServiceConnection mConnection = new ServiceConnection() {
|
||||
private ServiceConnection mConnection = new ServiceConnection() {
|
||||
|
||||
public void onServiceDisconnected(ComponentName name) {
|
||||
log.debug("Service is disconnected");
|
||||
|
@ -162,45 +159,44 @@ public class NSClientInternalPlugin implements PluginBase {
|
|||
MainApp.bus().post(new EventNSClientUpdateGUI());
|
||||
}
|
||||
|
||||
public void clearLog() {
|
||||
synchronized void clearLog() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
listLog = new ArrayList<EventNSClientNewLog>();
|
||||
updateLog();
|
||||
listLog = new ArrayList<>();
|
||||
MainApp.bus().post(new EventNSClientUpdateGUI());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void addToLog(final EventNSClientNewLog ev) {
|
||||
private synchronized void addToLog(final EventNSClientNewLog ev) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
|
||||
listLog.add(ev);
|
||||
// remove the first line if log is too large
|
||||
if (listLog.size() >= Constants.MAX_LOG_LINES) {
|
||||
listLog.remove(0);
|
||||
}
|
||||
updateLog();
|
||||
MainApp.bus().post(new EventNSClientUpdateGUI());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updateLog() {
|
||||
static synchronized void updateLog() {
|
||||
try {
|
||||
Spanned newTextLog = Html.fromHtml("");
|
||||
for (EventNSClientNewLog log : listLog) {
|
||||
newTextLog = (Spanned) TextUtils.concat(newTextLog, log.toHtml());
|
||||
StringBuilder newTextLog = new StringBuilder();
|
||||
List<EventNSClientNewLog> temporaryList = new ArrayList<>(listLog);
|
||||
for (EventNSClientNewLog log : temporaryList) {
|
||||
newTextLog.append(log.toPreparedHtml());
|
||||
}
|
||||
textLog = newTextLog;
|
||||
MainApp.bus().post(new EventNSClientUpdateGUI());
|
||||
textLog = Html.fromHtml(newTextLog.toString());
|
||||
} catch (OutOfMemoryError e) {
|
||||
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), "Out of memory!\nStop using this phone !!!", R.raw.error);
|
||||
}
|
||||
}
|
||||
|
||||
public void resend(String reason) {
|
||||
void resend(String reason) {
|
||||
if (nsClientService != null)
|
||||
nsClientService.resend(reason);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,50 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSAlarm;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 11.06.2017.
|
||||
*/
|
||||
|
||||
public class BroadcastAckAlarm {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastAckAlarm.class);
|
||||
|
||||
public static void handleClearAlarm(NSAlarm originalAlarm, Context context, long silenceTimeInMsec) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putInt("level", originalAlarm.getLevel());
|
||||
bundle.putString("group", originalAlarm.getGroup());
|
||||
bundle.putLong("silenceTime", silenceTimeInMsec);
|
||||
Intent intent = new Intent(Intents.ACTION_ACK_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putInt("level", originalAlarm.getLevel());
|
||||
bundle.putString("group", originalAlarm.getGroup());
|
||||
bundle.putLong("silenceTime", silenceTimeInMsec);
|
||||
intent = new Intent(Intents.ACTION_ACK_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 26.06.2016.
|
||||
*/
|
||||
public class BroadcastAlarm {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastAlarm.class);
|
||||
|
||||
public static void handleAlarm(JSONObject alarm, Context context) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("data", alarm.toString());
|
||||
Intent intent = new Intent(Intents.ACTION_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("data", alarm.toString());
|
||||
intent = new Intent(Intents.ACTION_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 26.06.2016.
|
||||
*/
|
||||
public class BroadcastAnnouncement {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastAnnouncement.class);
|
||||
|
||||
public static void handleAnnouncement(JSONObject announcement, Context context) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("data", announcement.toString());
|
||||
Intent intent = new Intent(Intents.ACTION_ANNOUNCEMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("data", announcement.toString());
|
||||
intent = new Intent(Intents.ACTION_ANNOUNCEMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,6 +4,7 @@ import android.content.Context;
|
|||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.slf4j.Logger;
|
||||
|
@ -11,7 +12,10 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 26.06.2016.
|
||||
|
@ -19,16 +23,24 @@ import info.nightscout.androidaps.Services.Intents;
|
|||
public class BroadcastCals {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastCals.class);
|
||||
|
||||
public void handleNewCal(JSONArray cals, Context context, boolean isDelta) {
|
||||
public static void handleNewCal(JSONArray cals, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("cals", cals.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_CAL);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("CAL " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("cals", cals.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_CAL);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,43 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 26.06.2016.
|
||||
*/
|
||||
public class BroadcastClearAlarm {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastClearAlarm.class);
|
||||
|
||||
public static void handleClearAlarm(JSONObject clearalarm, Context context) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("data", clearalarm.toString());
|
||||
Intent intent = new Intent(Intents.ACTION_CLEAR_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("data", clearalarm.toString());
|
||||
intent = new Intent(Intents.ACTION_CLEAR_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,6 +4,7 @@ import android.content.Context;
|
|||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
@ -12,34 +13,58 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
|
||||
public class BroadcastDeviceStatus {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastDeviceStatus.class);
|
||||
|
||||
public void handleNewDeviceStatus(JSONObject status, Context context, boolean isDelta) {
|
||||
public static void handleNewDeviceStatus(JSONObject status, Context context, boolean isDelta) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("devicestatus", status.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("DEVICESTATUS " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("devicestatus", status.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
public void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("devicestatuses", statuses.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
public static void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) {
|
||||
|
||||
log.debug("DEVICESTATUS " + x.size() + " receivers");
|
||||
List<JSONArray> splitted = BroadcastTreatment.splitArray(statuses);
|
||||
for (JSONArray part: splitted) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("devicestatuses", part.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
splitted = BroadcastTreatment.splitArray(statuses);
|
||||
for (JSONArray part : splitted) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("devicestatuses", part.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@ import android.content.Context;
|
|||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.slf4j.Logger;
|
||||
|
@ -11,7 +12,10 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 26.06.2016.
|
||||
|
@ -19,16 +23,24 @@ import info.nightscout.androidaps.Services.Intents;
|
|||
public class BroadcastMbgs {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class);
|
||||
|
||||
public void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
|
||||
public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("mbgs", mbgs.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_MBG);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("MBG " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("mbgs", mbgs.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_MBG);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,14 +4,18 @@ import android.content.Context;
|
|||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.androidaps.data.ProfileStore;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
|
||||
/**
|
||||
|
@ -20,17 +24,25 @@ import info.nightscout.androidaps.data.ProfileStore;
|
|||
public class BroadcastProfile {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class);
|
||||
|
||||
public void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) {
|
||||
public static void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("profile", profile.getData().toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_PROFILE);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("PROFILE " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("profile", profile.getData().toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_PROFILE);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,13 +5,18 @@ import android.content.Intent;
|
|||
import android.os.Bundle;
|
||||
import android.os.PowerManager;
|
||||
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 28.02.2016.
|
||||
*/
|
||||
public class BroadcastQueueStatus {
|
||||
public void handleNewStatus(int size, Context context) {
|
||||
public static void handleNewStatus(int size, Context context) {
|
||||
|
||||
if(!SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) return;
|
||||
|
||||
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
|
||||
"sendQueue");
|
||||
|
|
|
@ -4,6 +4,7 @@ import android.content.Context;
|
|||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
@ -12,7 +13,10 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 22.02.2016.
|
||||
|
@ -20,30 +24,45 @@ import info.nightscout.androidaps.Services.Intents;
|
|||
public class BroadcastSgvs {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastSgvs.class);
|
||||
|
||||
public void handleNewSgv(JSONObject sgv, Context context, boolean isDelta) {
|
||||
public static void handleNewSgv(JSONObject sgv, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("sgv", sgv.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("SGV " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("sgv", sgv.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_SGV);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) {
|
||||
public static void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("sgvs", sgvs.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("SGV " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("sgvs", sgvs.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_SGV);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,6 +5,7 @@ import android.content.Intent;
|
|||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
@ -12,9 +13,11 @@ import org.slf4j.LoggerFactory;
|
|||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 24.02.2016.
|
||||
|
@ -22,14 +25,15 @@ import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientServ
|
|||
public class BroadcastStatus {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastStatus.class);
|
||||
|
||||
public void handleNewStatus(NSStatus status, Context context, boolean isDelta) {
|
||||
public static void handleNewStatus(NSSettingsStatus status, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
try {
|
||||
bundle.putString("nsclientversionname", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionName);
|
||||
bundle.putInt("nsclientversioncode", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode);
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
};
|
||||
}
|
||||
bundle.putString("nightscoutversionname", NSClientService.nightscoutVersionName);
|
||||
bundle.putInt("nightscoutversioncode", NSClientService.nightscoutVersionCode);
|
||||
bundle.putString("status", status.getData().toString());
|
||||
|
@ -37,9 +41,24 @@ public class BroadcastStatus {
|
|||
Intent intent = new Intent(Intents.ACTION_NEW_STATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("STATUS: " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
try {
|
||||
bundle.putString("nsclientversionname", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionName);
|
||||
bundle.putInt("nsclientversioncode", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode);
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
bundle.putString("nightscoutversionname", NSClientService.nightscoutVersionName);
|
||||
bundle.putInt("nightscoutversioncode", NSClientService.nightscoutVersionCode);
|
||||
bundle.putString("status", status.getData().toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_STATUS);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,6 +4,8 @@ import android.content.Context;
|
|||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.os.TransactionTooLargeException;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
|
@ -11,10 +13,15 @@ import org.json.JSONObject;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
|
||||
import info.nightscout.utils.SP;
|
||||
import info.nightscout.utils.ToastUtils;
|
||||
|
||||
/**
|
||||
* Created by mike on 20.02.2016.
|
||||
|
@ -22,86 +29,173 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
|
|||
public class BroadcastTreatment {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class);
|
||||
|
||||
public void handleNewTreatment(NSTreatment treatment, Context context, boolean isDelta) {
|
||||
public static void handleNewTreatment(NSTreatment treatment, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatment", treatment.getData().toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("TREAT_ADD " + treatment.getEventType() + " " + x.size() + " receivers");
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("treatment", treatment.getData().toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_NEW_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleNewTreatment(JSONArray treatments, Context context, boolean isDelta) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", treatments.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
public static void handleNewTreatment(JSONArray treatments, Context context, boolean isDelta) {
|
||||
|
||||
log.debug("TREAT_ADD " + treatments.length() + " " + x.size() + " receivers");
|
||||
List<JSONArray> splitted = splitArray(treatments);
|
||||
for (JSONArray part: splitted) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", part.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)){
|
||||
splitted = splitArray(treatments);
|
||||
for (JSONArray part: splitted) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", part.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void handleChangedTreatment(JSONObject treatment, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatment", treatment.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
try {
|
||||
log.debug("TREAT_CHANGE " + treatment.getString("_id") + " " + x.size() + " receivers");
|
||||
} catch (JSONException e) {}
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("treatment", treatment.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleChangedTreatment(JSONArray treatments, Context context, boolean isDelta) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", treatments.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
public static void handleChangedTreatment(JSONArray treatments, Context context, boolean isDelta) {
|
||||
|
||||
log.debug("TREAT_CHANGE " + treatments.length() + " " + x.size() + " receivers");
|
||||
List<JSONArray> splitted = splitArray(treatments);
|
||||
for (JSONArray part : splitted) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", part.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
splitted = splitArray(treatments);
|
||||
for (JSONArray part : splitted) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", part.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void handleRemovedTreatment(JSONObject treatment, Context context, boolean isDelta) {
|
||||
public static void handleRemovedTreatment(JSONObject treatment, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatment", treatment.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
try {
|
||||
log.debug("TREAT_REMOVE " + treatment.getString("_id") + " " + x.size() + " receivers");
|
||||
} catch (JSONException e) {}
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("treatment", treatment.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleRemovedTreatment(JSONArray treatments, Context context, boolean isDelta) {
|
||||
public static void handleRemovedTreatment(JSONArray treatments, Context context, boolean isDelta) {
|
||||
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("treatments", treatments.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
log.debug("TREAT_REMOVE " + treatments.length() + " treatments " + x.size() + " receivers");
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("treatments", treatments.toString());
|
||||
bundle.putBoolean("delta", isDelta);
|
||||
intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static List<JSONArray> splitArray(JSONArray array) {
|
||||
List<JSONArray> ret = new ArrayList<>();
|
||||
try {
|
||||
int size = array.length();
|
||||
int count = 0;
|
||||
JSONArray newarr = null;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (count == 0) {
|
||||
if (newarr != null) {
|
||||
ret.add(newarr);
|
||||
}
|
||||
newarr = new JSONArray();
|
||||
count = 200;
|
||||
}
|
||||
newarr.put(array.get(i));
|
||||
--count;
|
||||
}
|
||||
if (newarr != null && newarr.length() > 0) {
|
||||
ret.add(newarr);
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
ret = new ArrayList<>();
|
||||
ret.add(array);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,43 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.content.LocalBroadcastManager;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.Intents;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 26.06.2016.
|
||||
*/
|
||||
public class BroadcastUrgentAlarm {
|
||||
private static Logger log = LoggerFactory.getLogger(BroadcastUrgentAlarm.class);
|
||||
|
||||
public static void handleUrgentAlarm(JSONObject urgentalarm, Context context) {
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString("data", urgentalarm.toString());
|
||||
Intent intent = new Intent(Intents.ACTION_URGENT_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
|
||||
|
||||
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
|
||||
bundle = new Bundle();
|
||||
bundle.putString("data", urgentalarm.toString());
|
||||
intent = new Intent(Intents.ACTION_URGENT_ALARM);
|
||||
intent.putExtras(bundle);
|
||||
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
|
||||
context.sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.data;
|
||||
|
||||
/**
|
||||
* Created by mike on 11.06.2017.
|
||||
*/
|
||||
|
||||
public class AlarmAck {
|
||||
public Integer level = null;
|
||||
public String group = null;
|
||||
public Long silenceTime = null;
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.data;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/**
|
||||
* Created by mike on 11.06.2017.
|
||||
*/
|
||||
|
||||
public class NSAlarm {
|
||||
JSONObject data;
|
||||
|
||||
public NSAlarm(JSONObject data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public int getLevel() {
|
||||
int retval = 0;
|
||||
if (data.has("level")) {
|
||||
try {
|
||||
retval = data.getInt("level");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
public String getGroup() {
|
||||
String retval = "N/A";
|
||||
if (data.has("group")) {
|
||||
try {
|
||||
retval = data.getString("group");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
public String getTile() {
|
||||
String retval = "N/A";
|
||||
if (data.has("title")) {
|
||||
try {
|
||||
retval = data.getString("title");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
String retval = "N/A";
|
||||
if (data.has("message")) {
|
||||
try {
|
||||
retval = data.getString("message");
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,387 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.data;
|
||||
|
||||
import android.text.Html;
|
||||
import android.text.Spanned;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.utils.DateUtil;
|
||||
import info.nightscout.utils.Round;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 25.06.2017.
|
||||
*/
|
||||
|
||||
/*
|
||||
{
|
||||
"_id": "594fdcec327b83c81b6b8c0f",
|
||||
"device": "openaps://Sony D5803",
|
||||
"pump": {
|
||||
"battery": {
|
||||
"percent": 100
|
||||
},
|
||||
"status": {
|
||||
"status": "normal",
|
||||
"timestamp": "2017-06-25T15:50:14Z"
|
||||
},
|
||||
"extended": {
|
||||
"Version": "1.5-ac98852-2017.06.25",
|
||||
"PumpIOB": 1.13,
|
||||
"LastBolus": "25. 6. 2017 17:25:00",
|
||||
"LastBolusAmount": 0.3,
|
||||
"BaseBasalRate": 0.4,
|
||||
"ActiveProfile": "2016 +30%"
|
||||
},
|
||||
"reservoir": 109,
|
||||
"clock": "2017-06-25T15:55:10Z"
|
||||
},
|
||||
"openaps": {
|
||||
"suggested": {
|
||||
"temp": "absolute",
|
||||
"bg": 115.9,
|
||||
"tick": "+5",
|
||||
"eventualBG": 105,
|
||||
"snoozeBG": 105,
|
||||
"predBGs": {
|
||||
"IOB": [116, 114, 112, 110, 109, 107, 106, 105, 105, 104, 104, 104, 104, 104, 104, 104, 104, 105, 105, 105, 105, 105, 106, 106, 106, 106, 106, 107]
|
||||
},
|
||||
"COB": 0,
|
||||
"IOB": -0.035,
|
||||
"reason": "COB: 0, Dev: -18, BGI: 0.43, ISF: 216, Target: 99; Eventual BG 105 > 99 but Min. Delta -2.60 < Exp. Delta 0.1; setting current basal of 0.4 as temp. Suggested rate is same as profile rate, no temp basal is active, doing nothing",
|
||||
"timestamp": "2017-06-25T15:55:10Z"
|
||||
},
|
||||
"iob": {
|
||||
"iob": -0.035,
|
||||
"basaliob": -0.035,
|
||||
"activity": -0.0004,
|
||||
"time": "2017-06-25T15:55:10Z"
|
||||
}
|
||||
},
|
||||
"uploaderBattery": 93,
|
||||
"created_at": "2017-06-25T15:55:10Z",
|
||||
"NSCLIENT_ID": 1498406118857
|
||||
}
|
||||
*/
|
||||
public class NSDeviceStatus {
|
||||
|
||||
private static NSDeviceStatus instance = null;
|
||||
|
||||
public static NSDeviceStatus getInstance() {
|
||||
if (instance == null)
|
||||
instance = new NSDeviceStatus();
|
||||
return instance;
|
||||
}
|
||||
|
||||
private JSONObject data = null;
|
||||
|
||||
public NSDeviceStatus() {
|
||||
}
|
||||
|
||||
public NSDeviceStatus setData(JSONObject obj) {
|
||||
this.data = obj;
|
||||
updatePumpData(obj);
|
||||
updateOpenApsData(obj);
|
||||
updateUploaderData(obj);
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDevice() {
|
||||
try {
|
||||
if (data.has("device")) {
|
||||
String device = data.getString("device");
|
||||
if (device.startsWith("openaps://")) {
|
||||
device = device.substring(10);
|
||||
return device;
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static class Levels {
|
||||
static int URGENT = 2;
|
||||
static int WARN = 1;
|
||||
static int INFO = 0;
|
||||
int LOW = -1;
|
||||
int LOWEST = -2;
|
||||
static int NONE = -3;
|
||||
}
|
||||
|
||||
// ***** PUMP DATA ******
|
||||
|
||||
static DeviceStatusPumpData deviceStatusPumpData = null;
|
||||
|
||||
public Spanned getExtendedPumpStatus() {
|
||||
if (deviceStatusPumpData.extended != null)
|
||||
return deviceStatusPumpData.extended;
|
||||
return Html.fromHtml("");
|
||||
}
|
||||
|
||||
public Spanned getPumpStatus() {
|
||||
//String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"};
|
||||
|
||||
if (deviceStatusPumpData == null)
|
||||
return Html.fromHtml("");
|
||||
|
||||
StringBuilder string = new StringBuilder();
|
||||
// test warning level
|
||||
int level = Levels.INFO;
|
||||
long now = System.currentTimeMillis();
|
||||
if (deviceStatusPumpData.clock + NSSettingsStatus.getInstance().extendedPumpSettings("urgentClock") * 60 * 1000L < now)
|
||||
level = Levels.URGENT;
|
||||
else if (deviceStatusPumpData.reservoir < NSSettingsStatus.getInstance().extendedPumpSettings("urgentRes"))
|
||||
level = Levels.URGENT;
|
||||
else if (deviceStatusPumpData.isPercent && deviceStatusPumpData.percent < NSSettingsStatus.getInstance().extendedPumpSettings("urgentBattP"))
|
||||
level = Levels.URGENT;
|
||||
else if (!deviceStatusPumpData.isPercent && deviceStatusPumpData.voltage < NSSettingsStatus.getInstance().extendedPumpSettings("urgentBattV"))
|
||||
level = Levels.URGENT;
|
||||
else if (deviceStatusPumpData.clock + NSSettingsStatus.getInstance().extendedPumpSettings("warnClock") < now)
|
||||
level = Levels.WARN;
|
||||
else if (deviceStatusPumpData.reservoir < NSSettingsStatus.getInstance().extendedPumpSettings("warnRes"))
|
||||
level = Levels.WARN;
|
||||
else if (deviceStatusPumpData.isPercent && deviceStatusPumpData.percent < NSSettingsStatus.getInstance().extendedPumpSettings("warnBattP"))
|
||||
level = Levels.WARN;
|
||||
else if (!deviceStatusPumpData.isPercent && deviceStatusPumpData.voltage < NSSettingsStatus.getInstance().extendedPumpSettings("warnBattV"))
|
||||
level = Levels.WARN;
|
||||
|
||||
string.append("<span style=\"color:");
|
||||
if (level == Levels.INFO) string.append("white\">");
|
||||
if (level == Levels.WARN) string.append("yellow\">");
|
||||
if (level == Levels.URGENT) string.append("red\">");
|
||||
|
||||
String fields = NSSettingsStatus.getInstance().pumpExtentendedSettingsFields();
|
||||
|
||||
if (fields.contains("reservoir")) {
|
||||
string.append((int) deviceStatusPumpData.reservoir).append("U ");
|
||||
}
|
||||
|
||||
if (fields.contains("battery") && deviceStatusPumpData.isPercent) {
|
||||
string.append(deviceStatusPumpData.percent).append("% ");
|
||||
}
|
||||
if (fields.contains("battery") && !deviceStatusPumpData.isPercent) {
|
||||
string.append(Round.roundTo(deviceStatusPumpData.voltage, 0.001d)).append(" ");
|
||||
}
|
||||
|
||||
if (fields.contains("clock")) {
|
||||
string.append(DateUtil.minAgo(deviceStatusPumpData.clock)).append(" ");
|
||||
}
|
||||
|
||||
if (fields.contains("status")) {
|
||||
string.append(deviceStatusPumpData.status).append(" ");
|
||||
}
|
||||
|
||||
if (fields.contains("device")) {
|
||||
string.append(getDevice()).append(" ");
|
||||
}
|
||||
|
||||
|
||||
string.append("</span>"); // color
|
||||
|
||||
return Html.fromHtml(string.toString());
|
||||
}
|
||||
|
||||
static class DeviceStatusPumpData {
|
||||
long clock = 0L;
|
||||
boolean isPercent = false;
|
||||
int percent = 0;
|
||||
double voltage = 0;
|
||||
|
||||
String status = "N/A";
|
||||
double reservoir = 0d;
|
||||
|
||||
Spanned extended = null;
|
||||
}
|
||||
|
||||
public void updatePumpData(JSONObject object) {
|
||||
try {
|
||||
JSONObject pump = data != null && data.has("pump") ? data.getJSONObject("pump") : new JSONObject();
|
||||
|
||||
long clock = 0L;
|
||||
if (pump.has("clock"))
|
||||
clock = DateUtil.fromISODateString(pump.getString("clock")).getTime();
|
||||
// check if this is new data
|
||||
if (clock == 0 || deviceStatusPumpData != null && clock < deviceStatusPumpData.clock)
|
||||
return;
|
||||
// create new status and process data
|
||||
deviceStatusPumpData = new DeviceStatusPumpData();
|
||||
deviceStatusPumpData.clock = clock;
|
||||
if (pump.has("status") && pump.getJSONObject("status").has("status"))
|
||||
deviceStatusPumpData.status = pump.getJSONObject("status").getString("status");
|
||||
if (pump.has("reservoir"))
|
||||
deviceStatusPumpData.reservoir = pump.getDouble("reservoir");
|
||||
if (pump.has("battery") && pump.getJSONObject("battery").has("percent")) {
|
||||
deviceStatusPumpData.isPercent = true;
|
||||
deviceStatusPumpData.percent = pump.getJSONObject("battery").getInt("percent");
|
||||
} else if (pump.has("battery") && pump.getJSONObject("battery").has("voltage")) {
|
||||
deviceStatusPumpData.isPercent = false;
|
||||
deviceStatusPumpData.voltage = pump.getJSONObject("battery").getDouble("voltage");
|
||||
}
|
||||
if (pump.has("extended")) {
|
||||
JSONObject extendedJson = pump.getJSONObject("extended");
|
||||
StringBuilder exteneded = new StringBuilder();
|
||||
Iterator<?> keys = extendedJson.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = (String) keys.next();
|
||||
String value = extendedJson.getString(key);
|
||||
exteneded.append("<b>").append(key).append(":</b> ").append(value).append("<br>");
|
||||
}
|
||||
deviceStatusPumpData.extended = Html.fromHtml(exteneded.toString());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ********* OpenAPS data ***********
|
||||
|
||||
static DeviceStatusOpenAPSData deviceStatusOpenAPSData = new DeviceStatusOpenAPSData();
|
||||
|
||||
static class DeviceStatusOpenAPSData {
|
||||
long clockSuggested = 0L;
|
||||
long clockEnacted = 0L;
|
||||
|
||||
JSONObject suggested = null;
|
||||
JSONObject enacted = null;
|
||||
}
|
||||
|
||||
public void updateOpenApsData(JSONObject object) {
|
||||
try {
|
||||
JSONObject openaps = object.has("openaps") ? object.getJSONObject("openaps") : new JSONObject();
|
||||
JSONObject suggested = openaps.has("suggested") ? openaps.getJSONObject("suggested") : new JSONObject();
|
||||
JSONObject enacted = openaps.has("enacted") ? openaps.getJSONObject("enacted") : new JSONObject();
|
||||
|
||||
long clock = 0L;
|
||||
if (suggested.has("timestamp"))
|
||||
clock = DateUtil.fromISODateString(suggested.getString("timestamp")).getTime();
|
||||
// check if this is new data
|
||||
if (clock != 0 && clock > deviceStatusOpenAPSData.clockSuggested) {
|
||||
deviceStatusOpenAPSData.suggested = suggested;
|
||||
deviceStatusOpenAPSData.clockSuggested = clock;
|
||||
}
|
||||
|
||||
clock = 0L;
|
||||
if (enacted.has("timestamp"))
|
||||
clock = DateUtil.fromISODateString(enacted.getString("timestamp")).getTime();
|
||||
// check if this is new data
|
||||
if (clock != 0 && clock > deviceStatusOpenAPSData.clockEnacted) {
|
||||
deviceStatusOpenAPSData.enacted = enacted;
|
||||
deviceStatusOpenAPSData.clockEnacted = clock;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public Spanned getOpenApsStatus() {
|
||||
StringBuilder string = new StringBuilder();
|
||||
// test warning level
|
||||
int level = Levels.INFO;
|
||||
long now = System.currentTimeMillis();
|
||||
if (deviceStatusOpenAPSData.clockSuggested != 0 && deviceStatusOpenAPSData.clockSuggested + SP.getInt(R.string.key_nsalarm_urgent_staledatavalue, 16) * 60 * 1000L < now)
|
||||
level = Levels.URGENT;
|
||||
else if (deviceStatusOpenAPSData.clockSuggested != 0 && deviceStatusOpenAPSData.clockSuggested + SP.getInt(R.string.key_nsalarm_staledatavalue, 16) * 60 * 1000L < now)
|
||||
level = Levels.WARN;
|
||||
|
||||
string.append("<span style=\"color:");
|
||||
if (level == Levels.INFO) string.append("white\">");
|
||||
if (level == Levels.WARN) string.append("yellow\">");
|
||||
if (level == Levels.URGENT) string.append("red\">");
|
||||
|
||||
if (deviceStatusOpenAPSData.clockSuggested != 0) {
|
||||
string.append(DateUtil.minAgo(deviceStatusOpenAPSData.clockSuggested)).append(" ");
|
||||
}
|
||||
string.append("</span>"); // color
|
||||
|
||||
return Html.fromHtml(string.toString());
|
||||
}
|
||||
|
||||
public Spanned getExtendedOpenApsStatus() {
|
||||
StringBuilder string = new StringBuilder();
|
||||
|
||||
try {
|
||||
if (deviceStatusOpenAPSData.enacted != null && deviceStatusOpenAPSData.clockEnacted != deviceStatusOpenAPSData.clockSuggested)
|
||||
string.append("<b>").append(DateUtil.minAgo(deviceStatusOpenAPSData.clockEnacted)).append("</b> ").append(deviceStatusOpenAPSData.enacted.getString("reason")).append("<br>");
|
||||
if (deviceStatusOpenAPSData.suggested != null)
|
||||
string.append("<b>").append(DateUtil.minAgo(deviceStatusOpenAPSData.clockSuggested)).append("</b> ").append(deviceStatusOpenAPSData.suggested.getString("reason")).append("<br>");
|
||||
return Html.fromHtml(string.toString());
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return Html.fromHtml("");
|
||||
}
|
||||
|
||||
// ********* Uploader data ***********
|
||||
|
||||
public static HashMap<String, Uploader> uploaders = new HashMap<>();
|
||||
|
||||
static class Uploader {
|
||||
long clock = 0L;
|
||||
int battery = 0;
|
||||
}
|
||||
|
||||
public void updateUploaderData(JSONObject object) {
|
||||
try {
|
||||
|
||||
long clock = 0L;
|
||||
if (object.has("created_at"))
|
||||
clock = DateUtil.fromISODateString(object.getString("created_at")).getTime();
|
||||
String device = getDevice();
|
||||
Integer battery = null;
|
||||
if (object.has("uploaderBattery"))
|
||||
battery = object.getInt("uploaderBattery");
|
||||
else if (object.has("uploader")) {
|
||||
if (object.getJSONObject("uploader").has("battery"))
|
||||
battery = object.getJSONObject("uploader").getInt("battery");
|
||||
}
|
||||
Uploader uploader = uploaders.get(device);
|
||||
// check if this is new data
|
||||
if (clock != 0 && (uploader != null && clock > uploader.clock || uploader == null)) {
|
||||
if (uploader == null)
|
||||
uploader = new Uploader();
|
||||
uploader.battery = battery;
|
||||
uploader.clock = clock;
|
||||
uploaders.put(device, uploader);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public String getUploaderStatus() {
|
||||
Iterator iter = uploaders.entrySet().iterator();
|
||||
int minBattery = 100;
|
||||
while(iter.hasNext()) {
|
||||
Map.Entry pair = (Map.Entry) iter.next();
|
||||
Uploader uploader = (Uploader) pair.getValue();
|
||||
if (minBattery > uploader.battery)
|
||||
minBattery = uploader.battery;
|
||||
}
|
||||
|
||||
return minBattery + "%";
|
||||
}
|
||||
|
||||
public Spanned getExtendedUploaderStatus() {
|
||||
StringBuilder string = new StringBuilder();
|
||||
|
||||
Iterator iter = uploaders.entrySet().iterator();
|
||||
while(iter.hasNext()) {
|
||||
Map.Entry pair = (Map.Entry) iter.next();
|
||||
Uploader uploader = (Uploader) pair.getValue();
|
||||
String device = (String) pair.getKey();
|
||||
string.append("<b>").append(device).append(":</b> ").append(uploader.battery).append("%<br>");
|
||||
}
|
||||
|
||||
return Html.fromHtml(string.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,343 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.data;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/*
|
||||
{
|
||||
"status": "ok",
|
||||
"name": "Nightscout",
|
||||
"version": "0.10.0-dev-20170423",
|
||||
"versionNum": 1000,
|
||||
"serverTime": "2017-06-12T07:46:56.006Z",
|
||||
"apiEnabled": true,
|
||||
"careportalEnabled": true,
|
||||
"boluscalcEnabled": true,
|
||||
"head": "96ee154",
|
||||
"settings": {
|
||||
"units": "mmol",
|
||||
"timeFormat": 24,
|
||||
"nightMode": false,
|
||||
"editMode": true,
|
||||
"showRawbg": "always",
|
||||
"customTitle": "Bara's CGM",
|
||||
"theme": "colors",
|
||||
"alarmUrgentHigh": true,
|
||||
"alarmUrgentHighMins": [30, 60, 90, 120],
|
||||
"alarmHigh": true,
|
||||
"alarmHighMins": [30, 60, 90, 120],
|
||||
"alarmLow": true,
|
||||
"alarmLowMins": [15, 30, 45, 60],
|
||||
"alarmUrgentLow": true,
|
||||
"alarmUrgentLowMins": [15, 30, 45],
|
||||
"alarmUrgentMins": [30, 60, 90, 120],
|
||||
"alarmWarnMins": [30, 60, 90, 120],
|
||||
"alarmTimeagoWarn": true,
|
||||
"alarmTimeagoWarnMins": 15,
|
||||
"alarmTimeagoUrgent": true,
|
||||
"alarmTimeagoUrgentMins": 30,
|
||||
"language": "cs",
|
||||
"scaleY": "linear",
|
||||
"showPlugins": "careportal boluscalc food bwp cage sage iage iob cob basal ar2 delta direction upbat rawbg",
|
||||
"showForecast": "ar2",
|
||||
"focusHours": 3,
|
||||
"heartbeat": 60,
|
||||
"baseURL": "http:\/\/barascgm.sysop.cz:82",
|
||||
"authDefaultRoles": "readable",
|
||||
"thresholds": {
|
||||
"bgHigh": 252,
|
||||
"bgTargetTop": 180,
|
||||
"bgTargetBottom": 72,
|
||||
"bgLow": 71
|
||||
},
|
||||
"DEFAULT_FEATURES": ["bgnow", "delta", "direction", "timeago", "devicestatus", "upbat", "errorcodes", "profile"],
|
||||
"alarmTypes": ["predict"],
|
||||
"enable": ["careportal", "boluscalc", "food", "bwp", "cage", "sage", "iage", "iob", "cob", "basal", "ar2", "rawbg", "pushover", "bgi", "pump", "openaps", "pushover", "treatmentnotify", "bgnow", "delta", "direction", "timeago", "devicestatus", "upbat", "profile", "ar2"]
|
||||
},
|
||||
"extendedSettings": {
|
||||
"pump": {
|
||||
"fields": "reservoir battery clock",
|
||||
"urgentBattP": 26,
|
||||
"warnBattP": 51
|
||||
},
|
||||
"openaps": {
|
||||
"enableAlerts": true
|
||||
},
|
||||
"cage": {
|
||||
"alerts": true,
|
||||
"display": "days",
|
||||
"urgent": 96,
|
||||
"warn": 72
|
||||
},
|
||||
"sage": {
|
||||
"alerts": true,
|
||||
"urgent": 336,
|
||||
"warn": 168
|
||||
},
|
||||
"iage": {
|
||||
"alerts": true,
|
||||
"urgent": 150,
|
||||
"warn": 120
|
||||
},
|
||||
"basal": {
|
||||
"render": "default"
|
||||
},
|
||||
"profile": {
|
||||
"history": true,
|
||||
"multiple": true
|
||||
},
|
||||
"devicestatus": {
|
||||
"advanced": true
|
||||
}
|
||||
},
|
||||
"activeProfile": "2016 +30%"
|
||||
}
|
||||
*/
|
||||
public class NSSettingsStatus {
|
||||
private static NSSettingsStatus instance = null;
|
||||
|
||||
public static NSSettingsStatus getInstance() {
|
||||
if (instance == null)
|
||||
instance = new NSSettingsStatus();
|
||||
return instance;
|
||||
}
|
||||
|
||||
private JSONObject data = null;
|
||||
|
||||
public NSSettingsStatus() {
|
||||
}
|
||||
|
||||
public NSSettingsStatus setData(JSONObject obj) {
|
||||
this.data = obj;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return getStringOrNull("name");
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return getStringOrNull("version");
|
||||
}
|
||||
|
||||
public Integer getVersionNum() {
|
||||
return getIntegerOrNull("versionNum");
|
||||
}
|
||||
|
||||
public Date getServerTime() {
|
||||
return getDateOrNull("versionNum");
|
||||
}
|
||||
|
||||
public boolean getApiEnabled() {
|
||||
return getBooleanOrNull("apiEnabled");
|
||||
}
|
||||
|
||||
public boolean getCareportalEnabled() {
|
||||
return getBooleanOrNull("careportalEnabled");
|
||||
}
|
||||
|
||||
public boolean getBoluscalcEnabled() {
|
||||
return getBooleanOrNull("boluscalcEnabled");
|
||||
}
|
||||
|
||||
public String getHead() {
|
||||
return getStringOrNull("head");
|
||||
}
|
||||
|
||||
public String getSettings() {
|
||||
return getStringOrNull("settings");
|
||||
}
|
||||
|
||||
public JSONObject getExtendedSettings() {
|
||||
try {
|
||||
String extended = getStringOrNull("extendedSettings");
|
||||
if (extended != null)
|
||||
return new JSONObject(extended);
|
||||
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public String getActiveProfile() {
|
||||
return getStringOrNull("activeProfile");
|
||||
}
|
||||
|
||||
// "bgHigh": 252,
|
||||
// "bgTargetTop": 180,
|
||||
// "bgTargetBottom": 72,
|
||||
// "bgLow": 71
|
||||
@Nullable
|
||||
public Double getThreshold(String what) {
|
||||
try {
|
||||
if (data == null)
|
||||
return null;
|
||||
String settings = getSettings();
|
||||
if (settings != null) {
|
||||
JSONObject settingsO = new JSONObject(settings);
|
||||
if (settingsO.has("thresholds")) {
|
||||
JSONObject tObject = settingsO.getJSONObject("thresholds");
|
||||
if (tObject.has(what)) {
|
||||
Double result = tObject.getDouble(what);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getStringOrNull(String key) {
|
||||
String ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getString(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private Integer getIntegerOrNull(String key) {
|
||||
Integer ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getInt(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private Long getLongOrNull(String key) {
|
||||
Long ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getLong(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private Date getDateOrNull(String key) {
|
||||
Date ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = new Date(data.getString(key));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private boolean getBooleanOrNull(String key) {
|
||||
boolean ret = false;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getBoolean(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// ***** PUMP STATUS ******
|
||||
|
||||
public JSONObject getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
/*
|
||||
, warnClock: sbx.extendedSettings.warnClock || 30
|
||||
, urgentClock: sbx.extendedSettings.urgentClock || 60
|
||||
, warnRes: sbx.extendedSettings.warnRes || 10
|
||||
, urgentRes: sbx.extendedSettings.urgentRes || 5
|
||||
, warnBattV: sbx.extendedSettings.warnBattV || 1.35
|
||||
, urgentBattV: sbx.extendedSettings.urgentBattV || 1.3
|
||||
, warnBattP: sbx.extendedSettings.warnBattP || 30
|
||||
, urgentBattP: sbx.extendedSettings.urgentBattP || 20
|
||||
, enableAlerts: sbx.extendedSettings.enableAlerts || false
|
||||
|
||||
*/
|
||||
|
||||
public double extendedPumpSettings(String setting) {
|
||||
try {
|
||||
JSONObject pump = extentendedPumpSettings();
|
||||
switch (setting) {
|
||||
case "warnClock":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "urgentClock":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "warnRes":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "urgentRes":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "warnBattV":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "urgentBattV":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "warnBattP":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
case "urgentBattP":
|
||||
return pump != null && pump.has(setting) ? pump.getDouble(setting) : 30;
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0d;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public JSONObject extentendedPumpSettings() {
|
||||
try {
|
||||
JSONObject extended = getExtendedSettings();
|
||||
if (extended.has("pump")) {
|
||||
JSONObject pump = extended.getJSONObject("pump");
|
||||
return pump;
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean pumpExtentendedSettingsEnabledAlerts() {
|
||||
try {
|
||||
JSONObject pump = extentendedPumpSettings();
|
||||
if (pump != null && pump.has("enableAlerts")) {
|
||||
return pump.getBoolean("enableAlerts");
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String pumpExtentendedSettingsFields() {
|
||||
try {
|
||||
JSONObject pump = extentendedPumpSettings();
|
||||
if (pump != null && pump.has("fields")) {
|
||||
return pump.getString("fields");
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -24,7 +24,7 @@ public class NSSgv {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
private Integer getIntegerOrNull(String key) {
|
||||
Integer ret = null;
|
||||
|
@ -36,7 +36,7 @@ public class NSSgv {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
private Long getLongOrNull(String key) {
|
||||
Long ret = null;
|
||||
|
@ -48,7 +48,7 @@ public class NSSgv {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
public JSONObject getData () { return data; }
|
||||
public Integer getMgdl () { return getIntegerOrNull("mgdl"); }
|
||||
|
|
|
@ -1,105 +0,0 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.data;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
{
|
||||
status: 'ok'
|
||||
, name: env.name
|
||||
, version: env.version
|
||||
, versionNum: versionNum (for ver 1.2.3 contains 10203)
|
||||
, serverTime: new Date().toISOString()
|
||||
, apiEnabled: apiEnabled
|
||||
, careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1
|
||||
, boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1
|
||||
, head: env.head
|
||||
, settings: env.settings
|
||||
, extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {}
|
||||
, activeProfile ..... calculated from treatments or missing
|
||||
}
|
||||
*/
|
||||
public class NSStatus {
|
||||
private JSONObject data;
|
||||
|
||||
public NSStatus(JSONObject obj) {
|
||||
this.data = obj;
|
||||
}
|
||||
|
||||
public String getName () { return getStringOrNull("name"); }
|
||||
public String getVersion () { return getStringOrNull("version"); }
|
||||
public Integer getVersionNum () { return getIntegerOrNull("versionNum"); }
|
||||
public Date getServerTime () { return getDateOrNull("versionNum"); }
|
||||
public boolean getApiEnabled () { return getBooleanOrNull("apiEnabled"); }
|
||||
public boolean getCareportalEnabled () { return getBooleanOrNull("careportalEnabled"); }
|
||||
public boolean getBoluscalcEnabled () { return getBooleanOrNull("boluscalcEnabled"); }
|
||||
public String getHead () { return getStringOrNull("head"); }
|
||||
public String getSettings () { return getStringOrNull("settings"); }
|
||||
public String getExtendedSettings () { return getStringOrNull("extendedSettings"); }
|
||||
public String getActiveProfile () { return getStringOrNull("activeProfile"); }
|
||||
|
||||
private String getStringOrNull(String key) {
|
||||
String ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getString(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
private Integer getIntegerOrNull(String key) {
|
||||
Integer ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getInt(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
private Long getLongOrNull(String key) {
|
||||
Long ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getLong(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
private Date getDateOrNull(String key) {
|
||||
Date ret = null;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = new Date(data.getString(key));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
private boolean getBooleanOrNull(String key) {
|
||||
boolean ret = false;
|
||||
if (data.has(key)) {
|
||||
try {
|
||||
ret = data.getBoolean(key);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
public JSONObject getData () { return data; }
|
||||
|
||||
}
|
|
@ -25,7 +25,7 @@ public class NSTreatment {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
private Double getDoubleOrNull(String key) {
|
||||
Double ret = null;
|
||||
|
@ -37,7 +37,7 @@ public class NSTreatment {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
private Integer getIntegerOrNull(String key) {
|
||||
Integer ret = null;
|
||||
|
@ -49,7 +49,7 @@ public class NSTreatment {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
private Long getLongOrNull(String key) {
|
||||
Long ret = null;
|
||||
|
@ -61,7 +61,7 @@ public class NSTreatment {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
private Date getDateOrNull(String key) {
|
||||
Date ret = null;
|
||||
|
@ -73,7 +73,7 @@ public class NSTreatment {
|
|||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
|
||||
public String getAction() { return action; }
|
||||
public JSONObject getData() { return data; }
|
||||
|
|
|
@ -22,9 +22,16 @@ public class EventNSClientNewLog {
|
|||
this.logText = logText;
|
||||
}
|
||||
|
||||
public Spanned toHtml() {
|
||||
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
|
||||
Spanned line = Html.fromHtml(timeFormat.format(date) + " <b>" + action + "</b> " + logText + "<br>");
|
||||
return line;
|
||||
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
|
||||
|
||||
public StringBuilder toPreparedHtml() {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.append(timeFormat.format(date));
|
||||
stringBuilder.append(" <b>");
|
||||
stringBuilder.append(action);
|
||||
stringBuilder.append("</b> ");
|
||||
stringBuilder.append(logText);
|
||||
stringBuilder.append("<br>");
|
||||
return stringBuilder;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
package info.nightscout.androidaps.plugins.NSClientInternal.receivers;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.PowerManager;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.db.DbRequest;
|
||||
import info.nightscout.androidaps.interfaces.PluginBase;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
public class AckAlarmReceiver extends BroadcastReceiver {
|
||||
private static Logger log = LoggerFactory.getLogger(AckAlarmReceiver.class);
|
||||
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
|
||||
AckAlarmReceiver.class.getSimpleName());
|
||||
NSClientInternalPlugin nsClientInternalPlugin = (NSClientInternalPlugin) MainApp.getSpecificPlugin(NSClientInternalPlugin.class);
|
||||
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();
|
||||
if (bundles == null) return;
|
||||
if (!bundles.containsKey("level")) return;
|
||||
if (!bundles.containsKey("group")) return;
|
||||
if (!bundles.containsKey("silenceTime")) return;
|
||||
|
||||
AlarmAck ack = new AlarmAck();
|
||||
ack.level = bundles.getInt("level");
|
||||
ack.group = bundles.getString("group");
|
||||
ack.silenceTime = bundles.getLong("silenceTime");
|
||||
|
||||
NSClientService nsClientService = nsClientInternalPlugin.nsClientService;
|
||||
if (nsClientService != null)
|
||||
nsClientService.sendAlarmAck(ack);
|
||||
|
||||
} finally {
|
||||
wakeLock.release();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -19,6 +19,8 @@ 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.androidaps.plugins.NSClientInternal.data.AlarmAck;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
public class DBAccessReceiver extends BroadcastReceiver {
|
||||
|
@ -29,7 +31,7 @@ public class DBAccessReceiver extends BroadcastReceiver {
|
|||
public void onReceive(Context context, Intent intent) {
|
||||
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
|
||||
"sendQueue");
|
||||
DBAccessReceiver.class.getSimpleName());
|
||||
NSClientInternalPlugin nsClientInternalPlugin = (NSClientInternalPlugin) MainApp.getSpecificPlugin(NSClientInternalPlugin.class);
|
||||
if (!nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) {
|
||||
return;
|
||||
|
@ -61,7 +63,7 @@ public class DBAccessReceiver extends BroadcastReceiver {
|
|||
data = new JSONObject();
|
||||
}
|
||||
// mark by id
|
||||
Long nsclientid = new Date().getTime();
|
||||
Long nsclientid = System.currentTimeMillis();
|
||||
try {
|
||||
data.put("NSCLIENT_ID", nsclientid);
|
||||
} catch (JSONException e) {
|
||||
|
|
|
@ -38,16 +38,20 @@ 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.NSUpdateAck;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAlarm;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAnnouncement;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastCals;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastClearAlarm;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastDeviceStatus;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastMbgs;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastProfile;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastSgvs;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastStatus;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSCal;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastUrgentAlarm;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
|
||||
|
@ -152,6 +156,7 @@ public class NSClientService extends Service {
|
|||
ev.isChanged(R.string.key_nsclientinternal_api_secret) ||
|
||||
ev.isChanged(R.string.key_nsclientinternal_paused)
|
||||
) {
|
||||
latestDateInReceivedData = 0;
|
||||
destroy();
|
||||
initialize();
|
||||
}
|
||||
|
@ -160,6 +165,7 @@ public class NSClientService extends Service {
|
|||
@Subscribe
|
||||
public void onStatusEvent(EventConfigBuilderChange ev) {
|
||||
if (nsEnabled != MainApp.getSpecificPlugin(NSClientInternalPlugin.class).isEnabled(PluginBase.GENERAL)) {
|
||||
latestDateInReceivedData = 0;
|
||||
destroy();
|
||||
initialize();
|
||||
}
|
||||
|
@ -201,6 +207,10 @@ public class NSClientService extends Service {
|
|||
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect"));
|
||||
mSocket.connect();
|
||||
mSocket.on("dataUpdate", onDataUpdate);
|
||||
mSocket.on("announcement", onAnnouncement);
|
||||
mSocket.on("alarm", onAlarm);
|
||||
mSocket.on("urgent_alarm", onUrgentAlarm);
|
||||
mSocket.on("clear_alarm", onClearAlarm);
|
||||
} catch (URISyntaxException | RuntimeException e) {
|
||||
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax"));
|
||||
MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax"));
|
||||
|
@ -297,6 +307,99 @@ public class NSClientService extends Service {
|
|||
}
|
||||
};
|
||||
|
||||
private Emitter.Listener onAnnouncement = new Emitter.Listener() {
|
||||
/*
|
||||
{
|
||||
"level":0,
|
||||
"title":"Announcement",
|
||||
"message":"test",
|
||||
"plugin":{"name":"treatmentnotify","label":"Treatment Notifications","pluginType":"notification","enabled":true},
|
||||
"group":"Announcement",
|
||||
"isAnnouncement":true,
|
||||
"key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da"
|
||||
}
|
||||
*/
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
JSONObject data = (JSONObject) args[0];
|
||||
if (Config.detailedLog)
|
||||
try {
|
||||
MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", data.has("message") ? data.getString("message") : "received"));
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
BroadcastAnnouncement.handleAnnouncement(data, getApplicationContext());
|
||||
log.debug(data.toString());
|
||||
}
|
||||
};
|
||||
|
||||
private Emitter.Listener onAlarm = new Emitter.Listener() {
|
||||
/*
|
||||
{
|
||||
"level":1,
|
||||
"title":"Warning HIGH",
|
||||
"message":"BG Now: 5 -0.2 → mmol\/L\nRaw BG: 4.8 mmol\/L Čistý\nBG 15m: 4.8 mmol\/L\nIOB: -0.02U\nCOB: 0g",
|
||||
"eventName":"high",
|
||||
"plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true},
|
||||
"pushoverSound":"climb",
|
||||
"debug":{"lastSGV":5,"thresholds":{"bgHigh":180,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}},
|
||||
"group":"default",
|
||||
"key":"simplealarms_1"
|
||||
}
|
||||
*/
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
if (Config.detailedLog)
|
||||
MainApp.bus().post(new EventNSClientNewLog("ALARM", "received"));
|
||||
JSONObject data = (JSONObject) args[0];
|
||||
BroadcastAlarm.handleAlarm(data, getApplicationContext());
|
||||
log.debug(data.toString());
|
||||
}
|
||||
};
|
||||
|
||||
private Emitter.Listener onUrgentAlarm = new Emitter.Listener() {
|
||||
/*
|
||||
{
|
||||
"level":2,
|
||||
"title":"Urgent HIGH",
|
||||
"message":"BG Now: 5.2 -0.1 → mmol\/L\nRaw BG: 5 mmol\/L Čistý\nBG 15m: 5 mmol\/L\nIOB: 0.00U\nCOB: 0g",
|
||||
"eventName":"high",
|
||||
"plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true},
|
||||
"pushoverSound":"persistent",
|
||||
"debug":{"lastSGV":5.2,"thresholds":{"bgHigh":80,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}},
|
||||
"group":"default",
|
||||
"key":"simplealarms_2"
|
||||
}
|
||||
*/
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
JSONObject data = (JSONObject) args[0];
|
||||
if (Config.detailedLog)
|
||||
MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received"));
|
||||
BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext());
|
||||
log.debug(data.toString());
|
||||
}
|
||||
};
|
||||
|
||||
private Emitter.Listener onClearAlarm = new Emitter.Listener() {
|
||||
/*
|
||||
{
|
||||
"clear":true,
|
||||
"title":"All Clear",
|
||||
"message":"default - Urgent was ack'd",
|
||||
"group":"default"
|
||||
}
|
||||
*/
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
if (Config.detailedLog)
|
||||
MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received"));
|
||||
JSONObject data = (JSONObject) args[0];
|
||||
BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext());
|
||||
log.debug(data.toString());
|
||||
}
|
||||
};
|
||||
|
||||
private Emitter.Listener onDataUpdate = new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
|
@ -329,19 +432,17 @@ public class NSClientService extends Service {
|
|||
|
||||
if (data.has("status")) {
|
||||
JSONObject status = data.getJSONObject("status");
|
||||
NSStatus nsStatus = new NSStatus(status);
|
||||
NSSettingsStatus nsSettingsStatus = NSSettingsStatus.getInstance().setData(status);
|
||||
|
||||
if (!status.has("versionNum")) {
|
||||
if (status.getInt("versionNum") < 900) {
|
||||
if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) {
|
||||
MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
|
||||
}
|
||||
} else {
|
||||
nightscoutVersionName = status.getString("version");
|
||||
nightscoutVersionCode = status.getInt("versionNum");
|
||||
nightscoutVersionName = nsSettingsStatus.getVersion();
|
||||
nightscoutVersionCode = nsSettingsStatus.getVersionNum();
|
||||
}
|
||||
|
||||
BroadcastStatus bs = new BroadcastStatus();
|
||||
bs.handleNewStatus(nsStatus, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastStatus.handleNewStatus(nsSettingsStatus, MainApp.instance().getApplicationContext(), isDelta);
|
||||
|
||||
/* Other received data to 2016/02/10
|
||||
{
|
||||
|
@ -365,17 +466,15 @@ public class NSClientService extends Service {
|
|||
|
||||
// If new profile received or change detected broadcast it
|
||||
if (broadcastProfile && profileStore != null) {
|
||||
BroadcastProfile bp = new BroadcastProfile();
|
||||
bp.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastProfile.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta);
|
||||
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting"));
|
||||
}
|
||||
|
||||
if (data.has("treatments")) {
|
||||
JSONArray treatments = (JSONArray) data.getJSONArray("treatments");
|
||||
JSONArray treatments = data.getJSONArray("treatments");
|
||||
JSONArray removedTreatments = new JSONArray();
|
||||
JSONArray updatedTreatments = new JSONArray();
|
||||
JSONArray addedTreatments = new JSONArray();
|
||||
BroadcastTreatment bt = new BroadcastTreatment();
|
||||
if (treatments.length() > 0)
|
||||
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments"));
|
||||
for (Integer index = 0; index < treatments.length(); index++) {
|
||||
|
@ -385,7 +484,7 @@ public class NSClientService extends Service {
|
|||
// remove from upload queue if Ack is failing
|
||||
UploadQueue.removeID(jsonTreatment);
|
||||
//Find latest date in treatment
|
||||
if (treatment.getMills() != null && treatment.getMills() < new Date().getTime())
|
||||
if (treatment.getMills() != null && treatment.getMills() < System.currentTimeMillis())
|
||||
if (treatment.getMills() > latestDateInReceivedData)
|
||||
latestDateInReceivedData = treatment.getMills();
|
||||
|
||||
|
@ -394,23 +493,22 @@ public class NSClientService extends Service {
|
|||
} else if (treatment.getAction().equals("update")) {
|
||||
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
|
||||
if (treatment.getMills() != null && treatment.getMills() > System.currentTimeMillis() - 24 * 60 * 60 * 1000L) // handle 1 day old deletions only
|
||||
removedTreatments.put(jsonTreatment);
|
||||
}
|
||||
}
|
||||
if (removedTreatments.length() > 0) {
|
||||
bt.handleRemovedTreatment(removedTreatments, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastTreatment.handleRemovedTreatment(removedTreatments, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
if (updatedTreatments.length() > 0) {
|
||||
bt.handleChangedTreatment(updatedTreatments, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastTreatment.handleChangedTreatment(updatedTreatments, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
if (addedTreatments.length() > 0) {
|
||||
bt.handleNewTreatment(addedTreatments, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastTreatment.handleNewTreatment(addedTreatments, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
}
|
||||
if (data.has("devicestatus")) {
|
||||
BroadcastDeviceStatus bds = new BroadcastDeviceStatus();
|
||||
JSONArray devicestatuses = (JSONArray) data.getJSONArray("devicestatus");
|
||||
JSONArray devicestatuses = data.getJSONArray("devicestatus");
|
||||
if (devicestatuses.length() > 0) {
|
||||
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses"));
|
||||
for (Integer index = 0; index < devicestatuses.length(); index++) {
|
||||
|
@ -418,13 +516,11 @@ public class NSClientService extends Service {
|
|||
// remove from upload queue if Ack is failing
|
||||
UploadQueue.removeID(jsonStatus);
|
||||
}
|
||||
// send only last record
|
||||
bds.handleNewDeviceStatus(devicestatuses.getJSONObject(devicestatuses.length() - 1), MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastDeviceStatus.handleNewDeviceStatus(devicestatuses, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
}
|
||||
if (data.has("mbgs")) {
|
||||
BroadcastMbgs bmbg = new BroadcastMbgs();
|
||||
JSONArray mbgs = (JSONArray) data.getJSONArray("mbgs");
|
||||
JSONArray mbgs = data.getJSONArray("mbgs");
|
||||
if (mbgs.length() > 0)
|
||||
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs"));
|
||||
for (Integer index = 0; index < mbgs.length(); index++) {
|
||||
|
@ -432,11 +528,10 @@ public class NSClientService extends Service {
|
|||
// remove from upload queue if Ack is failing
|
||||
UploadQueue.removeID(jsonMbg);
|
||||
}
|
||||
bmbg.handleNewMbg(mbgs, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastMbgs.handleNewMbg(mbgs, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
if (data.has("cals")) {
|
||||
BroadcastCals bc = new BroadcastCals();
|
||||
JSONArray cals = (JSONArray) data.getJSONArray("cals");
|
||||
JSONArray cals = data.getJSONArray("cals");
|
||||
if (cals.length() > 0)
|
||||
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals"));
|
||||
// Retreive actual calibration
|
||||
|
@ -444,11 +539,10 @@ public class NSClientService extends Service {
|
|||
// remove from upload queue if Ack is failing
|
||||
UploadQueue.removeID(cals.optJSONObject(index));
|
||||
}
|
||||
bc.handleNewCal(cals, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastCals.handleNewCal(cals, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
if (data.has("sgvs")) {
|
||||
BroadcastSgvs bs = new BroadcastSgvs();
|
||||
JSONArray sgvs = (JSONArray) data.getJSONArray("sgvs");
|
||||
JSONArray sgvs = data.getJSONArray("sgvs");
|
||||
if (sgvs.length() > 0)
|
||||
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
|
||||
for (Integer index = 0; index < sgvs.length(); index++) {
|
||||
|
@ -459,11 +553,11 @@ public class NSClientService extends Service {
|
|||
// remove from upload queue if Ack is failing
|
||||
UploadQueue.removeID(jsonSgv);
|
||||
//Find latest date in sgv
|
||||
if (sgv.getMills() != null && sgv.getMills() < new Date().getTime())
|
||||
if (sgv.getMills() != null && sgv.getMills() < System.currentTimeMillis())
|
||||
if (sgv.getMills() > latestDateInReceivedData)
|
||||
latestDateInReceivedData = sgv.getMills();
|
||||
}
|
||||
bs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta);
|
||||
BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta);
|
||||
}
|
||||
MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData)));
|
||||
} catch (JSONException e) {
|
||||
|
@ -543,6 +637,12 @@ public class NSClientService extends Service {
|
|||
}
|
||||
}
|
||||
|
||||
public void sendAlarmAck(AlarmAck alarmAck) {
|
||||
if (!isConnected || !hasWriteAuth) return;
|
||||
mSocket.emit("ack", alarmAck.level, alarmAck.group, alarmAck.silenceTime);
|
||||
MainApp.bus().post(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime));
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(NSAddAck ack) {
|
||||
if (ack.nsClientID != null) {
|
||||
|
@ -575,11 +675,11 @@ public class NSClientService extends Service {
|
|||
public void run() {
|
||||
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");
|
||||
if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) {
|
||||
log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec");
|
||||
return;
|
||||
}
|
||||
lastResendTime = new Date().getTime();
|
||||
lastResendTime = System.currentTimeMillis();
|
||||
|
||||
MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
|
||||
|
||||
|
|
|
@ -232,7 +232,7 @@ public class DetermineBasalAdapterAMAJS {
|
|||
mCurrentTemp.add("rate", MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory());
|
||||
|
||||
// as we have non default temps longer than 30 mintues
|
||||
TemporaryBasal tempBasal = MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime());
|
||||
TemporaryBasal tempBasal = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
|
||||
if (tempBasal != null) {
|
||||
mCurrentTemp.add("minutesrunning", tempBasal.getRealDuration());
|
||||
}
|
||||
|
|
|
@ -43,7 +43,7 @@ public class DetermineBasalResultAMA extends APSResult {
|
|||
}
|
||||
if (result.contains("duration")) {
|
||||
duration = result.getInteger("duration");
|
||||
changeRequested = changeRequested;
|
||||
//changeRequested as above
|
||||
} else {
|
||||
duration = -1;
|
||||
changeRequested = false;
|
||||
|
|
|
@ -20,11 +20,12 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
|
||||
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 {
|
||||
public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnClickListener {
|
||||
private static Logger log = LoggerFactory.getLogger(OpenAPSAMAFragment.class);
|
||||
|
||||
private static OpenAPSAMAPlugin openAPSAMAPlugin;
|
||||
|
@ -81,18 +82,6 @@ public class OpenAPSAMAFragment 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);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
|
||||
updateGUI();
|
||||
|
@ -103,7 +92,8 @@ public class OpenAPSAMAFragment extends Fragment implements View.OnClickListener
|
|||
updateResultGUI(ev.text);
|
||||
}
|
||||
|
||||
void updateGUI() {
|
||||
@Override
|
||||
protected void updateGUI() {
|
||||
Activity activity = getActivity();
|
||||
if (activity != null)
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
|
|
|
@ -135,6 +135,13 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
|
|||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
PumpInterface pump = MainApp.getConfigBuilder();
|
||||
|
||||
if (profile == null) {
|
||||
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.noprofileselected)));
|
||||
if (Config.logAPSResult)
|
||||
log.debug(MainApp.instance().getString(R.string.noprofileselected));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isEnabled(PluginBase.APS)) {
|
||||
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_disabled)));
|
||||
if (Config.logAPSResult)
|
||||
|
@ -151,22 +158,11 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
|
|||
|
||||
String units = profile.getUnits();
|
||||
|
||||
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
|
||||
Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL;
|
||||
Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL;
|
||||
if (!units.equals(Constants.MGDL)) {
|
||||
maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL;
|
||||
minBgDefault = Constants.MIN_BG_DEFAULT_MMOL;
|
||||
targetBgDefault = Constants.TARGET_BG_DEFAULT_MMOL;
|
||||
}
|
||||
|
||||
Date now = new Date();
|
||||
|
||||
double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
|
||||
double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
|
||||
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);
|
||||
double minBg = Profile.toMgdl(profile.getTargetLow(), units);
|
||||
double maxBg = Profile.toMgdl(profile.getTargetHigh(), units);
|
||||
double targetBg = (minBg + maxBg) / 2;
|
||||
|
||||
minBg = Round.roundTo(minBg, 0.1d);
|
||||
maxBg = Round.roundTo(maxBg, 0.1d);
|
||||
|
@ -187,7 +183,7 @@ 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;
|
||||
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
|
||||
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(System.currentTimeMillis());
|
||||
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]);
|
||||
|
@ -207,14 +203,9 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
|
|||
if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.1, 10)) return;
|
||||
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, 5)) return;
|
||||
|
||||
long oldestDataAvailable = MainApp.getConfigBuilder().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(getBGDataFrom, null);
|
||||
lastAutosensResult = IobCobCalculatorPlugin.detectSensitivity(getBGDataFrom);
|
||||
lastAutosensResult = IobCobCalculatorPlugin.detectSensitivityWithLock(IobCobCalculatorPlugin.oldestDataAvailable(), System.currentTimeMillis());
|
||||
} else {
|
||||
lastAutosensResult = new AutosensResult();
|
||||
}
|
||||
|
@ -246,6 +237,8 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
|
|||
|
||||
determineBasalAdapterAMAJS.release();
|
||||
|
||||
Date now = new Date();
|
||||
|
||||
try {
|
||||
determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));
|
||||
} catch (JSONException e) {
|
||||
|
|
|
@ -41,7 +41,7 @@ public class DetermineBasalResultMA extends APSResult {
|
|||
}
|
||||
if (result.contains("duration")) {
|
||||
duration = result.getInteger("duration");
|
||||
changeRequested = changeRequested;
|
||||
//changeRequested as above
|
||||
} else {
|
||||
duration = -1;
|
||||
changeRequested = false;
|
||||
|
|
|
@ -18,11 +18,12 @@ import org.slf4j.LoggerFactory;
|
|||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
|
||||
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 {
|
||||
public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener {
|
||||
private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class);
|
||||
|
||||
private static OpenAPSMAPlugin openAPSMAPlugin;
|
||||
|
@ -75,18 +76,6 @@ public class OpenAPSMAFragment 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);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
|
||||
updateGUI();
|
||||
|
@ -97,7 +86,8 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener
|
|||
updateResultGUI(ev.text);
|
||||
}
|
||||
|
||||
void updateGUI() {
|
||||
@Override
|
||||
protected void updateGUI() {
|
||||
Activity activity = getActivity();
|
||||
if (activity != null)
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
|
@ -123,7 +113,7 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener
|
|||
});
|
||||
}
|
||||
|
||||
void updateResultGUI(final String text) {
|
||||
private void updateResultGUI(final String text) {
|
||||
Activity activity = getActivity();
|
||||
if (activity != null)
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
|
|
|
@ -133,6 +133,13 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
|
|||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
PumpInterface pump = MainApp.getConfigBuilder();
|
||||
|
||||
if (profile == null) {
|
||||
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.noprofileselected)));
|
||||
if (Config.logAPSResult)
|
||||
log.debug(MainApp.instance().getString(R.string.noprofileselected));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isEnabled(PluginBase.APS)) {
|
||||
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_disabled)));
|
||||
if (Config.logAPSResult)
|
||||
|
@ -149,22 +156,13 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
|
|||
|
||||
String units = profile.getUnits();
|
||||
|
||||
Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
|
||||
Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL;
|
||||
Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL;
|
||||
if (!units.equals(Constants.MGDL)) {
|
||||
maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL;
|
||||
minBgDefault = Constants.MIN_BG_DEFAULT_MMOL;
|
||||
targetBgDefault = Constants.TARGET_BG_DEFAULT_MMOL;
|
||||
}
|
||||
|
||||
Date now = new Date();
|
||||
|
||||
double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
|
||||
double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
|
||||
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);
|
||||
double minBg = Profile.toMgdl(profile.getTargetLow(), units);
|
||||
double maxBg = Profile.toMgdl(profile.getTargetHigh(), units);
|
||||
double targetBg = (minBg + maxBg) / 2;
|
||||
|
||||
minBg = Round.roundTo(minBg, 0.1d);
|
||||
maxBg = Round.roundTo(maxBg, 0.1d);
|
||||
|
@ -186,7 +184,7 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
|
|||
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]);
|
||||
|
||||
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(new Date().getTime());
|
||||
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory(System.currentTimeMillis());
|
||||
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]);
|
||||
|
|
|
@ -9,7 +9,6 @@ import android.view.View;
|
|||
import android.view.ViewGroup;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.crashlytics.android.answers.Answers;
|
||||
|
@ -25,17 +24,15 @@ import info.nightscout.androidaps.MainApp;
|
|||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.data.GlucoseStatus;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.utils.PlusMinusEditText;
|
||||
import info.nightscout.utils.NumberPicker;
|
||||
import info.nightscout.utils.SafeParse;
|
||||
import info.nightscout.utils.XdripCalibrations;
|
||||
|
||||
public class CalibrationDialog extends DialogFragment implements View.OnClickListener {
|
||||
private static Logger log = LoggerFactory.getLogger(CalibrationDialog.class);
|
||||
|
||||
Button okButton;
|
||||
PlusMinusEditText bgText;
|
||||
NumberPicker bgNumber;
|
||||
TextView unitsView;
|
||||
TextView bgView;
|
||||
|
||||
Context context;
|
||||
|
||||
|
@ -49,6 +46,12 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
|
|||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetach() {
|
||||
super.onDetach();
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
|
@ -57,24 +60,21 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
|
|||
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
|
||||
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
|
||||
|
||||
okButton = (Button) view.findViewById(R.id.overview_calibration_okbutton);
|
||||
okButton.setOnClickListener(this);
|
||||
view.findViewById(R.id.ok).setOnClickListener(this);
|
||||
view.findViewById(R.id.cancel).setOnClickListener(this);
|
||||
|
||||
Profile profile = MainApp.getConfigBuilder().getProfile();
|
||||
Double bg = profile != null ? Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()) : 0d;
|
||||
String units = MainApp.getConfigBuilder().getProfileUnits();
|
||||
Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, units);
|
||||
|
||||
String units = Constants.MGDL;
|
||||
if (profile != null)
|
||||
units = profile.getUnits();
|
||||
bgNumber = (NumberPicker) view.findViewById(R.id.overview_calibration_bg);
|
||||
|
||||
if (units.equals(Constants.MMOL))
|
||||
bgText = new PlusMinusEditText(view, R.id.overview_calibration_bg, R.id.overview_calibration_bg_plus, R.id.overview_calibration_bg_minus, bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
bgNumber.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
else
|
||||
bgText = new PlusMinusEditText(view, R.id.overview_calibration_bg, R.id.overview_calibration_bg_plus, R.id.overview_calibration_bg_minus, bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
|
||||
bgNumber.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
|
||||
|
||||
unitsView = (TextView) view.findViewById(R.id.overview_calibration_units);
|
||||
unitsView.setText(units);
|
||||
bgView = (TextView) view.findViewById(R.id.overview_calibration_bg);
|
||||
|
||||
return view;
|
||||
}
|
||||
|
@ -82,13 +82,15 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
|
|||
@Override
|
||||
public void onClick(View view) {
|
||||
switch (view.getId()) {
|
||||
case R.id.overview_calibration_okbutton:
|
||||
final Double bg = SafeParse.stringToDouble(this.bgView.getText().toString());
|
||||
;
|
||||
case R.id.ok:
|
||||
final Double bg = SafeParse.stringToDouble(bgNumber.getText());
|
||||
XdripCalibrations.confirmAndSendCalibration(bg, context);
|
||||
dismiss();
|
||||
Answers.getInstance().logCustom(new CustomEvent("Calibration"));
|
||||
break;
|
||||
case R.id.cancel:
|
||||
dismiss();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,13 +29,14 @@ 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.NumberPicker;
|
||||
import info.nightscout.utils.PlusMinusEditText;
|
||||
import info.nightscout.utils.SafeParse;
|
||||
|
||||
public class NewTreatmentDialog extends DialogFragment implements OnClickListener {
|
||||
|
||||
PlusMinusEditText editCarbs;
|
||||
PlusMinusEditText editInsulin;
|
||||
NumberPicker editCarbs;
|
||||
NumberPicker editInsulin;
|
||||
|
||||
Handler mHandler;
|
||||
public static HandlerThread mHandlerThread;
|
||||
|
@ -49,7 +50,7 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
|
|||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container,
|
||||
Bundle savedInstanceState) {
|
||||
View view = inflater.inflate(R.layout.overview_newtreatment_dialog, null, false);
|
||||
View view = inflater.inflate(R.layout.overview_newtreatment_dialog, container, false);
|
||||
|
||||
view.findViewById(R.id.ok).setOnClickListener(this);
|
||||
view.findViewById(R.id.cancel).setOnClickListener(this);
|
||||
|
@ -60,19 +61,15 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
|
|||
Integer maxCarbs = MainApp.getConfigBuilder().applyCarbsConstraints(Constants.carbsOnlyForCheckLimit);
|
||||
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
|
||||
|
||||
editCarbs = new PlusMinusEditText(view, R.id.treatments_newtreatment_carbsamount, R.id.treatments_newtreatment_carbsamount_plus, R.id.treatments_newtreatment_carbsamount_minus, 0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false);
|
||||
editInsulin = new PlusMinusEditText(view, R.id.treatments_newtreatment_insulinamount, R.id.treatments_newtreatment_insulinamount_plus, R.id.treatments_newtreatment_insulinamount_minus, 0d, 0d, maxInsulin, MainApp.getConfigBuilder().getPumpDescription().bolusStep, new DecimalFormat("0.00"), false);
|
||||
editCarbs = (NumberPicker) view.findViewById(R.id.treatments_newtreatment_carbsamount);
|
||||
editInsulin = (NumberPicker) view.findViewById(R.id.treatments_newtreatment_insulinamount);
|
||||
|
||||
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false);
|
||||
editInsulin.setParams(0d, 0d, maxInsulin, MainApp.getConfigBuilder().getPumpDescription().bolusStep, new DecimalFormat("0.00"), false);
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
if (getDialog() != null)
|
||||
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
switch (view.getId()) {
|
||||
|
|
|
@ -21,7 +21,6 @@ import android.widget.ArrayAdapter;
|
|||
import android.widget.Button;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.CompoundButton;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TextView;
|
||||
|
@ -44,24 +43,24 @@ import info.nightscout.androidaps.MainApp;
|
|||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.data.DetailedBolusInfo;
|
||||
import info.nightscout.androidaps.data.IobTotal;
|
||||
import info.nightscout.androidaps.data.Profile;
|
||||
import info.nightscout.androidaps.data.ProfileStore;
|
||||
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.events.EventRefreshOverview;
|
||||
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
|
||||
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
|
||||
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.NumberPicker;
|
||||
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;
|
||||
|
@ -69,10 +68,7 @@ import info.nightscout.utils.ToastUtils;
|
|||
public class WizardDialog extends DialogFragment implements OnClickListener, CompoundButton.OnCheckedChangeListener, Spinner.OnItemSelectedListener {
|
||||
private static Logger log = LoggerFactory.getLogger(WizardDialog.class);
|
||||
|
||||
Button wizardDialogDeliverButton;
|
||||
TextView correctionInput;
|
||||
TextView carbsInput;
|
||||
TextView bgInput;
|
||||
Button okButton;
|
||||
TextView bg;
|
||||
TextView bgInsulin;
|
||||
TextView bgUnits;
|
||||
|
@ -85,8 +81,6 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
CheckBox basalIobCheckbox;
|
||||
TextView correctionInsulin;
|
||||
TextView total;
|
||||
TextView totalInsulin;
|
||||
EditText carbTimeEdit;
|
||||
Spinner profileSpinner;
|
||||
CheckBox superbolusCheckbox;
|
||||
TextView superbolus;
|
||||
|
@ -99,10 +93,10 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
TextView cob;
|
||||
TextView cobInsulin;
|
||||
|
||||
PlusMinusEditText editBg;
|
||||
PlusMinusEditText editCarbs;
|
||||
PlusMinusEditText editCorr;
|
||||
PlusMinusEditText editCarbTime;
|
||||
NumberPicker editBg;
|
||||
NumberPicker editCarbs;
|
||||
NumberPicker editCorr;
|
||||
NumberPicker editCarbTime;
|
||||
|
||||
Integer calculatedCarbs = 0;
|
||||
Double calculatedTotalInsulin = 0d;
|
||||
|
@ -127,11 +121,15 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetach() {
|
||||
super.onDetach();
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
if (getDialog() != null)
|
||||
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
super.onPause();
|
||||
MainApp.bus().register(this);
|
||||
}
|
||||
|
||||
|
@ -148,7 +146,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (ConfigBuilderPlugin.getActiveAPS() instanceof OpenAPSAMAPlugin && ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(new Date().getTime() - 11 * 60 * 1000L))) {
|
||||
if (ConfigBuilderPlugin.getActiveAPS() instanceof OpenAPSAMAPlugin && ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(System.currentTimeMillis() - 11 * 60 * 1000L))) {
|
||||
cobLayout.setVisibility(View.VISIBLE);
|
||||
cobAvailable = true;
|
||||
} else {
|
||||
|
@ -195,8 +193,9 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
|
||||
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
|
||||
|
||||
wizardDialogDeliverButton = (Button) view.findViewById(R.id.treatments_wizard_deliverButton);
|
||||
wizardDialogDeliverButton.setOnClickListener(this);
|
||||
okButton = (Button) view.findViewById(R.id.ok);
|
||||
okButton.setOnClickListener(this);
|
||||
view.findViewById(R.id.cancel).setOnClickListener(this);
|
||||
|
||||
bg = (TextView) view.findViewById(R.id.treatments_wizard_bg);
|
||||
bgInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bginsulin);
|
||||
|
@ -207,8 +206,6 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
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);
|
||||
|
||||
|
@ -216,9 +213,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
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);
|
||||
|
@ -236,22 +231,20 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
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);
|
||||
editCarbTime = (NumberPicker) view.findViewById(R.id.treatments_wizard_carbtimeinput);
|
||||
editCorr = (NumberPicker) view.findViewById(R.id.treatments_wizard_correctioninput);
|
||||
editCarbs = (NumberPicker) view.findViewById(R.id.treatments_wizard_carbsinput);
|
||||
editBg = (NumberPicker) view.findViewById(R.id.treatments_wizard_bginput);
|
||||
|
||||
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);
|
||||
|
||||
editBg = new PlusMinusEditText(view, R.id.treatments_wizard_bginput, R.id.treatments_wizard_bginput_plus, R.id.treatments_wizard_bginput_minus, 0d, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
|
||||
editCarbs = new PlusMinusEditText(view, R.id.treatments_wizard_carbsinput, R.id.treatments_wizard_carbsinput_plus, R.id.treatments_wizard_carbsinput_minus, 0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false);
|
||||
editCorr = new PlusMinusEditText(view, R.id.treatments_wizard_correctioninput, R.id.treatments_wizard_correctioninput_plus, R.id.treatments_wizard_correctioninput_minus, 0d, -maxCorrection, maxCorrection, 0.05d, new DecimalFormat("0.00"), false);
|
||||
editCarbTime = new PlusMinusEditText(view, R.id.treatments_wizard_carbtimeinput, R.id.treatments_wizard_carbtime_plus, R.id.treatments_wizard_carbtime_minus, 0d, -60d, 60d, 5d, new DecimalFormat("0"), false);
|
||||
editBg.setParams(0d, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false, textWatcher);
|
||||
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, textWatcher);
|
||||
editCorr.setParams(0d, -maxCorrection, maxCorrection, 0.05d, new DecimalFormat("0.00"), false, textWatcher);
|
||||
editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false);
|
||||
initDialog();
|
||||
|
||||
return view;
|
||||
|
@ -265,19 +258,19 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
@Override
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
|
||||
calculateInsulin();
|
||||
wizardDialogDeliverButton.setVisibility(View.VISIBLE);
|
||||
okButton.setVisibility(View.VISIBLE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> parent) {
|
||||
ToastUtils.showToastInUiThread(context, MainApp.sResources.getString(R.string.noprofileselected));
|
||||
wizardDialogDeliverButton.setVisibility(View.GONE);
|
||||
okButton.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
switch (view.getId()) {
|
||||
case R.id.treatments_wizard_deliverButton:
|
||||
case R.id.ok:
|
||||
if (calculatedTotalInsulin > 0d || calculatedCarbs > 0d) {
|
||||
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
|
||||
String confirmMessage = getString(R.string.entertreatmentquestion);
|
||||
|
@ -299,8 +292,8 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
|
||||
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 Double bg = SafeParse.stringToDouble(editBg.getText());
|
||||
final int carbTime = SafeParse.stringToInt(editCarbTime.getText());
|
||||
final boolean useSuperBolus = superbolusCheckbox.isChecked();
|
||||
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(context);
|
||||
|
@ -317,9 +310,10 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
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));
|
||||
activeloop.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000);
|
||||
MainApp.bus().post(new EventRefreshOverview("WizardDialog"));
|
||||
}
|
||||
pump.cancelTempBasal(true);
|
||||
result = pump.setTempBasalAbsolute(0d, 120);
|
||||
if (!result.success) {
|
||||
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror), result.comment, null);
|
||||
|
@ -350,6 +344,9 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
dismiss();
|
||||
}
|
||||
break;
|
||||
case R.id.cancel:
|
||||
dismiss();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -396,17 +393,17 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
|
||||
bg.setText(lastBg.valueToUnitsToString(units) + " ISF: " + DecimalFormatter.to1Decimal(sens));
|
||||
bgInsulin.setText(DecimalFormatter.to2Decimal(bgDiff / sens) + "U");
|
||||
bgInput.removeTextChangedListener(textWatcher);
|
||||
editBg.removeTextChangedListener(textWatcher);
|
||||
//bgInput.setText(lastBg.valueToUnitsToString(units));
|
||||
editBg.setValue(lastBg.valueToUnits(units));
|
||||
bgInput.addTextChangedListener(textWatcher);
|
||||
editBg.addTextChangedListener(textWatcher);
|
||||
} else {
|
||||
bg.setText("");
|
||||
bgInsulin.setText("");
|
||||
bgInput.removeTextChangedListener(textWatcher);
|
||||
editBg.removeTextChangedListener(textWatcher);
|
||||
//bgInput.setText("");
|
||||
editBg.setValue(0d);
|
||||
bgInput.addTextChangedListener(textWatcher);
|
||||
editBg.addTextChangedListener(textWatcher);
|
||||
}
|
||||
|
||||
// IOB calculation
|
||||
|
@ -418,17 +415,15 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
bolusIobInsulin.setText(DecimalFormatter.to2Decimal(-bolusIob.iob) + "U");
|
||||
basalIobInsulin.setText(DecimalFormatter.to2Decimal(-basalIob.basaliob) + "U");
|
||||
|
||||
totalInsulin.setText("");
|
||||
wizardDialogDeliverButton.setVisibility(Button.INVISIBLE);
|
||||
|
||||
// COB only if AMA is selected
|
||||
if (ConfigBuilderPlugin.getActiveAPS() instanceof OpenAPSAMAPlugin && ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(new Date().getTime() - 11 * 60 * 1000L))) {
|
||||
if (ConfigBuilderPlugin.getActiveAPS() instanceof OpenAPSAMAPlugin && ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(System.currentTimeMillis() - 11 * 60 * 1000L))) {
|
||||
cobLayout.setVisibility(View.VISIBLE);
|
||||
cobAvailable = true;
|
||||
} else {
|
||||
cobLayout.setVisibility(View.GONE);
|
||||
cobAvailable = false;
|
||||
}
|
||||
calculateInsulin();
|
||||
}
|
||||
|
||||
private void calculateInsulin() {
|
||||
|
@ -439,23 +434,23 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
Profile specificProfile = profile.getSpecificProfile(selectedAlternativeProfile);
|
||||
|
||||
// Entered values
|
||||
Double c_bg = SafeParse.stringToDouble(bgInput.getText().toString());
|
||||
Integer c_carbs = SafeParse.stringToInt(carbsInput.getText().toString());
|
||||
Double c_correction = SafeParse.stringToDouble(correctionInput.getText().toString());
|
||||
Double c_bg = SafeParse.stringToDouble(editBg.getText());
|
||||
Integer c_carbs = SafeParse.stringToInt(editCarbs.getText());
|
||||
Double c_correction = SafeParse.stringToDouble(editCorr.getText());
|
||||
Double corrAfterConstraint = MainApp.getConfigBuilder().applyBolusConstraints(c_correction);
|
||||
if (c_correction - corrAfterConstraint != 0) { // c_correction != corrAfterConstraint doesn't work
|
||||
correctionInput.removeTextChangedListener(textWatcher);
|
||||
correctionInput.setText("");
|
||||
correctionInput.addTextChangedListener(textWatcher);
|
||||
editCorr.removeTextChangedListener(textWatcher);
|
||||
editCorr.setValue(0d);
|
||||
editCorr.addTextChangedListener(textWatcher);
|
||||
//wizardDialogDeliverButton.setVisibility(Button.GONE);
|
||||
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), getString(R.string.bolusconstraintapplied));
|
||||
return;
|
||||
}
|
||||
Integer carbsAfterConstraint = MainApp.getConfigBuilder().applyCarbsConstraints(c_carbs);
|
||||
if (c_carbs - carbsAfterConstraint != 0) {
|
||||
carbsInput.removeTextChangedListener(textWatcher);
|
||||
carbsInput.setText("");
|
||||
carbsInput.addTextChangedListener(textWatcher);
|
||||
editCarbs.removeTextChangedListener(textWatcher);
|
||||
editCarbs.setValue(0d);
|
||||
editCarbs.addTextChangedListener(textWatcher);
|
||||
//wizardDialogDeliverButton.setVisibility(Button.GONE);
|
||||
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), getString(R.string.carbsconstraintapplied));
|
||||
return;
|
||||
|
@ -466,7 +461,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
// COB
|
||||
Double c_cob = 0d;
|
||||
if (cobAvailable && cobCheckbox.isChecked()) {
|
||||
if (ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(new Date().getTime() - 11 * 60 * 1000L))) {
|
||||
if (ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(System.currentTimeMillis() - 11 * 60 * 1000L))) {
|
||||
try {
|
||||
c_cob = SafeParse.stringToDouble(ConfigBuilderPlugin.getActiveAPS().getLastAPSResult().json().getString("COB"));
|
||||
} catch (JSONException e) {
|
||||
|
@ -489,14 +484,6 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
correctionInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromCorrection) + "U");
|
||||
calculatedTotalInsulin = wizard.calculatedTotalInsulin;
|
||||
|
||||
if (calculatedTotalInsulin <= 0) {
|
||||
total.setText(getString(R.string.missing) + " " + DecimalFormatter.to0Decimal(wizard.carbsEquivalent) + "g");
|
||||
totalInsulin.setText("");
|
||||
} else {
|
||||
total.setText("");
|
||||
totalInsulin.setText(DecimalFormatter.to2Decimal(calculatedTotalInsulin) + "U");
|
||||
}
|
||||
|
||||
calculatedCarbs = carbsAfterConstraint;
|
||||
|
||||
// Superbolus
|
||||
|
@ -531,10 +518,11 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
|
|||
if (calculatedTotalInsulin > 0d || calculatedCarbs > 0d) {
|
||||
String insulinText = calculatedTotalInsulin > 0d ? (DecimalFormatter.to2Decimal(calculatedTotalInsulin) + "U") : "";
|
||||
String carbsText = calculatedCarbs > 0d ? (DecimalFormatter.to0Decimal(calculatedCarbs) + "g") : "";
|
||||
wizardDialogDeliverButton.setText(getString(R.string.send) + " " + insulinText + " " + carbsText);
|
||||
wizardDialogDeliverButton.setVisibility(Button.VISIBLE);
|
||||
total.setText(getString(R.string.result) + ": " + insulinText + " " + carbsText);
|
||||
okButton.setVisibility(View.VISIBLE);
|
||||
} else {
|
||||
wizardDialogDeliverButton.setVisibility(Button.INVISIBLE);
|
||||
total.setText(getString(R.string.missing) + " " + DecimalFormatter.to0Decimal(wizard.carbsEquivalent) + "g");
|
||||
okButton.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
|
||||
boluscalcJSON = new JSONObject();
|
||||
|
|
|
@ -2,6 +2,13 @@ package info.nightscout.androidaps.plugins.Overview;
|
|||
|
||||
import java.util.Date;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.db.BgReading;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSAlarm;
|
||||
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
|
||||
import info.nightscout.utils.SP;
|
||||
|
||||
/**
|
||||
* Created by mike on 03.12.2016.
|
||||
*/
|
||||
|
@ -11,6 +18,7 @@ public class Notification {
|
|||
public static final int NORMAL = 1;
|
||||
public static final int LOW = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int ANNOUNCEMENT = 4;
|
||||
|
||||
public static final int PROFILE_SET_FAILED = 0;
|
||||
public static final int PROFILE_SET_OK = 1;
|
||||
|
@ -21,15 +29,18 @@ public class Notification {
|
|||
public static final int FAILED_UDPATE_PROFILE = 6;
|
||||
public static final int BASAL_VALUE_BELOW_MINIMUM = 7;
|
||||
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 = 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 static final int OLD_NS = 9;
|
||||
public static final int INVALID_PHONE_NUMBER = 10;
|
||||
public static final int APPROACHING_DAILY_LIMIT = 11;
|
||||
public static final int NSCLIENT_NO_WRITE_PERMISSION = 12;
|
||||
public static final int MISSING_SMS_PERMISSION = 13;
|
||||
public static final int ISF_MISSING = 14;
|
||||
public static final int IC_MISSING = 15;
|
||||
public static final int BASAL_MISSING = 16;
|
||||
public static final int TARGET_MISSING = 17;
|
||||
public static final int NSANNOUNCEMENT = 18;
|
||||
public static final int NSALARM = 19;
|
||||
public static final int NSURGENTALARM = 20;
|
||||
|
||||
public int id;
|
||||
public Date date;
|
||||
|
@ -37,6 +48,9 @@ public class Notification {
|
|||
public int level;
|
||||
public Date validTo = new Date(0);
|
||||
|
||||
public NSAlarm nsAlarm = null;
|
||||
public Integer soundId = null;
|
||||
|
||||
public Notification() {
|
||||
}
|
||||
|
||||
|
@ -53,7 +67,7 @@ public class Notification {
|
|||
this.date = new Date();
|
||||
this.text = text;
|
||||
this.level = level;
|
||||
this.validTo = new Date(new Date().getTime() + validMinutes * 60 * 1000L);
|
||||
this.validTo = new Date(System.currentTimeMillis() + validMinutes * 60 * 1000L);
|
||||
}
|
||||
|
||||
public Notification(int id, String text, int level) {
|
||||
|
@ -63,4 +77,68 @@ public class Notification {
|
|||
this.level = level;
|
||||
this.validTo = new Date(0);
|
||||
}
|
||||
|
||||
public Notification(NSAlarm nsAlarm) {
|
||||
this.date = new Date();
|
||||
this.validTo = new Date(0);
|
||||
this.nsAlarm = nsAlarm;
|
||||
switch (nsAlarm.getLevel()) {
|
||||
case 0:
|
||||
this.id = NSANNOUNCEMENT;
|
||||
this.level = ANNOUNCEMENT;
|
||||
this.text = nsAlarm.getMessage();
|
||||
this.validTo = new Date(System.currentTimeMillis() + 60 * 60 * 1000L);
|
||||
break;
|
||||
case 1:
|
||||
this.id = NSALARM;
|
||||
this.level = NORMAL;
|
||||
this.text = nsAlarm.getTile();
|
||||
if (isAlarmForLow() && SP.getBoolean(R.string.key_nsalarm_low, false) || isAlarmForHigh() && SP.getBoolean(R.string.key_nsalarm_high, false))
|
||||
this.soundId = R.raw.alarm;
|
||||
break;
|
||||
case 2:
|
||||
this.id = NSURGENTALARM;
|
||||
this.level = URGENT;
|
||||
this.text = nsAlarm.getTile();
|
||||
if (isAlarmForLow() && SP.getBoolean(R.string.key_nsalarm_urgent_low, false) || isAlarmForHigh() && SP.getBoolean(R.string.key_nsalarm_urgent_high, false))
|
||||
this.soundId = R.raw.urgentalarm;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
if (nsAlarm == null)
|
||||
return true;
|
||||
if (level == ANNOUNCEMENT)
|
||||
return true;
|
||||
if (level == NORMAL && isAlarmForLow() && SP.getBoolean(R.string.key_nsalarm_low, false) || isAlarmForHigh() && SP.getBoolean(R.string.key_nsalarm_high, false))
|
||||
return true;
|
||||
if (level == URGENT && isAlarmForLow() && SP.getBoolean(R.string.key_nsalarm_urgent_low, false) || isAlarmForHigh() && SP.getBoolean(R.string.key_nsalarm_urgent_high, false))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean isAlarmForLow() {
|
||||
BgReading bgReading = MainApp.getDbHelper().lastBg();
|
||||
if (bgReading == null)
|
||||
return false;
|
||||
Double threshold = NSSettingsStatus.getInstance().getThreshold("bgTargetTop");
|
||||
if (threshold == null)
|
||||
return false;
|
||||
if (bgReading.value <= threshold)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean isAlarmForHigh() {
|
||||
BgReading bgReading = MainApp.getDbHelper().lastBg();
|
||||
if (bgReading == null)
|
||||
return false;
|
||||
Double threshold = NSSettingsStatus.getInstance().getThreshold("bgTargetBottom");
|
||||
if (threshold == null)
|
||||
return false;
|
||||
if (bgReading.value >= threshold)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package info.nightscout.androidaps.plugins.Overview;
|
||||
|
||||
import android.content.Intent;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
@ -9,6 +11,11 @@ import java.util.Comparator;
|
|||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.Services.AlarmSoundService;
|
||||
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
|
||||
|
||||
|
||||
/**
|
||||
* Created by mike on 03.12.2016.
|
||||
|
@ -41,23 +48,39 @@ public class NotificationStore {
|
|||
return;
|
||||
}
|
||||
}
|
||||
if (n.soundId != null) {
|
||||
Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class);
|
||||
alarm.putExtra("soundid", n.soundId);
|
||||
MainApp.instance().startService(alarm);
|
||||
}
|
||||
store.add(n);
|
||||
|
||||
WearPlugin wearPlugin = (WearPlugin) MainApp.getSpecificPlugin(WearPlugin.class);
|
||||
if(wearPlugin!= null && wearPlugin.isEnabled()) {
|
||||
wearPlugin.overviewNotification(n.id, "OverviewNotification:\n" + n.text);
|
||||
}
|
||||
|
||||
Collections.sort(store, new NotificationComparator());
|
||||
}
|
||||
|
||||
public void remove(int id) {
|
||||
public boolean remove(int id) {
|
||||
for (int i = 0; i < store.size(); i++) {
|
||||
if (get(i).id == id) {
|
||||
if (get(i).soundId != null) {
|
||||
Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class);
|
||||
MainApp.instance().stopService(alarm);
|
||||
}
|
||||
store.remove(i);
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void removeExpired() {
|
||||
for (int i = 0; i < store.size(); i++) {
|
||||
Notification n = get(i);
|
||||
if (n.validTo.getTime() != 0 && n.validTo.getTime() < new Date().getTime()) {
|
||||
if (n.validTo.getTime() != 0 && n.validTo.getTime() < System.currentTimeMillis()) {
|
||||
store.remove(i);
|
||||
i--;
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -7,6 +7,7 @@ import org.json.JSONException;
|
|||
|
||||
import info.nightscout.androidaps.MainApp;
|
||||
import info.nightscout.androidaps.R;
|
||||
import info.nightscout.androidaps.events.EventRefreshOverview;
|
||||
import info.nightscout.androidaps.interfaces.PluginBase;
|
||||
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
|
||||
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
|
||||
|
@ -17,8 +18,8 @@ import info.nightscout.utils.SP;
|
|||
*/
|
||||
public class OverviewPlugin implements PluginBase {
|
||||
|
||||
public static Double bgTargetLow = 80d;
|
||||
public static Double bgTargetHigh = 180d;
|
||||
public static double bgTargetLow = 80d;
|
||||
public static double bgTargetHigh = 180d;
|
||||
|
||||
public QuickWizard quickWizard = new QuickWizard();
|
||||
|
||||
|
@ -99,11 +100,13 @@ public class OverviewPlugin implements PluginBase {
|
|||
@Subscribe
|
||||
public void onStatusEvent(final EventNewNotification n) {
|
||||
notificationStore.add(n.notification);
|
||||
MainApp.bus().post(new EventRefreshOverview("EventNewNotification"));
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onStatusEvent(final EventDismissNotification n) {
|
||||
notificationStore.remove(n.id);
|
||||
if (notificationStore.remove(n.id))
|
||||
MainApp.bus().post(new EventRefreshOverview("EventDismissNotification"));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package info.nightscout.androidaps.plugins.Overview.events;
|
||||
|
||||
/**
|
||||
* Created by mike on 02.07.2017.
|
||||
*/
|
||||
|
||||
public class EventSetWakeLock {
|
||||
public boolean lock = false;
|
||||
|
||||
public EventSetWakeLock(boolean val) {
|
||||
lock = val;
|
||||
}
|
||||
}
|
|
@ -23,10 +23,8 @@ public class TimeAsXAxisLabelFormatter extends DefaultLabelFormatter {
|
|||
public String formatLabel(double value, boolean isValueX) {
|
||||
if (isValueX) {
|
||||
// format as date
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeInMillis((long) value);
|
||||
DateFormat dateFormat = new SimpleDateFormat(mFormat);
|
||||
return dateFormat.format(calendar.getTimeInMillis());
|
||||
return dateFormat.format((long) value);
|
||||
} else {
|
||||
return super.formatLabel(value, isValueX);
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue