Merge branch 'dev' into medtronic_andy and some minor changes to make it compilable

This commit is contained in:
Andy Rozman 2018-09-14 18:14:45 +01:00
commit da75ed643d
619 changed files with 35392 additions and 17984 deletions

2
.gitignore vendored
View file

@ -11,3 +11,5 @@ app/src/main/jniLibs
full/ full/
debug/ debug/
release/ release/
app/com.crashlytics.settings.json
app/session_analytics.tap

View file

@ -18,7 +18,10 @@ There you can find the Project (Medtronic), with nice board with all the tasks (
[![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build status](https://travis-ci.org/MilosKozak/AndroidAPS.svg?branch=master)](https://travis-ci.org/MilosKozak/AndroidAPS) [![Build status](https://travis-ci.org/MilosKozak/AndroidAPS.svg?branch=master)](https://travis-ci.org/MilosKozak/AndroidAPS)
[![Crowdin](https://d322cqt584bo4o.cloudfront.net/androidaps/localized.svg)](https://translations.androidaps.org/project/androidaps)
[![Documentation Status](https://readthedocs.org/projects/androidaps/badge/?version=latest)](https://androidaps.readthedocs.io/en/latest/?badge=latest)
[![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/master/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS) [![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/master/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS)
dev: [![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/dev/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS) dev: [![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/dev/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS)
[![Donate via PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y4LHGJJESAVB8) [![Donate via PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y4LHGJJESAVB8)

View file

@ -37,9 +37,7 @@ repositories {
} }
def generateGitBuild = { -> def generateGitBuild = { ->
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('"')
try { try {
def stdout = new ByteArrayOutputStream() def stdout = new ByteArrayOutputStream()
exec { exec {
@ -51,9 +49,12 @@ def generateGitBuild = { ->
} catch (ignored) { } catch (ignored) {
stringBuilder.append('NoGitSystemAvailable') stringBuilder.append('NoGitSystemAvailable')
} }
stringBuilder.append('-') return stringBuilder.toString()
}
def generateDate = { ->
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append((new Date()).format('yyyy.MM.dd-HH:mm')) stringBuilder.append((new Date()).format('yyyy.MM.dd-HH:mm'))
stringBuilder.append('"')
return stringBuilder.toString() return stringBuilder.toString()
} }
@ -66,14 +67,14 @@ android {
compileSdkVersion 27 compileSdkVersion 27
defaultConfig { defaultConfig {
applicationId "info.nightscout.androidaps"
minSdkVersion 21 minSdkVersion 21
targetSdkVersion 25 targetSdkVersion 25
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "2.0a-dev" version "2.0g-medtronic"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild() buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk { ndk {
@ -103,6 +104,7 @@ android {
productFlavors { productFlavors {
flavorDimensions "standard" flavorDimensions "standard"
full { full {
applicationId "info.nightscout.androidaps"
dimension "standard" dimension "standard"
resValue "string", "app_name", "AndroidAPS" resValue "string", "app_name", "AndroidAPS"
versionName version versionName version
@ -110,13 +112,9 @@ android {
appIcon: "@mipmap/ic_launcher", appIcon: "@mipmap/ic_launcher",
appIconRound: "@mipmap/ic_launcher_round" appIconRound: "@mipmap/ic_launcher_round"
] ]
buildConfigField "boolean", "APS", "true"
buildConfigField "boolean", "PUMPDRIVERS", "true"
buildConfigField "boolean", "NSCLIENTOLNY", "false"
buildConfigField "boolean", "G5UPLOADER", "false"
buildConfigField "boolean", "PUMPCONTROL", "false"
} }
pumpcontrol { pumpcontrol {
applicationId "info.nightscout.androidaps"
dimension "standard" dimension "standard"
resValue "string", "app_name", "AndroidAPS" resValue "string", "app_name", "AndroidAPS"
versionName version versionName version
@ -124,13 +122,9 @@ android {
appIcon: "@mipmap/blueowl", appIcon: "@mipmap/blueowl",
appIconRound: "@null" appIconRound: "@null"
] ]
buildConfigField "boolean", "APS", "false"
buildConfigField "boolean", "PUMPDRIVERS", "true"
buildConfigField "boolean", "NSCLIENTOLNY", "false"
buildConfigField "boolean", "G5UPLOADER", "false"
buildConfigField "boolean", "PUMPCONTROL", "true"
} }
nsclient { nsclient {
applicationId "info.nightscout.nsclient"
dimension "standard" dimension "standard"
resValue "string", "app_name", "NSClient" resValue "string", "app_name", "NSClient"
versionName version + "-nsclient" versionName version + "-nsclient"
@ -138,25 +132,16 @@ android {
appIcon: "@mipmap/yellowowl", appIcon: "@mipmap/yellowowl",
appIconRound: "@null" appIconRound: "@null"
] ]
buildConfigField "boolean", "APS", "false"
buildConfigField "boolean", "PUMPDRIVERS", "false"
buildConfigField "boolean", "NSCLIENTOLNY", "true"
buildConfigField "boolean", "G5UPLOADER", "false"
buildConfigField "boolean", "PUMPCONTROL", "false"
} }
g5uploader { nsclient2 {
applicationId "info.nightscout.nsclient2"
dimension "standard" dimension "standard"
resValue "string", "app_name", "NSClient" resValue "string", "app_name", "NSClient2"
versionName version + "-nsclient" versionName version + "-nsclient"
manifestPlaceholders = [ manifestPlaceholders = [
appIcon: "@mipmap/yellowowl", appIcon: "@mipmap/yellowowl",
appIconRound: "@null" appIconRound: "@null"
] ]
buildConfigField "boolean", "APS", "false"
buildConfigField "boolean", "PUMPDRIVERS", "false"
buildConfigField "boolean", "NSCLIENTOLNY", "false"
buildConfigField "boolean", "G5UPLOADER", "true"
buildConfigField "boolean", "PUMPCONTROL", "false"
} }
} }
compileOptions { compileOptions {
@ -168,6 +153,8 @@ android {
unitTests.returnDefaultValues = true unitTests.returnDefaultValues = true
unitTests.includeAndroidResources = true unitTests.includeAndroidResources = true
} }
useLibrary "org.apache.http.legacy"
} }
allprojects { allprojects {
@ -196,6 +183,7 @@ dependencies {
libs "MilosKozak:danars-support-lib:master@zip" libs "MilosKozak:danars-support-lib:master@zip"
implementation "com.android.support:appcompat-v7:${supportLibraryVersion}" implementation "com.android.support:appcompat-v7:${supportLibraryVersion}"
implementation "com.android.support:support-v13:${supportLibraryVersion}"
implementation "com.android.support:support-v4:${supportLibraryVersion}" implementation "com.android.support:support-v4:${supportLibraryVersion}"
implementation "com.android.support:cardview-v7:${supportLibraryVersion}" implementation "com.android.support:cardview-v7:${supportLibraryVersion}"
implementation "com.android.support:recyclerview-v7:${supportLibraryVersion}" implementation "com.android.support:recyclerview-v7:${supportLibraryVersion}"

View file

@ -37,21 +37,20 @@
<activity android:name=".MainActivity"> <activity android:name=".MainActivity">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".PreferencesActivity" /> <activity android:name=".activities.PreferencesActivity" />
<activity <activity
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity" android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity <activity
android:name=".plugins.Overview.Dialogs.ErrorHelperActivity" android:name=".plugins.Overview.Dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".AgreementActivity" /> <activity android:name=".activities.AgreementActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" />
<activity android:name=".TDDStatsActivity" /> <activity android:name=".activities.TDDStatsActivity" />
<activity android:name=".plugins.Overview.activities.QuickWizardListActivity"> <activity android:name=".plugins.Overview.activities.QuickWizardListActivity">
<intent-filter> <intent-filter>
<action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" /> <action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" />
@ -135,9 +134,19 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
<!-- Service processing incomming data --> <!-- Service processing incomming data -->
<service <service
android:name=".Services.DataService" android:name=".services.DataService"
android:exported="false" /> android:exported="false" />
<service <service
android:name=".plugins.PumpDanaR.services.DanaRExecutionService" android:name=".plugins.PumpDanaR.services.DanaRExecutionService"
@ -167,7 +176,7 @@
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
android:name=".Services.AlarmSoundService" android:name=".services.AlarmSoundService"
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
@ -192,14 +201,16 @@
android:theme="@style/AppTheme.NoActionBar" android:theme="@style/AppTheme.NoActionBar"
android:label="@string/title_activity_setup_wizard" /> android:label="@string/title_activity_setup_wizard" />
<activity android:name=".activities.SingleFragmentActivity"
android:theme="@style/AppTheme" />
<activity android:name=".plugins.Maintenance.activities.LogSettingActivity"></activity>
<activity <activity
android:name=".plugins.PumpCommon.hw.rileylink.dialog.RileyLinkStatusActivity" android:name=".plugins.PumpCommon.hw.rileylink.dialog.RileyLinkStatusActivity"
android:label="@string/title_activity_rileylink_settings" android:label="@string/title_activity_rileylink_settings"
android:theme="@style/Theme.AppCompat.NoTitle" /> android:theme="@style/Theme.AppCompat.NoTitle" />
<activity
android:name=".SingleFragmentActivity"
android:theme="@style/AppTheme" />
</application> </application>
</manifest> </manifest>

View file

@ -18,7 +18,7 @@
<maxHistory>120</maxHistory> <maxHistory>120</maxHistory>
</rollingPolicy> </rollingPolicy>
<encoder> <encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level [%class{0}.%M\(\):%line]: %msg%n</pattern> <pattern>%d{HH:mm:ss.SSS} [%thread] %.-1level/%logger: [%class{0}.%M\(\):%line]: %msg%n</pattern>
</encoder> </encoder>
</appender> </appender>

View file

@ -5,20 +5,23 @@ import org.slf4j.LoggerFactory;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
/** Logs events has they're being posted to and dispatched from the event bus. /**
* * Logs events has they're being posted to and dispatched from the event bus.
* <p>
* A summary of event-receiver calls that occurred so far is logged * A summary of event-receiver calls that occurred so far is logged
* after 10s (after startup) and then again every 60s. * after 10s (after startup) and then again every 60s.
* */ */
public class LoggingBus extends Bus { public class LoggingBus extends Bus {
private static Logger log = LoggerFactory.getLogger(LoggingBus.class); private static Logger log = LoggerFactory.getLogger(L.EVENTS);
private static long everyMinute = System.currentTimeMillis() + 10 * 1000; private static long everyMinute = System.currentTimeMillis() + 10 * 1000;
private Map<String, Set<String>> event2Receiver = new HashMap<>(); private Map<String, Set<String>> event2Receiver = new HashMap<>();
@ -48,7 +51,10 @@ public class LoggingBus extends Bus {
log.debug(" source: <unknown>"); log.debug(" source: <unknown>");
} }
try {
super.post(event); super.post(event);
} catch (IllegalStateException ignored) {
}
} }
@Override @Override
@ -70,6 +76,7 @@ public class LoggingBus extends Bus {
log.debug(" receiver: <unknown>"); log.debug(" receiver: <unknown>");
} }
try {
if (everyMinute < System.currentTimeMillis()) { if (everyMinute < System.currentTimeMillis()) {
log.debug("***************** Event -> receiver pairings seen so far ****************"); log.debug("***************** Event -> receiver pairings seen so far ****************");
for (Map.Entry<String, Set<String>> stringSetEntry : event2Receiver.entrySet()) { for (Map.Entry<String, Set<String>> stringSetEntry : event2Receiver.entrySet()) {
@ -81,6 +88,8 @@ public class LoggingBus extends Bus {
log.debug("*************************************************************************"); log.debug("*************************************************************************");
everyMinute = System.currentTimeMillis() + 60 * 1000; everyMinute = System.currentTimeMillis() + 60 * 1000;
} }
} catch (ConcurrentModificationException ignored) {
}
super.dispatch(event, wrapper); super.dispatch(event, wrapper);
} }

View file

@ -6,39 +6,19 @@ package info.nightscout.androidaps;
public class Config { public class Config {
public static int SUPPORTEDNSVERSION = 1002; // 0.10.00 public static int SUPPORTEDNSVERSION = 1002; // 0.10.00
// MAIN FUCTIONALITY public static final boolean APS = BuildConfig.FLAVOR.equals("full");
public static final boolean APS = BuildConfig.APS;
// PLUGINS
public static final boolean NSCLIENT = BuildConfig.NSCLIENTOLNY;
public static final boolean G5UPLOADER = BuildConfig.G5UPLOADER;
public static final boolean PUMPCONTROL = BuildConfig.PUMPCONTROL;
public static final boolean HWPUMPS = BuildConfig.PUMPDRIVERS; public static final boolean NSCLIENT = BuildConfig.FLAVOR.equals("nsclient") || BuildConfig.FLAVOR.equals("nsclient2");
public static final boolean PUMPCONTROL = BuildConfig.FLAVOR.equals("pumpcontrol");
public static final boolean ACTION = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER; public static final boolean PUMPDRIVERS = BuildConfig.FLAVOR.equals("full") || BuildConfig.FLAVOR.equals("pumpcontrol");
public static final boolean MDI = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean OTHERPROFILES = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean SAFETY = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER; public static final boolean ACTION = !NSCLIENT;
public static final boolean MDI = !NSCLIENT;
public static final boolean OTHERPROFILES = !NSCLIENT;
public static final boolean SAFETY = !NSCLIENT;
public static final boolean SMSCOMMUNICATORENABLED = !NSCLIENT;
public static final boolean detailedLog = true;
public static final boolean logFunctionCalls = 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 logNSUpload = true;
public static final boolean logPumpActions = true;
public static final boolean logCongigBuilderActions = true;
public static final boolean logAutosensData = false;
public static final boolean logEvents = false;
public static final boolean logProfile = false;
// DanaR specific
public static final boolean logDanaBTComm = true;
public static boolean logDanaMessageDetail = true;
public static final boolean logDanaSerialEngine = true;
} }

View file

@ -67,4 +67,5 @@ public class Constants {
//SMS Communicator //SMS Communicator
public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs();
} }

View file

@ -1,410 +0,0 @@
package info.nightscout.androidaps;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP;
public class HistoryBrowseActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class);
ImageButton chartButton;
boolean showBasal = true;
boolean showIob, showCob, showDev, showRat, showDevslope;
@BindView(R.id.historybrowse_date)
Button buttonDate;
@BindView(R.id.historybrowse_zoom)
Button buttonZoom;
@BindView(R.id.historyybrowse_bggraph)
GraphView bgGraph;
@BindView(R.id.historybrowse_iobgraph)
GraphView iobGraph;
@BindView(R.id.historybrowse_seekBar)
SeekBar seekBar;
@BindView(R.id.historybrowse_noprofile)
TextView noProfile;
private int rangeToDisplay = 24; // for graph
private long start;
IobCobCalculatorPlugin iobCobCalculatorPlugin;
EventCustomCalculationFinished eventCustomCalculationFinished = new EventCustomCalculationFinished();
public HistoryBrowseActivity() {
iobCobCalculatorPlugin = new IobCobCalculatorPlugin();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historybrowse);
ButterKnife.bind(this);
bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid));
bgGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid));
iobGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
setupChartMenu();
// set start of current day
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
}
@Override
protected void onResume() {
super.onResume();
updateGUI("onResume");
}
@OnClick(R.id.historybrowse_start)
void onClickStart() {
}
@OnClick(R.id.historybrowse_left)
void onClickLeft() {
start -= rangeToDisplay * 60 * 60 * 1000L;
updateGUI("left");
iobCobCalculatorPlugin.clearCache();
iobCobCalculatorPlugin.runCalculation("onClickLeft", start, true, eventCustomCalculationFinished);
}
@OnClick(R.id.historybrowse_right)
void onClickRight() {
start += rangeToDisplay * 60 * 60 * 1000L;
updateGUI("right");
iobCobCalculatorPlugin.clearCache();
iobCobCalculatorPlugin.runCalculation("onClickRight", start, true, eventCustomCalculationFinished);
}
@OnClick(R.id.historybrowse_end)
void onClickEnd() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
updateGUI("resetToMidnight");
iobCobCalculatorPlugin.clearCache();
iobCobCalculatorPlugin.runCalculation("onClickEnd", start, true, eventCustomCalculationFinished);
}
@OnClick(R.id.historybrowse_zoom)
void onClickZoom() {
rangeToDisplay += 6;
rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
updateGUI("rangeChange");
}
@OnLongClick(R.id.historybrowse_zoom)
boolean onLongClickZoom() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(start);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
updateGUI("resetToMidnight");
iobCobCalculatorPlugin.clearCache();
iobCobCalculatorPlugin.runCalculation("onLongClickZoom", start, true, eventCustomCalculationFinished);
return true;
}
@OnClick(R.id.historybrowse_date)
void onClickDate() {
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished e) {
Activity activity = this;
if (activity != null && e.cause == eventCustomCalculationFinished) {
log.debug("EventAutosensCalculationFinished");
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (HistoryBrowseActivity.this) {
updateGUI("EventAutosensCalculationFinished");
}
}
});
}
}
void updateGUI(String from) {
if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null)
return;
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
final Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) {
noProfile.setVisibility(View.VISIBLE);
return;
} else {
noProfile.setVisibility(View.GONE);
}
final String units = profile.getUnits();
double lowLineSetting = SP.getDouble("low_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units));
double highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units));
if (lowLineSetting < 1)
lowLineSetting = Profile.fromMgdlToUnits(76d, units);
if (highLineSetting < 1)
highLineSetting = Profile.fromMgdlToUnits(180d, units);
final double lowLine = lowLineSetting;
final double highLine = highLineSetting;
final boolean showPrediction = false;
int hoursToFetch;
final long toTime;
final long fromTime;
//if (showPrediction) {
//int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000));
//predHours = Math.min(2, predHours);
//predHours = Math.max(0, predHours);
//hoursToFetch = rangeToDisplay - predHours;
//toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
//fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
//endTime = toTime + predHours * 60 * 60 * 1000L;
//} else {
fromTime = start + 100000;
toTime = start + rangeToDisplay * 60 * 60 * 1000L;
//}
buttonDate.setText(DateUtil.dateAndTimeString(start));
buttonZoom.setText(String.valueOf(rangeToDisplay));
log.debug("Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime));
final long pointer = System.currentTimeMillis();
// ------------------ 1st graph
final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin());
// **** In range Area ****
graphData.addInRangeArea(fromTime, toTime, lowLine, highLine);
// **** BG ****
if (showPrediction)
//graphData.addBgReadings(fromTime, toTime, lowLine, highLine, (DetermineBasalResultAMA) finalLastRun.constraintsProcessed);
;
else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
// set manual x bounds to have nice steps
graphData.formatAxis(fromTime, toTime);
// Treatments
graphData.addTreatments(fromTime, toTime);
// add basal data
if (pump.getPumpDescription().isTempBasalCapable && showBasal) {
graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2d);
}
// **** NOW line ****
graphData.addNowLine(pointer);
// ------------------ 2nd graph
final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin);
boolean useIobForScale = false;
boolean useCobForScale = false;
boolean useDevForScale = false;
boolean useRatioForScale = false;
boolean useDevSlopeForScale = false;
if (showIob) {
useIobForScale = true;
} else if (showCob) {
useCobForScale = true;
} else if (showDev) {
useDevForScale = true;
} else if (showRat) {
useRatioForScale = true;
} else if (showDevslope) {
useDevSlopeForScale = true;
}
if (showIob)
secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d);
if (showCob)
secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d);
if (showDev)
secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d);
if (showRat)
secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d);
if (showDevslope)
secondGraphData.addDeviationSlope(fromTime, toTime, useDevSlopeForScale, 1d);
// **** NOW line ****
// set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, toTime);
secondGraphData.addNowLine(pointer);
// do GUI update
if (showIob || showCob || showDev || showRat || showDevslope) {
iobGraph.setVisibility(View.VISIBLE);
} else {
iobGraph.setVisibility(View.GONE);
}
// finally enforce drawing of graphs
graphData.performUpdate();
secondGraphData.performUpdate();
}
private void setupChartMenu() {
chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MenuItem item;
CharSequence title;
SpannableString s;
PopupMenu popup = new PopupMenu(v.getContext(), v);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showBasal);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showIob);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showCob);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showDev);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showRat);
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showDevslope);
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) {
showBasal = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) {
showIob = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) {
showCob = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) {
showDev = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) {
showRat = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) {
showDevslope = !item.isChecked();
}
updateGUI("onGraphCheckboxesCheckedChanged");
return true;
}
});
chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
}
});
popup.show();
}
});
}
}

View file

@ -38,27 +38,30 @@ import com.squareup.otto.Subscribe;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.activities.AgreementActivity;
import info.nightscout.androidaps.activities.HistoryBrowseActivity;
import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.activities.SingleFragmentActivity;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventFeatureRunning; import info.nightscout.androidaps.events.EventFeatureRunning;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Food.FoodPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.setupwizard.SetupWizardActivity; import info.nightscout.androidaps.setupwizard.SetupWizardActivity;
import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.androidaps.tabs.TabPageAdapter;
import info.nightscout.utils.AndroidPermission; import info.nightscout.utils.AndroidPermission;
import info.nightscout.utils.ImportExportPrefs;
import info.nightscout.utils.LocaleHelper; import info.nightscout.utils.LocaleHelper;
import info.nightscout.utils.LogDialog;
import info.nightscout.utils.OKDialog; import info.nightscout.utils.OKDialog;
import info.nightscout.utils.PasswordProtection; import info.nightscout.utils.PasswordProtection;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.VersionChecker;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(MainActivity.class); private static Logger log = LoggerFactory.getLogger(L.CORE);
protected PowerManager.WakeLock mWakeLock; protected PowerManager.WakeLock mWakeLock;
@ -70,7 +73,7 @@ public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (Config.logFunctionCalls) if (L.isEnabled(L.CORE))
log.debug("onCreate"); log.debug("onCreate");
Iconify.with(new FontAwesomeModule()); Iconify.with(new FontAwesomeModule());
@ -111,6 +114,7 @@ public class MainActivity extends AppCompatActivity {
public void onPageScrollStateChanged(int state) { public void onPageScrollStateChanged(int state) {
} }
}); });
VersionChecker.check();
} }
private void checkPluginPreferences(ViewPager viewPager) { private void checkPluginPreferences(ViewPager viewPager) {
@ -130,6 +134,9 @@ public class MainActivity extends AppCompatActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
if (L.isEnabled(L.CORE))
log.debug("onResume");
if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) { if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) {
Intent intent = new Intent(this, SetupWizardActivity.class); Intent intent = new Intent(this, SetupWizardActivity.class);
startActivity(intent); startActivity(intent);
@ -139,7 +146,7 @@ public class MainActivity extends AppCompatActivity {
AndroidPermission.notifyForStoragePermission(this); AndroidPermission.notifyForStoragePermission(this);
AndroidPermission.notifyForBatteryOptimizationPermission(this); AndroidPermission.notifyForBatteryOptimizationPermission(this);
if (BuildConfig.APS || BuildConfig.PUMPCONTROL) { if (Config.PUMPDRIVERS) {
AndroidPermission.notifyForLocationPermissions(this); AndroidPermission.notifyForLocationPermissions(this);
AndroidPermission.notifyForSMSPermissions(this); AndroidPermission.notifyForSMSPermissions(this);
} }
@ -149,6 +156,8 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
public void onDestroy() { public void onDestroy() {
if (L.isEnabled(L.CORE))
log.debug("onDestroy");
if (mWakeLock != null) if (mWakeLock != null)
if (mWakeLock.isHeld()) if (mWakeLock.isHeld())
mWakeLock.release(); mWakeLock.release();
@ -187,7 +196,7 @@ public class MainActivity extends AppCompatActivity {
} }
} }
boolean keepScreenOn = BuildConfig.NSCLIENTOLNY && SP.getBoolean(R.string.key_keep_screen_on, false); boolean keepScreenOn = Config.NSCLIENT && SP.getBoolean(R.string.key_keep_screen_on, false);
if (keepScreenOn) if (keepScreenOn)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else else
@ -281,7 +290,7 @@ public class MainActivity extends AppCompatActivity {
private void checkUpgradeToProfileTarget() { // TODO: can be removed in the future private void checkUpgradeToProfileTarget() { // TODO: can be removed in the future
boolean oldKeyExists = SP.contains("openapsma_min_bg"); boolean oldKeyExists = SP.contains("openapsma_min_bg");
if (oldKeyExists) { if (oldKeyExists) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
String oldRange = SP.getDouble("openapsma_min_bg", 0d) + " - " + SP.getDouble("openapsma_max_bg", 0d); String oldRange = SP.getDouble("openapsma_min_bg", 0d) + " - " + SP.getDouble("openapsma_max_bg", 0d);
String newRange = ""; String newRange = "";
if (profile != null) { if (profile != null) {
@ -344,7 +353,6 @@ public class MainActivity extends AppCompatActivity {
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu); getMenuInflater().inflate(R.menu.menu_main, menu);
pluginPreferencesMenuItem = menu.findItem(R.id.nav_plugin_preferences); pluginPreferencesMenuItem = menu.findItem(R.id.nav_plugin_preferences);
menu.findItem(R.id.nav_historybrowser).setVisible(MainApp.devBranch);
checkPluginPreferences(findViewById(R.id.pager)); checkPluginPreferences(findViewById(R.id.pager));
return true; return true;
} }
@ -366,42 +374,16 @@ public class MainActivity extends AppCompatActivity {
case R.id.nav_setupwizard: case R.id.nav_setupwizard:
startActivity(new Intent(this, SetupWizardActivity.class)); startActivity(new Intent(this, SetupWizardActivity.class));
return true; return true;
case R.id.nav_resetdb:
new AlertDialog.Builder(this)
.setTitle(R.string.nav_resetdb)
.setMessage(R.string.reset_db_confirm)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
MainApp.getDbHelper().resetDatabases();
// should be handled by Plugin-Interface and
// additional service interface and plugin registry
FoodPlugin.getPlugin().getService().resetFood();
TreatmentsPlugin.getPlugin().getService().resetTreatments();
})
.create()
.show();
return true;
case R.id.nav_export:
ImportExportPrefs.verifyStoragePermissions(this);
ImportExportPrefs.exportSharedPreferences(this);
return true;
case R.id.nav_import:
ImportExportPrefs.verifyStoragePermissions(this);
ImportExportPrefs.importSharedPreferences(this);
return true;
case R.id.nav_show_logcat:
LogDialog.showLogcat(this);
return true;
case R.id.nav_about: case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION); builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION);
if (Config.NSCLIENT || Config.G5UPLOADER) if (Config.NSCLIENT)
builder.setIcon(R.mipmap.yellowowl); builder.setIcon(R.mipmap.yellowowl);
else else
builder.setIcon(R.mipmap.blueowl); builder.setIcon(R.mipmap.blueowl);
String message = "Build: " + BuildConfig.BUILDVERSION + "\n"; String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n"; message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + ConfigBuilderPlugin.nightscoutVersionName; message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName;
if (MainApp.engineeringMode) if (MainApp.engineeringMode)
message += "\n" + MainApp.gs(R.string.engineering_mode_enabled); message += "\n" + MainApp.gs(R.string.engineering_mode_enabled);
message += MainApp.gs(R.string.about_link_urls); message += MainApp.gs(R.string.about_link_urls);

View file

@ -15,7 +15,6 @@ import android.util.Log;
import com.crashlytics.android.Crashlytics; import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.squareup.otto.Bus; import com.squareup.otto.Bus;
import com.squareup.otto.LoggingBus; import com.squareup.otto.LoggingBus;
@ -29,13 +28,12 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import ch.qos.logback.classic.LoggerContext;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.data.ConstraintChecker;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment; import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
@ -46,9 +44,12 @@ import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver; import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.DBAccessReceiver;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
@ -85,13 +86,14 @@ import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.Maintenance.LoggerUtils;
import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Fabric;
public class MainApp extends Application { public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(MainApp.class); private static Logger log = LoggerFactory.getLogger(L.CORE);
private static KeepAliveReceiver keepAliveReceiver; private static KeepAliveReceiver keepAliveReceiver;
private static Bus sBus; private static Bus sBus;
@ -107,6 +109,7 @@ public class MainApp extends Application {
private static DataReceiver dataReceiver = new DataReceiver(); private static DataReceiver dataReceiver = new DataReceiver();
private static NSAlarmReceiver alarmReciever = new NSAlarmReceiver(); private static NSAlarmReceiver alarmReciever = new NSAlarmReceiver();
private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver(); private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver();
private static DBAccessReceiver dbAccessReciever = new DBAccessReceiver();
private LocalBroadcastManager lbm; private LocalBroadcastManager lbm;
private BroadcastReceiver btReceiver; // used for RileyLink (Medtronic and Omnipod) private BroadcastReceiver btReceiver; // used for RileyLink (Medtronic and Omnipod)
@ -116,6 +119,7 @@ public class MainApp extends Application {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
log.debug("onCreate");
sInstance = this; sInstance = this;
sResources = getResources(); sResources = getResources();
sConstraintsChecker = new ConstraintChecker(this); sConstraintsChecker = new ConstraintChecker(this);
@ -128,7 +132,7 @@ public class MainApp extends Application {
Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION); Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION);
} }
} catch (Exception e) { } catch (Exception e) {
android.util.Log.e("ANDROIDAPS", "Error with Fabric init! " + e); log.error("Error with Fabric init! " + e);
} }
JodaTimeAndroid.init(this); JodaTimeAndroid.init(this);
@ -136,13 +140,13 @@ public class MainApp extends Application {
log.info("Version: " + BuildConfig.VERSION_NAME); log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION); log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
String extFilesDir = this.getLogDirectory(); String extFilesDir = LoggerUtils.getLogDirectory();
File engineeringModeSemaphore = new File(extFilesDir, "engineering_mode"); File engineeringModeSemaphore = new File(extFilesDir, "engineering_mode");
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile(); engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("dev"); devBranch = BuildConfig.VERSION.contains("dev");
sBus = Config.logEvents ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY); sBus = L.isEnabled(L.EVENTS) && devBranch ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY);
registerLocalBroadcastReceiver(); registerLocalBroadcastReceiver();
@ -161,15 +165,16 @@ public class MainApp extends Application {
pluginsList.add(SensitivityAAPSPlugin.getPlugin()); pluginsList.add(SensitivityAAPSPlugin.getPlugin());
pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin()); pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
pluginsList.add(SensitivityOref1Plugin.getPlugin()); pluginsList.add(SensitivityOref1Plugin.getPlugin());
if (Config.HWPUMPS) pluginsList.add(DanaRPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRPlugin.getPlugin());
if (Config.HWPUMPS) pluginsList.add(DanaRKoreanPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.HWPUMPS) pluginsList.add(DanaRv2Plugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.HWPUMPS) pluginsList.add(DanaRSPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin());
pluginsList.add(CareportalPlugin.getPlugin()); pluginsList.add(CareportalPlugin.getPlugin());
if (Config.HWPUMPS) pluginsList.add(MedtronicPumpPlugin.getPlugin()); if (Config.PUMPDRIVERS && engineeringMode)
if (Config.HWPUMPS && engineeringMode)
pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here
if (Config.HWPUMPS) pluginsList.add(ComboPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin());
if (Config.PUMPDRIVERS && engineeringMode)
pluginsList.add(MedtronicPumpPlugin.getPlugin());
if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin()); if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin()); pluginsList.add(VirtualPumpPlugin.getPlugin());
if (Config.APS) pluginsList.add(LoopPlugin.getPlugin()); if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
@ -182,17 +187,11 @@ public class MainApp extends Application {
pluginsList.add(TreatmentsPlugin.getPlugin()); pluginsList.add(TreatmentsPlugin.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin()); if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin()); if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin());
if (!Config.NSCLIENT && !Config.G5UPLOADER)
pluginsList.add(SourceXdripPlugin.getPlugin()); pluginsList.add(SourceXdripPlugin.getPlugin());
if (!Config.G5UPLOADER)
pluginsList.add(SourceNSClientPlugin.getPlugin()); pluginsList.add(SourceNSClientPlugin.getPlugin());
if (!Config.NSCLIENT && !Config.G5UPLOADER)
pluginsList.add(SourceMM640gPlugin.getPlugin()); pluginsList.add(SourceMM640gPlugin.getPlugin());
if (!Config.NSCLIENT && !Config.G5UPLOADER)
pluginsList.add(SourceGlimpPlugin.getPlugin()); pluginsList.add(SourceGlimpPlugin.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceDexcomG5Plugin.getPlugin()); pluginsList.add(SourceDexcomG5Plugin.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourcePoctechPlugin.getPlugin()); pluginsList.add(SourcePoctechPlugin.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(FoodPlugin.getPlugin());
@ -201,6 +200,7 @@ public class MainApp extends Application {
pluginsList.add(StatuslinePlugin.initPlugin(this)); pluginsList.add(StatuslinePlugin.initPlugin(this));
pluginsList.add(PersistentNotificationPlugin.getPlugin()); pluginsList.add(PersistentNotificationPlugin.getPlugin());
pluginsList.add(NSClientPlugin.getPlugin()); pluginsList.add(NSClientPlugin.getPlugin());
pluginsList.add(MaintenancePlugin.initPlugin(this));
pluginsList.add(sConfigBuilder = ConfigBuilderPlugin.getPlugin()); pluginsList.add(sConfigBuilder = ConfigBuilderPlugin.getPlugin());
@ -242,6 +242,9 @@ public class MainApp extends Application {
//register ack alarm //register ack alarm
lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM)); lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM));
//register dbaccess
lbm.registerReceiver(dbAccessReciever, new IntentFilter(Intents.ACTION_DATABASE));
} }
private void setBTReceiver() { private void setBTReceiver() {
@ -275,6 +278,7 @@ public class MainApp extends Application {
} }
private void startKeepAliveService() { private void startKeepAliveService() {
if (keepAliveReceiver == null) { if (keepAliveReceiver == null) {
keepAliveReceiver = new KeepAliveReceiver(); keepAliveReceiver = new KeepAliveReceiver();
@ -422,7 +426,7 @@ public class MainApp extends Application {
} }
public static boolean isEngineeringModeOrRelease() { public static boolean isEngineeringModeOrRelease() {
if (!BuildConfig.APS) if (!Config.APS)
return true; return true;
return engineeringMode || !devBranch; return engineeringMode || !devBranch;
} }
@ -431,13 +435,10 @@ public class MainApp extends Application {
return devBranch; return devBranch;
} }
public String getLogDirectory() {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
return lc.getProperty("EXT_FILES_DIR");
}
@Override @Override
public void onTerminate() { public void onTerminate() {
if (L.isEnabled(L.CORE))
log.debug("onTerminate");
super.onTerminate(); super.onTerminate();
if (sDatabaseHelper != null) { if (sDatabaseHelper != null) {
sDatabaseHelper.close(); sDatabaseHelper.close();
@ -448,5 +449,4 @@ public class MainApp extends Application {
unregisterReceiver(btReceiver); unregisterReceiver(btReceiver);
} }
} }
} }

View file

@ -1,616 +0,0 @@
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;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ProfileStore;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
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.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.Source.SourcePoctechPlugin;
import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.utils.BundleLogger;
import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
public class DataService extends IntentService {
private static Logger log = LoggerFactory.getLogger(DataService.class);
boolean xDripEnabled = false;
boolean nsClientEnabled = true;
boolean mm640gEnabled = false;
boolean glimpEnabled = false;
boolean dexcomG5Enabled = false;
boolean poctechEnabled = false;
public DataService() {
super("DataService");
registerBus();
}
@Override
protected void onHandleIntent(final Intent intent) {
if (Config.logFunctionCalls)
log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras()));
if (ConfigBuilderPlugin.getPlugin().getActiveBgSource() == null) {
xDripEnabled = true;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) {
xDripEnabled = true;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = true;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = true;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = true;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = true;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = true;
}
boolean isNSProfile = MainApp.getConfigBuilder().getActiveProfileInterface() != null && MainApp.getConfigBuilder().getActiveProfileInterface().getClass().equals(NSProfilePlugin.class);
boolean acceptNSData = !SP.getBoolean(R.string.key_ns_upload_only, false);
Bundle bundles = intent.getExtras();
if (bundles != null && bundles.containsKey("islocal")) {
acceptNSData = acceptNSData || bundles.getBoolean("islocal");
}
if (intent != null) {
final String action = intent.getAction();
if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) {
if (xDripEnabled) {
handleNewDataFromXDrip(intent);
}
} else if (Intents.NS_EMULATOR.equals(action)) {
if (mm640gEnabled) {
handleNewDataFromMM640g(intent);
}
} else if (Intents.GLIMP_BG.equals(action)) {
if (glimpEnabled) {
handleNewDataFromGlimp(intent);
}
} else if (Intents.DEXCOMG5_BG.equals(action)) {
if (dexcomG5Enabled) {
handleNewDataFromDexcomG5(intent);
}
} else if (Intents.POCTECH_BG.equals(action)) {
if (poctechEnabled) {
handleNewDataFromPoctech(intent);
}
} else if (Intents.ACTION_NEW_SGV.equals(action)) {
if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true))
handleNewDataFromNSClient(intent);
// Objectives 0
ObjectivesPlugin.bgIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
} else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) {
// always handle Profile if NSProfile is enabled without looking at nsUploadOnly
handleNewDataFromNSClient(intent);
} else if (acceptNSData &&
(Intents.ACTION_NEW_TREATMENT.equals(action) ||
Intents.ACTION_CHANGED_TREATMENT.equals(action) ||
Intents.ACTION_REMOVED_TREATMENT.equals(action) ||
Intents.ACTION_NEW_STATUS.equals(action) ||
Intents.ACTION_NEW_DEVICESTATUS.equals(action) ||
Intents.ACTION_NEW_FOOD.equals(action) ||
Intents.ACTION_CHANGED_FOOD.equals(action) ||
Intents.ACTION_REMOVED_FOOD.equals(action) ||
Intents.ACTION_NEW_CAL.equals(action) ||
Intents.ACTION_NEW_MBG.equals(action))
) {
handleNewDataFromNSClient(intent);
} else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) {
handleNewSMS(intent);
}
}
if (Config.logFunctionCalls)
log.debug("onHandleIntent exit " + intent);
DataReceiver.completeWakefulIntent(intent);
}
/*
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (Config.logFunctionCalls)
log.debug("onStartCommand");
return START_STICKY;
}
*/
@Override
public void onDestroy() {
super.onDestroy();
MainApp.bus().unregister(this);
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
private void handleNewDataFromXDrip(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE);
bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME);
bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP);
bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW);
String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified");
SourceXdripPlugin.getPlugin().setSource(source);
MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP");
}
private void handleNewDataFromGlimp(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
bgReading.value = bundle.getDouble("mySGV");
bgReading.direction = bundle.getString("myTrend");
bgReading.date = bundle.getLong("myTimestamp");
bgReading.raw = 0;
MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP");
}
private void handleNewDataFromDexcomG5(Intent intent) {
// onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
String data = bundle.getString("data");
log.debug("Received Dexcom Data", data);
try {
JSONArray jsonArray = new JSONArray(data);
log.debug("Received Dexcom Data size:" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
bgReading.value = json.getInt("m_value");
bgReading.direction = json.getString("m_trend");
bgReading.date = json.getLong("m_time") * 1000L;
bgReading.raw = 0;
boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5");
if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading);
}
if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleNewDataFromPoctech(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
String data = bundle.getString("data");
log.debug("Received Poctech Data", data);
try {
JSONArray jsonArray = new JSONArray(data);
log.debug("Received Poctech Data size:" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
bgReading.value = json.getDouble("current");
bgReading.direction = json.getString("direction");
bgReading.date = json.getLong("date");
bgReading.raw = json.getDouble("raw");
if (JsonHelper.safeGetString(json, "units", Constants.MGDL).equals("mmol/L"))
bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL;
boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech");
if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading);
}
if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleNewDataFromMM640g(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
final String collection = bundle.getString("collection");
if (collection == null) return;
if (collection.equals("entries")) {
final String data = bundle.getString("data");
if ((data != null) && (data.length() > 0)) {
try {
final JSONArray json_array = new JSONArray(data);
for (int i = 0; i < json_array.length(); i++) {
final JSONObject json_object = json_array.getJSONObject(i);
final String type = json_object.getString("type");
switch (type) {
case "sgv":
BgReading bgReading = new BgReading();
bgReading.value = json_object.getDouble("sgv");
bgReading.direction = json_object.getString("direction");
bgReading.date = json_object.getLong("date");
bgReading.raw = json_object.getDouble("sgv");
MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g");
break;
default:
log.debug("Unknown entries type: " + type);
}
}
} catch (JSONException e) {
log.error("Got JSON exception: " + e);
}
}
}
}
private void handleNewDataFromNSClient(Intent intent) {
Bundle bundles = intent.getExtras();
if (bundles == null) return;
if (Config.logIncommingData)
log.debug("Got intent: " + intent.getAction());
if (intent.getAction().equals(Intents.ACTION_NEW_STATUS)) {
if (bundles.containsKey("nsclientversioncode")) {
ConfigBuilderPlugin.nightscoutVersionCode = bundles.getInt("nightscoutversioncode"); // for ver 1.2.3 contains 10203
ConfigBuilderPlugin.nightscoutVersionName = bundles.getString("nightscoutversionname");
ConfigBuilderPlugin.nsClientVersionCode = bundles.getInt("nsclientversioncode"); // for ver 1.17 contains 117
ConfigBuilderPlugin.nsClientVersionName = bundles.getString("nsclientversionname");
log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName);
try {
if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
}
} catch (PackageManager.NameNotFoundException e) {
log.error("Unhandled exception", e);
}
if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS));
}
} else {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
}
if (bundles.containsKey("status")) {
try {
JSONObject statusJson = new JSONObject(bundles.getString("status"));
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) {
log.error("Unhandled exception", e);
}
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_DEVICESTATUS)) {
try {
if (bundles.containsKey("devicestatus")) {
JSONObject devicestatusJson = new JSONObject(bundles.getString("devicestatus"));
NSDeviceStatus.getInstance().setData(devicestatusJson);
if (devicestatusJson.has("pump")) {
// Objectives 0
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
}
}
if (bundles.containsKey("devicestatuses")) {
String devicestatusesstring = bundles.getString("devicestatuses");
JSONArray jsonArray = new JSONArray(devicestatusesstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject devicestatusJson = jsonArray.getJSONObject(i);
NSDeviceStatus.getInstance().setData(devicestatusJson);
if (devicestatusJson.has("pump")) {
// Objectives 0
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
}
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
// Handle profile
if (intent.getAction().equals(Intents.ACTION_NEW_PROFILE)) {
try {
String activeProfile = bundles.getString("activeprofile");
String profile = bundles.getString("profile");
ProfileStore profileStore = new ProfileStore(new JSONObject(profile));
NSProfilePlugin.getPlugin().storeNewProfile(profileStore);
MainApp.bus().post(new EventNSProfileUpdateGUI());
if (Config.logIncommingData)
log.debug("Received profileStore: " + activeProfile + " " + profile);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) {
try {
if (bundles.containsKey("treatment")) {
JSONObject json = new JSONObject(bundles.getString("treatment"));
handleTreatmentFromNS(json, intent);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
handleTreatmentFromNS(json, intent);
}
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_REMOVED_TREATMENT)) {
try {
if (bundles.containsKey("treatment")) {
String trstring = bundles.getString("treatment");
JSONObject json = new JSONObject(trstring);
handleTreatmentFromNS(json);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
handleTreatmentFromNS(json);
}
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) {
try {
if (bundles.containsKey("sgv")) {
String sgvstring = bundles.getString("sgv");
JSONObject sgvJson = new JSONObject(sgvstring);
storeSgv(sgvJson);
}
if (bundles.containsKey("sgvs")) {
String sgvstring = bundles.getString("sgvs");
JSONArray jsonArray = new JSONArray(sgvstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject sgvJson = jsonArray.getJSONObject(i);
storeSgv(sgvJson);
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) {
try {
if (bundles.containsKey("mbg")) {
String mbgstring = bundles.getString("mbg");
JSONObject mbgJson = new JSONObject(mbgstring);
storeMbg(mbgJson);
}
if (bundles.containsKey("mbgs")) {
String sgvstring = bundles.getString("mbgs");
JSONArray jsonArray = new JSONArray(sgvstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject mbgJson = jsonArray.getJSONObject(i);
storeMbg(mbgJson);
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_FOOD)
|| intent.getAction().equals(Intents.ACTION_CHANGED_FOOD)) {
int mode = Intents.ACTION_NEW_FOOD.equals(intent.getAction()) ? EventNsFood.ADD : EventNsFood.UPDATE;
EventNsFood evt = new EventNsFood(mode, bundles);
MainApp.bus().post(evt);
}
if (intent.getAction().equals(Intents.ACTION_REMOVED_FOOD)) {
EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles);
MainApp.bus().post(evt);
}
}
private void handleTreatmentFromNS(JSONObject json) {
// new DB model
EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json);
MainApp.bus().post(evtTreatment);
// old DB model
String _id = JsonHelper.safeGetString(json, "_id");
MainApp.getDbHelper().deleteTempTargetById(_id);
MainApp.getDbHelper().deleteTempBasalById(_id);
MainApp.getDbHelper().deleteExtendedBolusById(_id);
MainApp.getDbHelper().deleteCareportalEventById(_id);
MainApp.getDbHelper().deleteProfileSwitchById(_id);
}
private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException {
// new DB model
int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE;
double insulin = JsonHelper.safeGetDouble(json, "insulin");
double carbs = JsonHelper.safeGetDouble(json, "carbs");
String eventType = JsonHelper.safeGetString(json, "eventType");
if (insulin > 0 || carbs > 0) {
EventNsTreatment evtTreatment = new EventNsTreatment(mode, json);
MainApp.bus().post(evtTreatment);
} else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) {
// old DB model
MainApp.getDbHelper().updateDanaRHistoryRecordId(json);
} else if (eventType.equals(CareportalEvent.TEMPORARYTARGET)) {
MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.TEMPBASAL)) {
MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.COMBOBOLUS)) {
MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.PROFILESWITCH)) {
MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.SITECHANGE) ||
eventType.equals(CareportalEvent.INSULINCHANGE) ||
eventType.equals(CareportalEvent.SENSORCHANGE) ||
eventType.equals(CareportalEvent.BGCHECK) ||
eventType.equals(CareportalEvent.NOTE) ||
eventType.equals(CareportalEvent.NONE) ||
eventType.equals(CareportalEvent.ANNOUNCEMENT) ||
eventType.equals(CareportalEvent.QUESTION) ||
eventType.equals(CareportalEvent.EXERCISE) ||
eventType.equals(CareportalEvent.OPENAPSOFFLINE) ||
eventType.equals(CareportalEvent.PUMPBATTERYCHANGE)) {
MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json);
}
if (eventType.equals(CareportalEvent.ANNOUNCEMENT)) {
long date = JsonHelper.safeGetLong(json,"mills");
long now = System.currentTimeMillis();
String enteredBy = JsonHelper.safeGetString(json, "enteredBy", "");
String notes = JsonHelper.safeGetString(json, "notes", "");
if (date > now - 15 * 60 * 1000L && !notes.isEmpty()
&& !enteredBy.equals(SP.getString("careportal_enteredby", "AndroidAPS"))) {
Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60);
MainApp.bus().post(new EventNewNotification(announcement));
}
}
}
private void storeMbg(JSONObject mbgJson) {
NSMbg nsMbg = new NSMbg(mbgJson);
CareportalEvent careportalEvent = new CareportalEvent(nsMbg);
MainApp.getDbHelper().createOrUpdate(careportalEvent);
if (Config.logIncommingData)
log.debug("Adding/Updating new MBG: " + careportalEvent.log());
}
private void storeSgv(JSONObject sgvJson) {
NSSgv nsSgv = new NSSgv(sgvJson);
BgReading bgReading = new BgReading(nsSgv);
MainApp.getDbHelper().createIfNotExists(bgReading, "NS");
SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills"));
}
private void handleNewSMS(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
MainApp.bus().post(new EventNewSMS(bundle));
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
@ -9,6 +9,8 @@ import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.R;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class AgreementActivity extends Activity { public class AgreementActivity extends Activity {

View file

@ -0,0 +1,435 @@
package info.nightscout.androidaps.activities;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.T;
public class HistoryBrowseActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class);
ImageButton chartButton;
boolean showBasal = true;
boolean showIob, showCob, showDev, showRat, showDevslope;
@BindView(R.id.historybrowse_date)
Button buttonDate;
@BindView(R.id.historybrowse_zoom)
Button buttonZoom;
@BindView(R.id.historyybrowse_bggraph)
GraphView bgGraph;
@BindView(R.id.historybrowse_iobgraph)
GraphView iobGraph;
@BindView(R.id.historybrowse_seekBar)
SeekBar seekBar;
@BindView(R.id.historybrowse_noprofile)
TextView noProfile;
@BindView(R.id.overview_iobcalculationprogess)
TextView iobCalculationProgressView;
private int rangeToDisplay = 24; // for graph
private long start = 0;
IobCobCalculatorPlugin iobCobCalculatorPlugin;
EventCustomCalculationFinished eventCustomCalculationFinished = new EventCustomCalculationFinished();
public HistoryBrowseActivity() {
iobCobCalculatorPlugin = new IobCobCalculatorPlugin();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historybrowse);
ButterKnife.bind(this);
bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid));
bgGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid));
iobGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
setupChartMenu();
}
@Override
public void onPause() {
super.onPause();
MainApp.bus().unregister(this);
iobCobCalculatorPlugin.stopCalculation("onPause");
}
@Override
public void onResume() {
super.onResume();
MainApp.bus().register(this);
// set start of current day
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
runCalculation("onResume");
SystemClock.sleep(1000);
updateGUI("onResume");
}
@OnClick(R.id.historybrowse_left)
void onClickLeft() {
start -= T.hours(rangeToDisplay).msecs();
updateGUI("onClickLeft");
runCalculation("onClickLeft");
}
@OnClick(R.id.historybrowse_right)
void onClickRight() {
start += T.hours(rangeToDisplay).msecs();
updateGUI("onClickRight");
runCalculation("onClickRight");
}
@OnClick(R.id.historybrowse_end)
void onClickEnd() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
updateGUI("onClickEnd");
runCalculation("onClickEnd");
}
@OnClick(R.id.historybrowse_zoom)
void onClickZoom() {
rangeToDisplay += 6;
rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
updateGUI("rangeChange");
}
@OnLongClick(R.id.historybrowse_zoom)
boolean onLongClickZoom() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(start);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
start = calendar.getTimeInMillis();
updateGUI("resetToMidnight");
runCalculation("onLongClickZoom");
return true;
}
@OnClick(R.id.historybrowse_date)
void onClickDate() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(start));
DatePickerDialog dpd = DatePickerDialog.newInstance(
(view, year, monthOfYear, dayOfMonth) -> {
Date date = new Date(0);
date.setYear(year - 1900);
date.setMonth(monthOfYear);
date.setDate(dayOfMonth);
date.setHours(0);
start = date.getTime();
updateGUI("onClickDate");
runCalculation("onClickDate");
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
dpd.setThemeDark(true);
dpd.dismissOnPause(true);
dpd.show(getFragmentManager(), "Datepickerdialog");
}
private void runCalculation(String from) {
long end = start + T.hours(rangeToDisplay).msecs();
iobCobCalculatorPlugin.stopCalculation(from);
iobCobCalculatorPlugin.clearCache();
iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished);
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished e) {
if (e.cause == eventCustomCalculationFinished) {
log.debug("EventAutosensCalculationFinished");
runOnUiThread(() -> {
synchronized (HistoryBrowseActivity.this) {
updateGUI("EventAutosensCalculationFinished");
}
});
}
}
@Subscribe
public void onStatusEvent(final EventIobCalculationProgress e) {
runOnUiThread(() -> {
if (iobCalculationProgressView != null)
iobCalculationProgressView.setText(e.progress);
});
}
void updateGUI(String from) {
log.debug("updateGUI from: " + from);
if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null)
return;
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
final Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) {
noProfile.setVisibility(View.VISIBLE);
return;
} else {
noProfile.setVisibility(View.GONE);
}
final String units = profile.getUnits();
final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
final double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
buttonDate.setText(DateUtil.dateAndTimeString(start));
buttonZoom.setText(String.valueOf(rangeToDisplay));
final boolean showPrediction = false;
int hoursToFetch;
final long toTime;
final long fromTime;
//if (showPrediction) {
//int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000));
//predHours = Math.min(2, predHours);
//predHours = Math.max(0, predHours);
//hoursToFetch = rangeToDisplay - predHours;
//toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
//fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
//endTime = toTime + predHours * 60 * 60 * 1000L;
//} else {
fromTime = start + T.secs(100).msecs();
toTime = start + T.hours(rangeToDisplay).msecs();
//}
log.debug("Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime));
final long pointer = System.currentTimeMillis();
// ------------------ 1st graph
final GraphData graphData = new GraphData(bgGraph, iobCobCalculatorPlugin);
// **** In range Area ****
graphData.addInRangeArea(fromTime, toTime, lowLine, highLine);
// **** BG ****
if (showPrediction)
//graphData.addBgReadings(fromTime, toTime, lowLine, highLine, (DetermineBasalResultAMA) finalLastRun.constraintsProcessed);
;
else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
// set manual x bounds to have nice steps
graphData.formatAxis(fromTime, toTime);
// Treatments
graphData.addTreatments(fromTime, toTime);
// add basal data
if (pump.getPumpDescription().isTempBasalCapable && showBasal) {
graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2d);
}
// **** NOW line ****
graphData.addNowLine(pointer);
// ------------------ 2nd graph
new Thread(() -> {
final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin);
boolean useIobForScale = false;
boolean useCobForScale = false;
boolean useDevForScale = false;
boolean useRatioForScale = false;
boolean useDSForScale = false;
if (showIob) {
useIobForScale = true;
} else if (showCob) {
useCobForScale = true;
} else if (showDev) {
useDevForScale = true;
} else if (showRat) {
useRatioForScale = true;
} else if (showDevslope) {
useDSForScale = true;
}
if (showIob)
secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d);
if (showCob)
secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d);
if (showDev)
secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d);
if (showRat)
secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d);
if (showDevslope)
secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1d);
// **** NOW line ****
// set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, toTime);
secondGraphData.addNowLine(pointer);
// do GUI update
runOnUiThread(() -> {
if (showIob || showCob || showDev || showRat || showDevslope) {
iobGraph.setVisibility(View.VISIBLE);
} else {
iobGraph.setVisibility(View.GONE);
}
// finally enforce drawing of graphs
graphData.performUpdate();
if (showIob || showCob || showDev || showRat || showDevslope)
secondGraphData.performUpdate();
});
}).start();
}
private void setupChartMenu() {
chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(v -> {
MenuItem item;
CharSequence title;
SpannableString s;
PopupMenu popup = new PopupMenu(v.getContext(), v);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showBasal);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showIob);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showCob);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showDev);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showRat);
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showDevslope);
}
popup.setOnMenuItemClickListener(item1 -> {
if (item1.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) {
showBasal = !item1.isChecked();
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) {
showIob = !item1.isChecked();
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) {
showCob = !item1.isChecked();
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) {
showDev = !item1.isChecked();
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) {
showRat = !item1.isChecked();
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) {
showDevslope = !item1.isChecked();
}
updateGUI("onGraphCheckboxesCheckedChanged");
return true;
});
chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
popup.setOnDismissListener(menu -> chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp));
popup.show();
});
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
@ -11,6 +11,9 @@ import android.preference.PreferenceGroup;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.text.TextUtils; import android.text.TextUtils;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -88,7 +91,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
pref.setSummary("******"); pref.setSummary("******");
} else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) { } else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) {
pref.setSummary(SP.getString(R.string.key_danars_name, "")); pref.setSummary(SP.getString(R.string.key_danars_name, ""));
} else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) { } else if (editTextPref.getText() != null) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage()); ((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText()); pref.setSummary(editTextPref.getText());
} else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) { } else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) {
@ -134,7 +137,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResource(id); addPreferencesFromResource(id);
} else { } else {
if (!Config.NSCLIENT && !Config.G5UPLOADER) { if (!Config.NSCLIENT) {
addPreferencesFromResource(R.xml.pref_password); addPreferencesFromResource(R.xml.pref_password);
} }
addPreferencesFromResource(R.xml.pref_age); addPreferencesFromResource(R.xml.pref_age);
@ -157,7 +160,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY); addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY); addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY);
if (Config.HWPUMPS) { if (Config.PUMPDRIVERS) {
addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP);
@ -174,7 +177,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
} }
} }
if (!Config.NSCLIENT && !Config.G5UPLOADER) { if (!Config.NSCLIENT) {
addPreferencesFromResourceIfEnabled(VirtualPumpPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(VirtualPumpPlugin.getPlugin(), PluginType.PUMP);
} }
@ -185,9 +188,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.getPlugin(), PluginType.GENERAL);
if (!Config.NSCLIENT && !Config.G5UPLOADER) {
addPreferencesFromResource(R.xml.pref_others); addPreferencesFromResource(R.xml.pref_others);
}
addPreferencesFromResource(R.xml.pref_datachoices); addPreferencesFromResource(R.xml.pref_datachoices);
addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL);

View file

@ -1,16 +1,17 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.tabs.TabPageAdapter;
import info.nightscout.utils.PasswordProtection; import info.nightscout.utils.PasswordProtection;
public class SingleFragmentActivity extends AppCompatActivity { public class SingleFragmentActivity extends AppCompatActivity {

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.app.Activity; import android.app.Activity;
import android.graphics.Color; import android.graphics.Color;
@ -33,14 +33,15 @@ import java.util.Date;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
@ -121,7 +122,7 @@ public class TDDStatsActivity extends Activity {
TBB = SP.getString("TBB", "10.00"); TBB = SP.getString("TBB", "10.00");
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile != null) { if (profile != null) {
double cppTBB = profile.baseBasalSum(); double cppTBB = profile.baseBasalSum();
TBB = decimalFormat.format(cppTBB); TBB = decimalFormat.format(cppTBB);

View file

@ -58,6 +58,10 @@ public class ConstraintChecker implements ConstraintsInterface {
return applyBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS)); return applyBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS));
} }
public Constraint<Double> getMaxExtendedBolusAllowed() {
return applyExtendedBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS));
}
public Constraint<Integer> getMaxCarbsAllowed() { public Constraint<Integer> getMaxCarbsAllowed() {
return applyCarbsConstraints(new Constraint<>(Constants.REALLYHIGHCARBS)); return applyCarbsConstraints(new Constraint<>(Constants.REALLYHIGHCARBS));
} }
@ -170,6 +174,17 @@ public class ConstraintChecker implements ConstraintsInterface {
return insulin; return insulin;
} }
@Override
public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
constrain.applyExtendedBolusConstraints(insulin);
}
return insulin;
}
@Override @Override
public Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) { public Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) {
ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);

View file

@ -57,6 +57,7 @@ public class DetailedBolusInfo {
@Override @Override
public String toString() { public String toString() {
return new Date(date).toLocaleString() + return new Date(date).toLocaleString() +
" date: " + date +
" insulin: " + insulin + " insulin: " + insulin +
" carbs: " + carbs + " carbs: " + carbs +
" isValid: " + isValid + " isValid: " + isValid +

View file

@ -52,6 +52,14 @@ public class Profile {
protected Profile() { protected Profile() {
} }
@Override
public String toString() {
if (json != null)
return json.toString();
else
return "Profile has no JSON";
}
// Constructor from profileStore JSON // Constructor from profileStore JSON
public Profile(JSONObject json, String units) { public Profile(JSONObject json, String units) {
init(json, 100, 0); init(json, 100, 0);
@ -295,8 +303,6 @@ public class Profile {
Integer getShitfTimeSecs(Integer originalTime) { Integer getShitfTimeSecs(Integer originalTime) {
Integer shiftedTime = originalTime + timeshift * 60 * 60; Integer shiftedTime = originalTime + timeshift * 60 * 60;
shiftedTime = (shiftedTime + 24 * 60 * 60) % (24 * 60 * 60); shiftedTime = (shiftedTime + 24 * 60 * 60) % (24 * 60 * 60);
if (timeshift != 0 && Config.logProfile)
log.debug("(Sec) Original time: " + originalTime + " ShiftedTime: " + shiftedTime);
return shiftedTime; return shiftedTime;
} }

View file

@ -10,11 +10,12 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
public class PumpEnactResult { public class PumpEnactResult {
private static Logger log = LoggerFactory.getLogger(PumpEnactResult.class); private static Logger log = LoggerFactory.getLogger(L.APS);
public boolean success = false; // request was processed successfully (but possible no change was needed) public boolean success = false; // request was processed successfully (but possible no change was needed)
public boolean enacted = false; // request was processed successfully and change has been made public boolean enacted = false; // request was processed successfully and change has been made
@ -107,7 +108,7 @@ public class PumpEnactResult {
if (bolusDelivered > 0) { if (bolusDelivered > 0) {
ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted; ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted;
ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment; ret += "\n" + MainApp.gs(R.string.comment) + ": " + comment;
ret += "\n" + MainApp.gs(R.string.smb_shortname) ret += "\n" + MainApp.gs(R.string.configbuilder_insulin)
+ ": " + bolusDelivered + " " + MainApp.gs(R.string.insulin_unit_shortname); + ": " + bolusDelivered + " " + MainApp.gs(R.string.insulin_unit_shortname);
} else if (isTempCancel) { } else if (isTempCancel) {
ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted; ret += "\n" + MainApp.gs(R.string.enacted) + ": " + enacted;

View file

@ -15,6 +15,8 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
@ -24,7 +26,7 @@ import info.nightscout.utils.SP;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)
public class BgReading implements DataPointWithLabelInterface { public class BgReading implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(BgReading.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;
@ -142,7 +144,7 @@ public class BgReading implements DataPointWithLabelInterface {
return false; return false;
if (raw != other.raw) if (raw != other.raw)
return false; return false;
if (!direction.equals(other.direction)) if (!Objects.equals(direction, other.direction))
return false; return false;
if (!Objects.equals(_id, other._id)) if (!Objects.equals(_id, other._id))
return false; return false;
@ -160,6 +162,21 @@ public class BgReading implements DataPointWithLabelInterface {
_id = other._id; _id = other._id;
} }
public BgReading date(long date) {
this.date = date;
return this;
}
public BgReading date(Date date) {
this.date = date.getTime();
return this;
}
public BgReading value(double value) {
this.value = value;
return this;
}
// ------------------ DataPointWithLabelInterface ------------------ // ------------------ DataPointWithLabelInterface ------------------
@Override @Override
public double getX() { public double getX() {
@ -168,7 +185,7 @@ public class BgReading implements DataPointWithLabelInterface {
@Override @Override
public double getY() { public double getY() {
String units = MainApp.getConfigBuilder().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
return valueToUnits(units); return valueToUnits(units);
} }
@ -202,7 +219,7 @@ public class BgReading implements DataPointWithLabelInterface {
@Override @Override
public int getColor() { public int getColor() {
String units = MainApp.getConfigBuilder().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
Double lowLine = SP.getDouble("low_mark", 0d); Double lowLine = SP.getDouble("low_mark", 0d);
Double highLine = SP.getDouble("high_mark", 0d); Double highLine = SP.getDouble("high_mark", 0d);
if (lowLine < 1) { if (lowLine < 1) {

View file

@ -25,6 +25,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
@ -35,7 +37,7 @@ import info.nightscout.utils.Translator;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
public class CareportalEvent implements DataPointWithLabelInterface, Interval { public class CareportalEvent implements DataPointWithLabelInterface, Interval {
private static Logger log = LoggerFactory.getLogger(CareportalEvent.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;
@ -95,14 +97,17 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
public String age() { public String age() {
Map<TimeUnit, Long> diff = computeDiff(date, System.currentTimeMillis()); Map<TimeUnit, Long> diff = computeDiff(date, System.currentTimeMillis());
if (OverviewFragment.shorttextmode) if (OverviewFragment.shorttextmode)
return diff.get(TimeUnit.DAYS) +"d" + diff.get(TimeUnit.HOURS) + "h"; return diff.get(TimeUnit.DAYS) + "d" + diff.get(TimeUnit.HOURS) + "h";
else else
return diff.get(TimeUnit.DAYS) + " " + MainApp.gs(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.gs(R.string.hours); return diff.get(TimeUnit.DAYS) + " " + MainApp.gs(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.gs(R.string.hours);
} }
public boolean isOlderThan(double hours) { return getHoursFromStart() > hours; } public boolean isOlderThan(double hours) {
return getHoursFromStart() > hours;
}
public String log() { @Override
public String toString() {
return "CareportalEvent{" + return "CareportalEvent{" +
"date= " + date + "date= " + date +
", date= " + DateUtil.dateAndTimeString(date) + ", date= " + DateUtil.dateAndTimeString(date) +
@ -134,11 +139,11 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
CareportalEvent event = list.get(i); CareportalEvent event = list.get(i);
if (event.date <= time && event.date > (time - T.mins(5).msecs())) { if (event.date <= time && event.date > (time - T.mins(5).msecs())) {
//log.debug("Found event for time: " + DateUtil.dateAndTimeString(time) + " " + event.toString()); if (L.isEnabled(L.DATABASE))
log.debug("Found event for time: " + DateUtil.dateAndTimeFullString(time) + " " + event.toString());
return true; return true;
} }
} }
//log.debug("WWWWWW No found event for time: " + DateUtil.dateAndTimeString(time));
return false; return false;
} }
@ -153,7 +158,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@Override @Override
public double getY() { public double getY() {
String units = MainApp.getConfigBuilder().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
if (eventType.equals(MBG)) { if (eventType.equals(MBG)) {
double mbg = 0d; double mbg = 0d;
try { try {

View file

@ -27,8 +27,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -43,12 +41,15 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.utils.JsonHelper; import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PercentageSplitter; import info.nightscout.utils.PercentageSplitter;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -61,7 +62,7 @@ import info.nightscout.utils.ToastUtils;
* direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service. * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
*/ */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings"; public static final String DATABASE_BGREADINGS = "BgReadings";
@ -74,7 +75,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches"; public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs"; public static final String DATABASE_TDDS = "TDDs";
private static final int DATABASE_VERSION = 8; private static final int DATABASE_VERSION = 9;
public static Long earliestDataChange = null; public static Long earliestDataChange = null;
@ -108,6 +109,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Override @Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try { try {
if (L.isEnabled(L.DATABASE))
log.info("onCreate"); log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
@ -132,6 +134,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (oldVersion == 7 && newVersion == 8) { if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8"); log.debug("Upgrading database from v7 to v8");
} else if (oldVersion == 8 && newVersion == 9) {
log.debug("Upgrading database from v8 to v9");
} else { } else {
log.info(DatabaseHelper.class.getName(), "onUpgrade"); log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.dropTable(connectionSource, TempTarget.class, true);
@ -197,7 +201,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
VirtualPumpPlugin.setFakingStatus(true); VirtualPumpPlugin.getPlugin().setFakingStatus(true);
scheduleBgChange(null); // trigger refresh scheduleBgChange(null); // trigger refresh
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -233,7 +237,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
VirtualPumpPlugin.setFakingStatus(false); VirtualPumpPlugin.getPlugin().setFakingStatus(false);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
} }
@ -316,7 +320,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
public static long roundDateToSec(long date) { public static long roundDateToSec(long date) {
return date - date % 1000; long rounded = date - date % 1000;
if (rounded != date)
if (L.isEnabled(L.DATABASE))
log.debug("Rounding " + date + " to " + rounded);
return rounded;
} }
// ------------------- BgReading handling ----------------------- // ------------------- BgReading handling -----------------------
@ -326,14 +334,17 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
BgReading old = getDaoBgReadings().queryForId(bgReading.date); BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) { if (old == null) {
getDaoBgReadings().create(bgReading); getDaoBgReadings().create(bgReading);
if (L.isEnabled(L.DATABASE))
log.debug("BG: New record from: " + from + " " + bgReading.toString()); log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange(bgReading); scheduleBgChange(bgReading);
return true; return true;
} }
if (!old.isEqual(bgReading)) { if (!old.isEqual(bgReading)) {
if (L.isEnabled(L.DATABASE))
log.debug("BG: Similiar found: " + old.toString()); log.debug("BG: Similiar found: " + old.toString());
old.copyFrom(bgReading); old.copyFrom(bgReading);
getDaoBgReadings().update(old); getDaoBgReadings().update(old);
if (L.isEnabled(L.DATABASE))
log.debug("BG: Updating record from: " + from + " New data: " + old.toString()); log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange(bgReading); scheduleBgChange(bgReading);
return false; return false;
@ -356,6 +367,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleBgChange(@Nullable final BgReading bgReading) { private static void scheduleBgChange(@Nullable final BgReading bgReading) {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg"); log.debug("Firing EventNewBg");
MainApp.bus().post(new EventNewBG(bgReading)); MainApp.bus().post(new EventNewBG(bgReading));
scheduledBgPost = null; scheduledBgPost = null;
@ -388,7 +400,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
bgList = daoBgReadings.query(preparedQuery); bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) { } catch (SQLException e) {
log.debug(e.getMessage(), e); log.error("Unhandled exception", e);
} }
if (bgList != null && bgList.size() > 0) if (bgList != null && bgList.size() > 0)
return bgList.get(0); return bgList.get(0);
@ -431,6 +443,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<BgReading>(); return new ArrayList<BgReading>();
} }
public List<BgReading> getBgreadingsDataFromTime(long start, long end, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", start, end).and().gt("value", 38).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<BgReading>();
}
public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) { public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
try { try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings(); Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
@ -579,6 +608,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(old); // need to delete/create because date may change too getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget); old.copyFrom(tempTarget);
getDaoTempTargets().create(old); getDaoTempTargets().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
return true; return true;
@ -598,6 +628,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(old); // need to delete/create because date may change too getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget); old.copyFrom(tempTarget);
getDaoTempTargets().create(old); getDaoTempTargets().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
return true; return true;
@ -605,12 +636,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
getDaoTempTargets().create(tempTarget); getDaoTempTargets().create(tempTarget);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
return true; return true;
} }
if (tempTarget.source == Source.USER) { if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget); getDaoTempTargets().create(tempTarget);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
return true; return true;
@ -633,6 +666,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleTemporaryTargetChange() { private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange"); log.debug("Firing EventTempTargetChange");
MainApp.bus().post(new EventTempTargetChange()); MainApp.bus().post(new EventTempTargetChange());
scheduledTemTargetPost = null; scheduledTemTargetPost = null;
@ -665,13 +699,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) { public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try { try {
String units = JsonHelper.safeGetString(trJson, "units", MainApp.getConfigBuilder().getProfileUnits()); String units = JsonHelper.safeGetString(trJson, "units", ProfileFunctions.getInstance().getProfileUnits());
TempTarget tempTarget = new TempTarget() TempTarget tempTarget = new TempTarget()
.date(trJson.getLong("mills")) .date(trJson.getLong("mills"))
.duration(trJson.getInt("duration")) .duration(trJson.getInt("duration"))
.low(Profile.toMgdl(trJson.getDouble("targetBottom"), units)) .low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
.high(Profile.toMgdl(trJson.getDouble("targetTop"), units)) .high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
.reason(trJson.getString("reason")) .reason(JsonHelper.safeGetString(trJson, "reason", ""))
._id(trJson.getString("_id")) ._id(trJson.getString("_id"))
.source(Source.NIGHTSCOUT); .source(Source.NIGHTSCOUT);
createOrUpdate(tempTarget); createOrUpdate(tempTarget);
@ -753,7 +787,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} else if (list.size() == 1) { } else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0); DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) { if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id")); log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id"); record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record); getDaoDanaRHistory().update(record);
@ -783,10 +817,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery); List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) { if (trList.size() > 0) {
// do nothing, pump history record cannot be changed // do nothing, pump history record cannot be changed
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false; return false;
} }
getDaoTemporaryBasal().create(tempBasal); getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -804,6 +840,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal); old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old); getDaoTemporaryBasal().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
@ -826,6 +863,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal); old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old); getDaoTemporaryBasal().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
@ -835,6 +873,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
getDaoTemporaryBasal().create(tempBasal); getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -842,6 +881,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
if (tempBasal.source == Source.USER) { if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal); getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -882,6 +922,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleTemporaryBasalChange() { private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempBasalChange"); log.debug("Firing EventTempBasalChange");
MainApp.bus().post(new EventReloadTempBasalData()); MainApp.bus().post(new EventReloadTempBasalData());
MainApp.bus().post(new EventTempBasalChange()); MainApp.bus().post(new EventTempBasalChange());
@ -920,15 +961,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try { try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.source = Source.NIGHTSCOUT; .source(Source.NIGHTSCOUT)
extendedBolus.date = trJson.getLong("mills"); .date(trJson.getLong("mills"))
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
extendedBolus.durationInMinutes = trJson.getInt("duration"); .durationInMinutes(trJson.getInt("duration"))
extendedBolus.insulin = trJson.getDouble("originalExtendedAmount"); .insulin(trJson.getDouble("originalExtendedAmount"))
extendedBolus._id = trJson.getString("_id"); ._id(trJson.getString("_id"));
if (!VirtualPumpPlugin.getFakingStatus()) { // if faking found in NS, adapt AAPS to use it too
VirtualPumpPlugin.setFakingStatus(true); if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0); updateEarliestDataChange(0);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
} }
@ -941,8 +983,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
extendedBolus.durationInMinutes = 0; extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0; extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id"); extendedBolus._id = trJson.getString("_id");
if (!VirtualPumpPlugin.getFakingStatus()) { // if faking found in NS, adapt AAPS to use it too
VirtualPumpPlugin.setFakingStatus(true); if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0); updateEarliestDataChange(0);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
} }
@ -974,6 +1017,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteTempBasalById(String _id) { public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id); TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) { if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored); delete(stored);
updateEarliestDataChange(stored.date); updateEarliestDataChange(stored.date);
@ -1005,22 +1049,33 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public boolean createOrUpdate(ExtendedBolus extendedBolus) { public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try { try {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
ExtendedBolus old; ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date); extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) { if (extendedBolus.source == Source.PUMP) {
// check for changed from pump change in NS // if pumpId == 0 do not check for existing pumpId
// used with pumps without history
// and insight where record as added first without pumpId
// and then is record updated with pumpId
if (extendedBolus.pumpId == 0) {
getDaoExtendedBolus().createOrUpdate(extendedBolus);
} else {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder(); QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where(); Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId); where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare(); PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery); List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) { if (trList.size() > 1) {
// do nothing, pump history record cannot be changed log.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId);
return false; return false;
} }
getDaoExtendedBolus().create(extendedBolus); getDaoExtendedBolus().createOrUpdate(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); }
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
@ -1033,7 +1088,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus); old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old); getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString()); if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1055,7 +1111,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus); old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old); getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString()); if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1064,14 +1121,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
getDaoExtendedBolus().create(extendedBolus); getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
} }
if (extendedBolus.source == Source.USER) { if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus); getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
@ -1111,6 +1170,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteExtendedBolusById(String _id) { public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id); ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) { if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored); delete(stored);
updateEarliestDataChange(stored.date); updateEarliestDataChange(stored.date);
@ -1164,6 +1224,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleExtendedBolusChange() { private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange"); log.debug("Firing EventExtendedBolusChange");
MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange())); MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null) if (earliestDataChange != null)
@ -1304,11 +1365,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (list.size() == 1) { if (list.size() == 1) {
CareportalEvent record = list.get(0); CareportalEvent record = list.get(0);
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Removing CareportalEvent record from database: " + record.log()); log.debug("Removing CareportalEvent record from database: " + record.toString());
delete(record); delete(record);
} else { } else {
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("CareportalEvent not found database: " + _id); log.debug("CareportalEvent not found database: " + _id);
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -1328,12 +1389,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (list.size() == 0) { if (list.size() == 0) {
careportalEvent = new CareportalEvent(); careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT; careportalEvent.source = Source.NIGHTSCOUT;
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Adding CareportalEvent record to database: " + trJson.toString()); log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add // Record does not exists. add
} else if (list.size() == 1) { } else if (list.size() == 1) {
careportalEvent = list.get(0); careportalEvent = list.get(0);
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Updating CareportalEvent record in database: " + trJson.toString()); log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else { } else {
log.error("Something went wrong"); log.error("Something went wrong");
@ -1352,6 +1413,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleCareportalEventChange() { private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange"); log.debug("Firing scheduleCareportalEventChange");
MainApp.bus().post(new EventCareportalEventChange()); MainApp.bus().post(new EventCareportalEventChange());
scheduledCareportalEventPost = null; scheduledCareportalEventPost = null;
@ -1385,6 +1447,24 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<>(); return new ArrayList<>();
} }
public List<ProfileSwitch> getProfileSwitchEventsFromTime(long mills, boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public boolean createOrUpdate(ProfileSwitch profileSwitch) { public boolean createOrUpdate(ProfileSwitch profileSwitch) {
try { try {
ProfileSwitch old; ProfileSwitch old;
@ -1398,6 +1478,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch); getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
return true; return true;
@ -1417,6 +1498,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch); old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old); getDaoProfileSwitch().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
return true; return true;
@ -1426,12 +1508,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// look for already added percentage from NS // look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName); profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
getDaoProfileSwitch().create(profileSwitch); getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
return true; return true;
} }
if (profileSwitch.source == Source.USER) { if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch); getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
return true; return true;
@ -1454,6 +1538,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleProfileSwitchChange() { private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventProfileSwitchChange"); log.debug("Firing EventProfileSwitchChange");
MainApp.bus().post(new EventReloadProfileSwitchData()); MainApp.bus().post(new EventReloadProfileSwitchData());
MainApp.bus().post(new EventProfileSwitchChange()); MainApp.bus().post(new EventProfileSwitchChange());
@ -1499,22 +1584,32 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (trJson.has("profileJson")) if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson"); profileSwitch.profileJson = trJson.getString("profileJson");
else { else {
ProfileStore store = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile(); ProfileInterface profileInterface = MainApp.getConfigBuilder().getActiveProfileInterface();
if (profileInterface != null) {
ProfileStore store = profileInterface.getProfile();
if (store != null) { if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName); Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) { if (profile != null) {
profileSwitch.profileJson = profile.getData().toString(); profileSwitch.profileJson = profile.getData().toString();
if (L.isEnabled(L.DATABASE))
log.debug("Profile switch prefilled with JSON from local store"); log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS // Update data in NS
NSUpload.updateProfileSwitch(profileSwitch); NSUpload.updateProfileSwitch(profileSwitch);
} else { } else {
if (L.isEnabled(L.DATABASE))
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return; return;
} }
} else { } else {
if (L.isEnabled(L.DATABASE))
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return; return;
} }
} else {
if (L.isEnabled(L.DATABASE))
log.debug("No active profile interface. Ignoring: " + trJson.toString());
return;
}
} }
if (trJson.has("profilePlugin")) if (trJson.has("profilePlugin"))
profileSwitch.profilePlugin = trJson.getString("profilePlugin"); profileSwitch.profilePlugin = trJson.getString("profilePlugin");
@ -1527,6 +1622,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteProfileSwitchById(String _id) { public void deleteProfileSwitchById(String _id) {
ProfileSwitch stored = findProfileSwitchById(_id); ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) { if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
delete(stored); delete(stored);
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();

View file

@ -10,6 +10,8 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 27.02.2016. * Created by mike on 27.02.2016.
* <p> * <p>
@ -17,7 +19,7 @@ import org.slf4j.LoggerFactory;
*/ */
@DatabaseTable(tableName = DatabaseHelper.DATABASE_DBREQUESTS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_DBREQUESTS)
public class DbRequest { public class DbRequest {
private static Logger log = LoggerFactory.getLogger(DbRequest.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public String nsClientID = null; public String nsClientID = null;

View file

@ -21,6 +21,7 @@ import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -36,7 +37,7 @@ import info.nightscout.utils.Round;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_EXTENDEDBOLUSES) @DatabaseTable(tableName = DatabaseHelper.DATABASE_EXTENDEDBOLUSES)
public class ExtendedBolus implements Interval, DataPointWithLabelInterface { public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(ExtendedBolus.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;
@ -69,6 +70,36 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
this.date = date; this.date = date;
} }
public ExtendedBolus date(long date) {
this.date = date;
return this;
}
public ExtendedBolus insulin(double insulin) {
this.insulin = insulin;
return this;
}
public ExtendedBolus pumpId(long pumpId) {
this.pumpId = pumpId;
return this;
}
public ExtendedBolus source(int source) {
this.source = source;
return this;
}
public ExtendedBolus durationInMinutes(int durationInMinutes) {
this.durationInMinutes = durationInMinutes;
return this;
}
public ExtendedBolus _id(String _id) {
this._id = _id;
return this;
}
public boolean isEqual(ExtendedBolus other) { public boolean isEqual(ExtendedBolus other) {
if (date != other.date) { if (date != other.date) {
return false; return false;
@ -93,13 +124,13 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
} }
public static ExtendedBolus createFromJson(JSONObject json) { public static ExtendedBolus createFromJson(JSONObject json) {
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.source = Source.NIGHTSCOUT; .source(Source.NIGHTSCOUT)
extendedBolus.date = JsonHelper.safeGetLong(json, "mills"); .date(JsonHelper.safeGetLong(json, "mills"))
extendedBolus.durationInMinutes = JsonHelper.safeGetInt(json, "duration"); .durationInMinutes(JsonHelper.safeGetInt(json, "duration"))
extendedBolus.insulin = JsonHelper.safeGetDouble(json, "relative") / 60 * extendedBolus.durationInMinutes; .insulin(JsonHelper.safeGetDouble(json, "relative") / 60 * JsonHelper.safeGetInt(json, "duration"))
extendedBolus._id = JsonHelper.safeGetString(json, "_id"); ._id(JsonHelper.safeGetString(json, "_id"))
extendedBolus.pumpId = JsonHelper.safeGetLong(json, "pumpId"); .pumpId(JsonHelper.safeGetLong(json, "pumpId"));
return extendedBolus; return extendedBolus;
} }
// -------- Interval interface --------- // -------- Interval interface ---------
@ -166,7 +197,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
// -------- Interval interface end --------- // -------- Interval interface end ---------
public String log() { public String log() {
return "Bolus{" + return "ExtendedBolus{" +
"date= " + date + "date= " + date +
", date= " + DateUtil.dateAndTimeString(date) + ", date= " + DateUtil.dateAndTimeString(date) +
", isValid=" + isValid + ", isValid=" + isValid +

View file

@ -11,12 +11,14 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -24,10 +26,11 @@ import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin; import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.T;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES) @DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface { public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(ProfileSwitch.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;
@ -217,6 +220,26 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} }
public static boolean isEvent5minBack(List<ProfileSwitch> list, long time, boolean zeroDurationOnly) {
for (int i = 0; i < list.size(); i++) {
ProfileSwitch event = list.get(i);
if (event.date <= time && event.date > (time - T.mins(5).msecs())) {
if (zeroDurationOnly) {
if (event.durationInMinutes == 0) {
if (L.isEnabled(L.DATABASE))
log.debug("Found ProfileSwitch event for time: " + DateUtil.dateAndTimeFullString(time) + " " + event.toString());
return true;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("Found ProfileSwitch event for time: " + DateUtil.dateAndTimeFullString(time) + " " + event.toString());
return true;
}
}
}
return false;
}
// -------- Interval interface end --------- // -------- Interval interface end ---------
// ----------------- DataPointInterface -------------------- // ----------------- DataPointInterface --------------------

View file

@ -8,6 +8,8 @@ import org.slf4j.LoggerFactory;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 20.09.2017. * Created by mike on 20.09.2017.
*/ */
@ -15,7 +17,7 @@ import java.util.Objects;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS)
public class TDD { public class TDD {
private static Logger log = LoggerFactory.getLogger(TDD.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;

View file

@ -11,12 +11,13 @@ import java.util.Objects;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS)
public class TempTarget implements Interval { public class TempTarget implements Interval {
private static Logger log = LoggerFactory.getLogger(TempTarget.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;

View file

@ -15,7 +15,9 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -27,7 +29,7 @@ import info.nightscout.utils.SP;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS)
public class TemporaryBasal implements Interval { public class TemporaryBasal implements Interval {
private static Logger log = LoggerFactory.getLogger(TemporaryBasal.class); private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true) @DatabaseField(id = true)
public long date; public long date;
@ -93,7 +95,7 @@ public class TemporaryBasal implements Interval {
} }
public TemporaryBasal(ExtendedBolus extendedBolus) { public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = MainApp.getConfigBuilder().getProfile(extendedBolus.date).getBasal(extendedBolus.date); double basal = ProfileFunctions.getInstance().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date; this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid; this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source; this.source = extendedBolus.source;
@ -103,6 +105,7 @@ public class TemporaryBasal implements Interval {
this.isFakeExtended = true; this.isFakeExtended = true;
this.netExtendedRate = extendedBolus.absoluteRate(); this.netExtendedRate = extendedBolus.absoluteRate();
this.absoluteRate = basal + extendedBolus.absoluteRate(); this.absoluteRate = basal + extendedBolus.absoluteRate();
this.pumpId = extendedBolus.pumpId;
} }
public TemporaryBasal clone() { public TemporaryBasal clone() {
@ -219,7 +222,7 @@ public class TemporaryBasal implements Interval {
public IobTotal iobCalc(long time, Profile profile) { public IobTotal iobCalc(long time, Profile profile) {
if(isFakeExtended){ if (isFakeExtended) {
log.error("iobCalc should only be called on Extended boluses separately"); log.error("iobCalc should only be called on Extended boluses separately");
return new IobTotal(time); return new IobTotal(time);
} }
@ -290,7 +293,7 @@ public class TemporaryBasal implements Interval {
} }
public double tempBasalConvertedToAbsolute(long time, Profile profile) { public double tempBasalConvertedToAbsolute(long time, Profile profile) {
if(isFakeExtended){ if (isFakeExtended) {
return profile.getBasal(time) + netExtendedRate; return profile.getBasal(time) + netExtendedRate;
} else if (isAbsolute) { } else if (isAbsolute) {
return absoluteRate; return absoluteRate;
@ -299,6 +302,16 @@ public class TemporaryBasal implements Interval {
} }
} }
public int tempBasalConvertedToPercent(long time, Profile profile) {
if (isFakeExtended) {
return (int) ((profile.getBasal(time) + netExtendedRate) / profile.getBasal(time)) * 100;
} else if (isAbsolute) {
return (int) (absoluteRate / profile.getBasal(time)) * 100;
} else {
return percentRate;
}
}
public String toString() { public String toString() {
return "TemporaryBasal{" + return "TemporaryBasal{" +
"date=" + date + "date=" + date +
@ -316,12 +329,12 @@ public class TemporaryBasal implements Interval {
} }
public String toStringFull() { public String toStringFull() {
if(isFakeExtended){ if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal(); Double currentBasalRate = profile.getBasal();
double rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); double rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
return getCalcuatedPercentageIfNeeded() + DecimalFormatter.to2Decimal(rate) + "U/h ("+DecimalFormatter.to2Decimal(netExtendedRate)+"E) @" + return getCalcuatedPercentageIfNeeded() + DecimalFormatter.to2Decimal(rate) + "U/h (" + DecimalFormatter.to2Decimal(netExtendedRate) + "E) @" +
DateUtil.timeString(date) + DateUtil.timeString(date) +
" " + getRealDuration() + "/" + durationInMinutes + "'"; " " + getRealDuration() + "/" + durationInMinutes + "'";
} else if (isAbsolute) { } else if (isAbsolute) {
@ -340,19 +353,19 @@ public class TemporaryBasal implements Interval {
double rate = 0d; double rate = 0d;
if (isFakeExtended) { if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal(); Double currentBasalRate = profile.getBasal();
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
} else if (isAbsolute){ } else if (isAbsolute) {
rate = absoluteRate; rate = absoluteRate;
} }
if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){ if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if(profile != null) { if (profile != null) {
double basal = profile.getBasal(); double basal = profile.getBasal();
if(basal != 0){ if (basal != 0) {
return Math.round(rate*100d/basal) + "%"; return Math.round(rate * 100d / basal) + "%";
} }
} }
} }
@ -362,24 +375,24 @@ public class TemporaryBasal implements Interval {
} }
} }
private String getCalcuatedPercentageIfNeeded(){ private String getCalcuatedPercentageIfNeeded() {
if (isAbsolute || isFakeExtended) { if (isAbsolute || isFakeExtended) {
double rate = 0d; double rate = 0d;
if (isFakeExtended) { if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal(); Double currentBasalRate = profile.getBasal();
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
} else if (isAbsolute){ } else if (isAbsolute) {
rate = absoluteRate; rate = absoluteRate;
} }
if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){ if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if(profile != null) { if (profile != null) {
double basal = profile.getBasal(); double basal = profile.getBasal();
if(basal != 0){ if (basal != 0) {
return Math.round(rate*100d/basal) + "% "; return Math.round(rate * 100d / basal) + "% ";
} }
} }
} }
@ -392,10 +405,10 @@ public class TemporaryBasal implements Interval {
double rate = 0d; double rate = 0d;
if (isFakeExtended) { if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal(); Double currentBasalRate = profile.getBasal();
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
} else if (isAbsolute){ } else if (isAbsolute) {
rate = absoluteRate; rate = absoluteRate;
} }
return DecimalFormatter.to2Decimal(rate) + "U/h "; return DecimalFormatter.to2Decimal(rate) + "U/h ";

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.events;
/** Base class for events to update the UI, mostly a specific tab. */
public class EventAcceptOpenLoopChange extends Event {
}

View file

@ -10,9 +10,10 @@ import info.nightscout.androidaps.R;
public class EventPumpStatusChanged extends Event { public class EventPumpStatusChanged extends Event {
public static final int CONNECTING = 0; public static final int CONNECTING = 0;
public static final int CONNECTED = 1; public static final int CONNECTED = 1;
public static final int PERFORMING = 2; public static final int HANDSHAKING = 2;
public static final int DISCONNECTING = 3; public static final int PERFORMING = 3;
public static final int DISCONNECTED = 4; public static final int DISCONNECTING = 4;
public static final int DISCONNECTED = 5;
public int sStatus = DISCONNECTED; public int sStatus = DISCONNECTED;
public int sSecondsElapsed = 0; public int sSecondsElapsed = 0;
@ -47,6 +48,8 @@ public class EventPumpStatusChanged extends Event {
public String textStatus() { public String textStatus() {
if (sStatus == CONNECTING) if (sStatus == CONNECTING)
return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed); return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed);
else if (sStatus == HANDSHAKING)
return MainApp.gs(R.string.handshaking);
else if (sStatus == CONNECTED) else if (sStatus == CONNECTED)
return MainApp.gs(R.string.connected); return MainApp.gs(R.string.connected);
else if (sStatus == PERFORMING) else if (sStatus == PERFORMING)

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import java.util.Date;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
/** /**
@ -9,7 +7,7 @@ import info.nightscout.androidaps.plugins.Loop.APSResult;
*/ */
public interface APSInterface { public interface APSInterface {
public APSResult getLastAPSResult(); public APSResult getLastAPSResult();
public Date getLastAPSRun(); public long getLastAPSRun();
public void invoke(String initiator, boolean tempBasalFallback); public void invoke(String initiator, boolean tempBasalFallback);
} }

View file

@ -1,8 +1,12 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import android.content.Intent;
/** /**
* Created by mike on 20.06.2016. * Created by mike on 20.06.2016.
*/ */
public interface BgSourceInterface { public interface BgSourceInterface {
boolean advancedFilteringSupported(); boolean advancedFilteringSupported();
void handleNewData(Intent intent);
} }

View file

@ -6,12 +6,14 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 19.03.2018. * Created by mike on 19.03.2018.
*/ */
public class Constraint<T extends Comparable> { public class Constraint<T extends Comparable> {
private static Logger log = LoggerFactory.getLogger(Constraint.class); private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
T value; T value;
T originalValue; T originalValue;
@ -35,18 +37,35 @@ public class Constraint<T extends Comparable> {
public Constraint<T> set(T value) { public Constraint<T> set(T value) {
this.value = value; this.value = value;
this.originalValue = value; this.originalValue = value;
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Setting value " + value);
return this; return this;
} }
public Constraint<T> set(T value, String reason, Object from) { public Constraint<T> set(T value, String reason, Object from) {
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]");
this.value = value; this.value = value;
addReason(reason, from); addReason(reason, from);
addMostLimingReason(reason, from); addMostLimingReason(reason, from);
return this; return this;
} }
public Constraint<T> setIfDifferent(T value, String reason, Object from) {
if (!this.value.equals(value)) {
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]");
this.value = value;
addReason(reason, from);
addMostLimingReason(reason, from);
}
return this;
}
public Constraint<T> setIfSmaller(T value, String reason, Object from) { public Constraint<T> setIfSmaller(T value, String reason, Object from) {
if (value.compareTo(this.value) < 0) { if (value.compareTo(this.value) < 0) {
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]");
this.value = value; this.value = value;
mostLimiting.clear(); mostLimiting.clear();
addMostLimingReason(reason, from); addMostLimingReason(reason, from);
@ -59,6 +78,8 @@ public class Constraint<T extends Comparable> {
public Constraint<T> setIfGreater(T value, String reason, Object from) { public Constraint<T> setIfGreater(T value, String reason, Object from) {
if (value.compareTo(this.value) > 0) { if (value.compareTo(this.value) > 0) {
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]");
this.value = value; this.value = value;
mostLimiting.clear(); mostLimiting.clear();
addMostLimingReason(reason, from); addMostLimingReason(reason, from);
@ -69,13 +90,17 @@ public class Constraint<T extends Comparable> {
return this; return this;
} }
private String translateFrom(Object from) {
return from.getClass().getSimpleName().replace("Plugin", "");
}
public Constraint addReason(String reason, Object from) { public Constraint addReason(String reason, Object from) {
reasons.add(from.getClass().getSimpleName().replace("Plugin", "") + ": " + reason); reasons.add(translateFrom(from) + ": " + reason);
return this; return this;
} }
public Constraint addMostLimingReason(String reason, Object from) { public Constraint addMostLimingReason(String reason, Object from) {
mostLimiting.add(from.getClass().getSimpleName().replace("Plugin", "") + ": " + reason); mostLimiting.add(translateFrom(from) + ": " + reason);
return this; return this;
} }
@ -86,6 +111,7 @@ public class Constraint<T extends Comparable> {
if (count++ != 0) sb.append("\n"); if (count++ != 0) sb.append("\n");
sb.append(r); sb.append(r);
} }
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString());
return sb.toString(); return sb.toString();
} }
@ -101,6 +127,7 @@ public class Constraint<T extends Comparable> {
if (count++ != 0) sb.append("\n"); if (count++ != 0) sb.append("\n");
sb.append(r); sb.append(r);
} }
if (L.isEnabled(L.CONSTRAINTS))
log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString());
return sb.toString(); return sb.toString();
} }
@ -110,7 +137,7 @@ public class Constraint<T extends Comparable> {
} }
public void copyReasons(Constraint<?> another) { public void copyReasons(Constraint<?> another) {
for (String s: another.getReasonList()) { for (String s : another.getReasonList()) {
reasons.add(s); reasons.add(s);
} }
} }

View file

@ -43,6 +43,10 @@ public interface ConstraintsInterface {
return insulin; return insulin;
} }
default Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
return insulin;
}
default Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) { default Constraint<Integer> applyCarbsConstraints(Constraint<Integer> carbs) {
return carbs; return carbs;
} }

View file

@ -7,14 +7,16 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.queue.CommandQueue;
/** /**
* Created by mike on 09.06.2016. * Created by mike on 09.06.2016.
*/ */
public abstract class PluginBase { public abstract class PluginBase {
private static Logger log = LoggerFactory.getLogger(PluginBase.class); private static Logger log = LoggerFactory.getLogger(L.CORE);
public enum State { public enum State {
NOT_INITIALIZED, NOT_INITIALIZED,
@ -113,14 +115,16 @@ public abstract class PluginBase {
if (state != State.ENABLED) { if (state != State.ENABLED) {
onStateChange(type, state, State.ENABLED); onStateChange(type, state, State.ENABLED);
state = State.ENABLED; state = State.ENABLED;
if (L.isEnabled(L.CORE))
log.debug("Starting: " + getName()); log.debug("Starting: " + getName());
onStart(); onStart();
} }
} else { // disabling plugin } else { // disabling plugin
if (state == State.ENABLED) { if (state == State.ENABLED) {
onStateChange(type, state, State.ENABLED); onStateChange(type, state, State.DISABLED);
state = State.DISABLED; state = State.DISABLED;
onStop(); onStop();
if (L.isEnabled(L.CORE))
log.debug("Stopping: " + getName()); log.debug("Stopping: " + getName());
} }
} }
@ -165,7 +169,9 @@ public abstract class PluginBase {
if (getType() == PluginType.PUMP) { if (getType() == PluginType.PUMP) {
new Thread(() -> { new Thread(() -> {
SystemClock.sleep(3000); SystemClock.sleep(3000);
ConfigBuilderPlugin.getCommandQueue().readStatus("Pump driver changed.", null); CommandQueue commandQueue = ConfigBuilderPlugin.getCommandQueue();
if (commandQueue != null)
commandQueue.readStatus("Pump driver changed.", null);
}).start(); }).start();
} }
} }

View file

@ -1,54 +1,62 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpCapability;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpTempBasalType;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
/** /**
* Created by mike on 08.12.2016. * Created by mike on 08.12.2016.
*/ */
public class PumpDescription { public class PumpDescription {
public PumpType pumpType = PumpType.GenericAAPS;
public PumpDescription () {
resetSettings();
}
public static final int NONE = 0; public static final int NONE = 0;
public static final int PERCENT = 0x01; public static final int PERCENT = 0x01;
public static final int ABSOLUTE = 0x02; public static final int ABSOLUTE = 0x02;
public boolean isBolusCapable = true; public boolean isBolusCapable;
public double bolusStep = 0.1d; public double bolusStep;
public boolean isExtendedBolusCapable = true; public boolean isExtendedBolusCapable;
public double extendedBolusStep = 0.1d; public double extendedBolusStep;
public double extendedBolusDurationStep = 30; public double extendedBolusDurationStep;
public double extendedBolusMaxDuration = 12 * 60; public double extendedBolusMaxDuration;
public boolean isTempBasalCapable = true; public boolean isTempBasalCapable;
public int tempBasalStyle = PERCENT; public int tempBasalStyle;
public int maxTempPercent = 200; public int maxTempPercent;
public int tempPercentStep = 10; public int tempPercentStep;
public double maxTempAbsolute = 10; public double maxTempAbsolute;
public double tempAbsoluteStep = 0.05d; public double tempAbsoluteStep;
public int tempDurationStep = 60; public int tempDurationStep;
public boolean tempDurationStep15mAllowed = false; public boolean tempDurationStep15mAllowed;
public boolean tempDurationStep30mAllowed = false; public boolean tempDurationStep30mAllowed;
public int tempMaxDuration = 12 * 60; public int tempMaxDuration;
public boolean isSetBasalProfileCapable;
public double basalStep;
public double basalMinimumRate;
public double basalMaximumRate;
public boolean isRefillingCapable;
public boolean storesCarbInfo;
public boolean is30minBasalRatesCapable;
public boolean supportsTDDs;
public boolean needsManualTDDLoad;
public boolean isSetBasalProfileCapable = true; public void resetSettings() {
public double basalStep = 0.01d;
public double basalMinimumRate = 0.04d;
public double basalMaximumRate = 25d;
public boolean isRefillingCapable = false;
public boolean storesCarbInfo = true;
public boolean is30minBasalRatesCapable = false;
public boolean supportsTDDs = false;
public boolean needsManualTDDLoad = true;
public void resetSettings()
{
isBolusCapable = true; isBolusCapable = true;
bolusStep = 0.1d; bolusStep = 0.1d;
@ -59,26 +67,73 @@ public class PumpDescription {
isTempBasalCapable = true; isTempBasalCapable = true;
tempBasalStyle = PERCENT; tempBasalStyle = PERCENT;
maxTempPercent = 200; maxTempPercent = 200;
tempPercentStep = 10; tempPercentStep = 10;
maxTempAbsolute = 10; maxTempAbsolute = 10;
tempAbsoluteStep = 0.05d; tempAbsoluteStep = 0.05d;
tempDurationStep = 60; tempDurationStep = 60;
tempMaxDuration = 12 * 60; tempMaxDuration = 12 * 60;
tempDurationStep15mAllowed = false;
tempDurationStep30mAllowed = false;
isSetBasalProfileCapable = true; isSetBasalProfileCapable = true;
basalStep = 0.01d; basalStep = 0.01d;
basalMinimumRate = 0.04d; basalMinimumRate = 0.04d;
basalMaximumRate = 25d;
is30minBasalRatesCapable = false;
isRefillingCapable = false; isRefillingCapable = false;
storesCarbInfo = true; storesCarbInfo = true;
supportsTDDs = false;
needsManualTDDLoad = true;
} }
public void setPumpDescription(PumpType pumpType) {
resetSettings();
this.pumpType = pumpType;
PumpCapability pumpCapability = pumpType.getPumpCapability();
isBolusCapable = pumpCapability.hasCapability(PumpCapability.Bolus);
bolusStep = pumpType.getBolusSize();
isExtendedBolusCapable = pumpCapability.hasCapability(PumpCapability.ExtendedBolus);
extendedBolusStep = pumpType.getExtendedBolusSettings().getStep();
extendedBolusDurationStep = pumpType.getExtendedBolusSettings().getDurationStep();
extendedBolusMaxDuration = pumpType.getExtendedBolusSettings().getMaxDuration();
isTempBasalCapable = pumpCapability.hasCapability(PumpCapability.TempBasal);
if (pumpType.getPumpTempBasalType() == PumpTempBasalType.Percent) {
tempBasalStyle = PERCENT;
maxTempPercent = pumpType.getTbrSettings().getMaxDose().intValue();
tempPercentStep = (int) pumpType.getTbrSettings().getStep();
} else {
tempBasalStyle = ABSOLUTE;
maxTempAbsolute = pumpType.getTbrSettings().getMaxDose();
tempAbsoluteStep = pumpType.getTbrSettings().getStep();
}
tempDurationStep = pumpType.getTbrSettings().getDurationStep();
tempMaxDuration = pumpType.getTbrSettings().getMaxDuration();
tempDurationStep15mAllowed = pumpType.getSpecialBasalDurations()
.hasCapability(PumpCapability.BasalRate_Duration15minAllowed);
tempDurationStep30mAllowed = pumpType.getSpecialBasalDurations()
.hasCapability(PumpCapability.BasalRate_Duration30minAllowed);
isSetBasalProfileCapable = pumpCapability.hasCapability(PumpCapability.BasalProfileSet);
basalStep = pumpType.getBaseBasalStep();
basalMinimumRate = pumpType.getBaseBasalMinValue();
isRefillingCapable = pumpCapability.hasCapability(PumpCapability.Refill);
storesCarbInfo = pumpCapability.hasCapability(PumpCapability.StoreCarbInfo);
supportsTDDs = pumpCapability.hasCapability(PumpCapability.TDD);
needsManualTDDLoad = pumpCapability.hasCapability(PumpCapability.ManualTDDLoad);
is30minBasalRatesCapable = pumpCapability.hasCapability(PumpCapability.BasalRate30min);
}
} }

View file

@ -2,8 +2,6 @@ package info.nightscout.androidaps.interfaces;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
@ -13,11 +11,13 @@ import info.nightscout.androidaps.data.PumpEnactResult;
*/ */
public interface PumpInterface { public interface PumpInterface {
boolean isInitialized(); boolean isInitialized(); // true if pump status has been read and is ready to accept commands
boolean isSuspended(); boolean isSuspended(); // true if suspended (not delivering insulin)
boolean isBusy(); boolean isBusy(); // if true pump is not ready to accept commands right now
boolean isConnected(); boolean isConnected(); // true if BT connection is established
boolean isConnecting(); boolean isConnecting(); // true if BT connection is in progress
boolean isHandshakeInProgress(); // true if BT is connected but initial handshake is still in progress
void finishHandshaking(); // set initial handshake completed
void connect(String reason); void connect(String reason);
void disconnect(String reason); void disconnect(String reason);
@ -29,7 +29,7 @@ public interface PumpInterface {
PumpEnactResult setNewBasalProfile(Profile profile); PumpEnactResult setNewBasalProfile(Profile profile);
boolean isThisProfileSet(Profile profile); boolean isThisProfileSet(Profile profile);
Date lastDataTime(); long lastDataTime();
double getBaseBasalRate(); // base basal rate, not temp basal double getBaseBasalRate(); // base basal rate, not temp basal

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
/** /**
* Created by mike on 24.06.2017. * Created by mike on 24.06.2017.
@ -11,6 +12,6 @@ public interface SensitivityInterface {
double MIN_HOURS = 1; double MIN_HOURS = 1;
double MIN_HOURS_FULL_AUTOSENS = 4; double MIN_HOURS_FULL_AUTOSENS = 4;
AutosensResult detectSensitivity(long fromTime, long toTime); AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime);
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.utils; package info.nightscout.androidaps.logging;
import android.os.Bundle; import android.os.Bundle;

View file

@ -0,0 +1,123 @@
package info.nightscout.androidaps.logging;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.utils.SP;
public class L {
public static class LogElement {
public String name;
boolean defaultValue;
public boolean enabled;
boolean requiresRestart = false;
LogElement(String name, boolean defaultValue) {
this.name = name;
this.defaultValue = defaultValue;
enabled = SP.getBoolean(getSPName(), defaultValue);
}
LogElement(String name, boolean defaultValue, boolean requiresRestart) {
this.name = name;
this.defaultValue = defaultValue;
this.requiresRestart = requiresRestart;
enabled = SP.getBoolean(getSPName(), defaultValue);
}
LogElement(boolean defaultValue) {
this.name = "NONEXISTING";
this.defaultValue = defaultValue;
enabled = defaultValue;
}
private String getSPName() {
return "log_" + name;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
SP.putBoolean(getSPName(), enabled);
}
void resetToDefault() {
setEnabled(defaultValue);
}
}
private static List<LogElement> logElements;
static {
initialize();
}
private static LogElement findByName(String name) {
for (LogElement element : logElements) {
if (element.name.equals(name))
return element;
}
return new LogElement(false);
}
public static boolean isEnabled(String name) {
return findByName(name).enabled;
}
public static List<LogElement> getLogElements() {
return logElements;
}
public static void resetToDefaults() {
for (LogElement element : logElements) {
element.resetToDefault();
}
}
public static final String CORE = "CORE";
public static final String AUTOSENS = "AUTOSENS";
public static final String EVENTS = "EVENTS";
public static final String BGSOURCE = "BGSOURCE";
public static final String OVERVIEW = "OVERVIEW";
public static final String NOTIFICATION = "NOTIFICATION";
public static final String DATASERVICE = "DATASERVICE";
public static final String DATABASE = "DATABASE";
public static final String DATAFOOD = "DATAFOOD";
public static final String DATATREATMENTS = "DATATREATMENTS";
public static final String NSCLIENT = "NSCLIENT";
public static final String CONSTRAINTS = "CONSTRAINTS";
public static final String PUMP = "PUMP";
public static final String PUMPQUEUE = "PUMPQUEUE";
public static final String PUMPCOMM = "PUMPCOMM";
public static final String PUMPBTCOMM = "PUMPBTCOMM";
public static final String APS = "APS";
public static final String PROFILE = "PROFILE";
public static final String CONFIGBUILDER = "CONFIGBUILDER";
public static final String UI = "UI";
private static void initialize() {
logElements = new ArrayList<>();
logElements.add(new LogElement(APS, true));
logElements.add(new LogElement(AUTOSENS, true));
logElements.add(new LogElement(BGSOURCE, true));
logElements.add(new LogElement(CONFIGBUILDER, true));
logElements.add(new LogElement(CONSTRAINTS, true));
logElements.add(new LogElement(CORE, true));
logElements.add(new LogElement(DATABASE, true));
logElements.add(new LogElement(DATAFOOD, true));
logElements.add(new LogElement(DATASERVICE, true));
logElements.add(new LogElement(DATATREATMENTS, true));
logElements.add(new LogElement(EVENTS, false, true));
logElements.add(new LogElement(NOTIFICATION, true));
logElements.add(new LogElement(NSCLIENT, true));
logElements.add(new LogElement(OVERVIEW, true));
logElements.add(new LogElement(PROFILE, true));
logElements.add(new LogElement(PUMP, true));
logElements.add(new LogElement(PUMPBTCOMM, false));
logElements.add(new LogElement(PUMPCOMM, true));
logElements.add(new LogElement(PUMPQUEUE, true));
logElements.add(new LogElement(UI, true));
}
}

View file

@ -14,10 +14,10 @@ import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.HistoryBrowseActivity; import info.nightscout.androidaps.activities.HistoryBrowseActivity;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.TDDStatsActivity; import info.nightscout.androidaps.activities.TDDStatsActivity;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;
@ -33,6 +33,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SingleClickButton; import info.nightscout.utils.SingleClickButton;
@ -87,7 +88,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasalCancel.setOnClickListener(this); tempBasalCancel.setOnClickListener(this);
fill.setOnClickListener(this); fill.setOnClickListener(this);
history.setOnClickListener(this); history.setOnClickListener(this);
history.setVisibility(MainApp.devBranch ? View.VISIBLE : View.GONE);
tddStats.setOnClickListener(this); tddStats.setOnClickListener(this);
updateGUI(); updateGUI();
@ -132,7 +132,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
profileSwitch.setVisibility(View.GONE); profileSwitch.setVisibility(View.GONE);
} }
if (MainApp.getConfigBuilder().getProfile() == null) { if (ProfileFunctions.getInstance().getProfile() == null) {
tempTarget.setVisibility(View.GONE); tempTarget.setVisibility(View.GONE);
extendedBolus.setVisibility(View.GONE); extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE); extendedBolusCancel.setVisibility(View.GONE);

View file

@ -39,7 +39,7 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.NumberPicker; import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
@ -91,7 +91,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.actions_fill_dialog, null, false); View view = inflater.inflate(R.layout.actions_fill_dialog, container, false);
view.findViewById(R.id.ok).setOnClickListener(this); view.findViewById(R.id.ok).setOnClickListener(this);
view.findViewById(R.id.cancel).setOnClickListener(this); view.findViewById(R.id.cancel).setOnClickListener(this);
@ -184,7 +184,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
if (insulinAfterConstraints > 0) { if (insulinAfterConstraints > 0) {
confirmMessage.add(MainApp.gs(R.string.fillwarning)); confirmMessage.add(MainApp.gs(R.string.fillwarning));
confirmMessage.add(""); confirmMessage.add("");
confirmMessage.add(MainApp.gs(R.string.bolus) + ": " + "<font color='" + MainApp.gc(R.color.colorCarbsButton) + "'>" + insulinAfterConstraints + "U" + "</font>"); confirmMessage.add(MainApp.gs(R.string.bolus) + ": " + "<font color='" + MainApp.gc(R.color.colorCarbsButton) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + "U" + "</font>");
if (!insulinAfterConstraints.equals(insulin)) if (!insulinAfterConstraints.equals(insulin))
confirmMessage.add("<font color='" + MainApp.gc(R.color.low) + "'>" + MainApp.gs(R.string.bolusconstraintapplied) + "</font>"); confirmMessage.add("<font color='" + MainApp.gc(R.color.low) + "'>" + MainApp.gs(R.string.bolusconstraintapplied) + "</font>");
} }

View file

@ -44,7 +44,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false); View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false);
Double maxInsulin = MainApp.getConstraintChecker().getMaxBolusAllowed().value(); Double maxInsulin = MainApp.getConstraintChecker().getMaxExtendedBolusAllowed().value();
editInsulin = (NumberPicker) view.findViewById(R.id.overview_newextendedbolus_insulin); editInsulin = (NumberPicker) view.findViewById(R.id.overview_newextendedbolus_insulin);
editInsulin.setParams(0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false); editInsulin.setParams(0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false);
@ -71,10 +71,10 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
String confirmMessage = MainApp.gs(R.string.setextendedbolusquestion); String confirmMessage = MainApp.gs(R.string.setextendedbolusquestion);
Double insulinAfterConstraint = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value(); Double insulinAfterConstraint = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value();
confirmMessage += " " + insulinAfterConstraint + " U "; confirmMessage += " " + insulinAfterConstraint + " U ";
confirmMessage += MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?"; confirmMessage += MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (insulinAfterConstraint - insulin != 0d) if (Math.abs(insulinAfterConstraint - insulin) > 0.01d)
confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied); confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
insulin = insulinAfterConstraint; insulin = insulinAfterConstraint;

View file

@ -25,6 +25,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
@ -70,7 +71,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
double tempPercentStep = pumpDescription.tempPercentStep; double tempPercentStep = pumpDescription.tempPercentStep;
basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true); basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true);
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasal = profile != null ? profile.getBasal() : 0d; Double currentBasal = profile != null ? profile.getBasal() : 0d;
basalAbsolute = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalabsoluteinput); basalAbsolute = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalabsoluteinput);
basalAbsolute.setParams(currentBasal, 0d, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, new DecimalFormat("0.00"), true); basalAbsolute.setParams(currentBasal, 0d, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, new DecimalFormat("0.00"), true);
@ -118,7 +119,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
final boolean setAsPercent = percentRadio.isChecked(); final boolean setAsPercent = percentRadio.isChecked();
int durationInMinutes = SafeParse.stringToInt(duration.getText()); int durationInMinutes = SafeParse.stringToInt(duration.getText());
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) if (profile == null)
return; return;
@ -135,7 +136,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
absolute = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(basalAbsoluteInput), profile).value(); absolute = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(basalAbsoluteInput), profile).value();
confirmMessage += "\n" + absolute + " U/h "; confirmMessage += "\n" + absolute + " U/h ";
confirmMessage += "\n" + MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?"; confirmMessage += "\n" + MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (absolute - basalAbsoluteInput != 0d) if (Math.abs(absolute - basalAbsoluteInput) > 0.01d)
confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied); confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
} }

View file

@ -100,7 +100,7 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
noProfileView = view.findViewById(R.id.profileview_noprofile); noProfileView = view.findViewById(R.id.profileview_noprofile);
butonsLayout = (LinearLayout) view.findViewById(R.id.careportal_buttons); butonsLayout = (LinearLayout) view.findViewById(R.id.careportal_buttons);
ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile(); ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface() != null ? MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() : null;
if (profileStore == null) { if (profileStore == null) {
noProfileView.setVisibility(View.VISIBLE); noProfileView.setVisibility(View.VISIBLE);
butonsLayout.setVisibility(View.GONE); butonsLayout.setVisibility(View.GONE);
@ -109,7 +109,7 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
butonsLayout.setVisibility(View.VISIBLE); butonsLayout.setVisibility(View.VISIBLE);
} }
if (Config.NSCLIENT || Config.G5UPLOADER) if (Config.NSCLIENT)
statsLayout.setVisibility(View.GONE); // visible on overview statsLayout.setVisibility(View.GONE); // visible on overview
updateGUI(); updateGUI();

View file

@ -49,13 +49,14 @@ import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DefaultValueHelper; import info.nightscout.utils.DefaultValueHelper;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.HardLimits; import info.nightscout.utils.HardLimits;
import info.nightscout.utils.JsonHelper; import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.NumberPicker; import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
@ -171,7 +172,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
view.findViewById(R.id.cancel).setOnClickListener(this); view.findViewById(R.id.cancel).setOnClickListener(this);
// profile // profile
profile = MainApp.getConfigBuilder().getProfile(); profile = ProfileFunctions.getInstance().getProfile();
profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile(); profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profileStore == null) { if (profileStore == null) {
if (options.eventType == R.id.careportal_profileswitch) { if (options.eventType == R.id.careportal_profileswitch) {
@ -186,7 +187,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
profileSpinner.setAdapter(adapter); profileSpinner.setAdapter(adapter);
// set selected to actual profile // set selected to actual profile
for (int p = 0; p < profileList.size(); p++) { for (int p = 0; p < profileList.size(); p++) {
if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName(false))) if (profileList.get(p).equals(ProfileFunctions.getInstance().getProfileName(false)))
profileSpinner.setSelection(p); profileSpinner.setSelection(p);
} }
} }
@ -206,12 +207,15 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
double defaultDuration; double defaultDuration;
double defaultTarget = 0; double defaultTarget = 0;
if (profile != null) { if (profile != null && editTemptarget.getValue() == bg) {
defaultTarget = bg; defaultTarget = bg;
} else {
//prevent changes on screen rotate
defaultTarget = editTemptarget.getValue();
} }
boolean erase = false; boolean erase = false;
String units = MainApp.getConfigBuilder().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
DefaultValueHelper helper = new DefaultValueHelper(); DefaultValueHelper helper = new DefaultValueHelper();
if (MainApp.gs(R.string.eatingsoon).equals(reasonList.get(position))) { if (MainApp.gs(R.string.eatingsoon).equals(reasonList.get(position))) {
defaultDuration = helper.determineEatingSoonTTDuration(); defaultDuration = helper.determineEatingSoonTTDuration();
@ -222,6 +226,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
} else if (MainApp.gs(R.string.hypo).equals(reasonList.get(position))) { } else if (MainApp.gs(R.string.hypo).equals(reasonList.get(position))) {
defaultDuration = helper.determineHypoTTDuration(); defaultDuration = helper.determineHypoTTDuration();
defaultTarget = helper.determineHypoTT(units); defaultTarget = helper.determineHypoTT(units);
} else if (editDuration.getValue() != 0) {
defaultDuration = editDuration.getValue();
} else { } else {
defaultDuration = 0; defaultDuration = 0;
erase = true; erase = true;
@ -258,7 +264,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true); if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true);
} }
}; };
editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput); editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput);
editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget); editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget);
if (profile == null) { if (profile == null) {
@ -271,9 +276,14 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher); editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher);
editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false); editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
} }
sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
Double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()); Double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) {
editBg.setValue(savedInstanceState.getDouble("editBg"));
} else {
editBg.setValue(bg1); editBg.setValue(bg1);
}
}); });
Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value(); Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value();
@ -311,7 +321,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
if (profile != null) if (profile != null)
maxPercent = MainApp.getConstraintChecker().getMaxBasalPercentAllowed(profile).value(); maxPercent = MainApp.getConstraintChecker().getMaxBasalPercentAllowed(profile).value();
editPercent = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentinput); editPercent = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentinput);
editPercent.setParams(0d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true, percentTextWatcher); editPercent.setParams(0d, -100d, (double) maxPercent, 5d, new DecimalFormat("0"), true, percentTextWatcher);
TextWatcher absoluteTextWatcher = new TextWatcher() { TextWatcher absoluteTextWatcher = new TextWatcher() {
@Override @Override
@ -378,6 +388,25 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
setCancelable(true); setCancelable(true);
getDialog().setCanceledOnTouchOutside(false); getDialog().setCanceledOnTouchOutside(false);
//recovering state if there is something
// only numberPickers and editTexts
if (savedInstanceState != null) {
editBg.setValue(savedInstanceState.getDouble("editBg"));
editTemptarget.setValue(savedInstanceState.getDouble("editTemptarget"));
notesEdit.setText(savedInstanceState.getString("notesEdit"));
editCarbs.setValue(savedInstanceState.getDouble("editCarbs"));
editCarbs.setValue(savedInstanceState.getDouble("editCarbs"));
editInsulin.setValue(savedInstanceState.getDouble("editInsulin"));
editDuration.setValue(savedInstanceState.getDouble("editDuration"));
editPercent.setValue(savedInstanceState.getDouble("editPercent"));
editAbsolute.setValue(savedInstanceState.getDouble("editAbsolute"));
editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime"));
editPercentage.setValue(savedInstanceState.getDouble("editPercentage"));
editTimeshift.setValue(savedInstanceState.getDouble("editTimeshift"));
// time and date
dateButton.setText(savedInstanceState.getString("dateButton"));
timeButton.setText(savedInstanceState.getString("timeButton"));
}
return view; return view;
} }
@ -758,8 +787,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
profileSwitch = new ProfileSwitch(); profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis(); profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER; profileSwitch.source = Source.USER;
profileSwitch.profileName = MainApp.getConfigBuilder().getProfileName(System.currentTimeMillis(), false); profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), false);
profileSwitch.profileJson = MainApp.getConfigBuilder().getProfile().getData().toString(); profileSwitch.profileJson = ProfileFunctions.getInstance().getProfile().getData().toString();
profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName(); profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration; profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0; profileSwitch.isCPP = percentage != 100 || timeshift != 0;
@ -772,4 +801,22 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
} }
} }
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("notesEdit", notesEdit.getText().toString());
savedInstanceState.putString("dateButton", dateButton.getText().toString());
savedInstanceState.putString("timeButton", timeButton.getText().toString());
savedInstanceState.putDouble("editBg", editBg.getValue());
savedInstanceState.putDouble("editCarbs", editCarbs.getValue());
savedInstanceState.putDouble("editInsulin", editInsulin.getValue());
savedInstanceState.putDouble("editDuration", editDuration.getValue());
savedInstanceState.putDouble("editPercent", editPercent.getValue());
savedInstanceState.putDouble("editAbsolute", editAbsolute.getValue());
savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue());
savedInstanceState.putDouble("editTemptarget", editTemptarget.getValue());
savedInstanceState.putDouble("editPercentage", editPercentage.getValue());
savedInstanceState.putDouble("editTimeshift", editTimeshift.getValue());
super.onSaveInstanceState(savedInstanceState);
}
} }

View file

@ -26,7 +26,7 @@ import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import butterknife.Unbinder; import butterknife.Unbinder;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.PreferencesActivity; import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;

View file

@ -1,35 +1,17 @@
package info.nightscout.androidaps.plugins.ConfigBuilder; package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Intent;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventAppInitialized;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
@ -38,24 +20,18 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue; import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class ConfigBuilderPlugin extends PluginBase { public class ConfigBuilderPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class); private Logger log = LoggerFactory.getLogger(L.CONFIGBUILDER);
private static ConfigBuilderPlugin configBuilderPlugin; private static ConfigBuilderPlugin configBuilderPlugin;
@ -70,15 +46,9 @@ public class ConfigBuilderPlugin extends PluginBase {
private static ProfileInterface activeProfile; private static ProfileInterface activeProfile;
private static TreatmentsInterface activeTreatments; private static TreatmentsInterface activeTreatments;
private static APSInterface activeAPS; private static APSInterface activeAPS;
private static LoopPlugin activeLoop;
private static InsulinInterface activeInsulin; private static InsulinInterface activeInsulin;
private static SensitivityInterface activeSensitivity; private static SensitivityInterface activeSensitivity;
static public String nightscoutVersionName = "";
static public Integer nightscoutVersionCode = 0;
static public String nsClientVersionName = "";
static public Integer nsClientVersionCode = 0;
private static ArrayList<PluginBase> pluginList; private static ArrayList<PluginBase> pluginList;
private static CommandQueue commandQueue = new CommandQueue(); private static CommandQueue commandQueue = new CommandQueue();
@ -119,16 +89,19 @@ public class ConfigBuilderPlugin extends PluginBase {
private void setAlwaysEnabledPluginsEnabled() { private void setAlwaysEnabledPluginsEnabled() {
for (PluginBase plugin : pluginList) { for (PluginBase plugin : pluginList) {
if (plugin.pluginDescription.alwaysEnabled) plugin.setPluginEnabled(plugin.getType(), true); if (plugin.pluginDescription.alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true);
} }
storeSettings("setAlwaysEnabledPluginsEnabled"); storeSettings("setAlwaysEnabledPluginsEnabled");
} }
public void storeSettings(String from) { public void storeSettings(String from) {
if (pluginList != null) { if (pluginList != null) {
if (Config.logPrefsChange) if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Storing settings from: " + from); log.debug("Storing settings from: " + from);
verifySelectionInCategories();
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
PluginType type = p.getType(); PluginType type = p.getType();
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwayVisible) if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwayVisible)
@ -142,23 +115,24 @@ public class ConfigBuilderPlugin extends PluginBase {
} }
} }
} }
verifySelectionInCategories();
} }
} }
private void savePref(PluginBase p, PluginType type, boolean storeVisible) { private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled"; String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
SP.putBoolean(settingEnabled, p.isEnabled(type)); SP.putBoolean(settingEnabled, p.isEnabled(type));
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type)); log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (storeVisible) { if (storeVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible"; String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
SP.putBoolean(settingVisible, p.isFragmentVisible()); SP.putBoolean(settingVisible, p.isFragmentVisible());
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible()); log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible());
} }
} }
private void loadSettings() { private void loadSettings() {
if (Config.logPrefsChange) if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Loading stored settings"); log.debug("Loading stored settings");
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
PluginType type = p.getType(); PluginType type = p.getType();
@ -179,6 +153,7 @@ public class ConfigBuilderPlugin extends PluginBase {
else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) { else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
p.setPluginEnabled(type, true); p.setPluginEnabled(type, true);
} }
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type)); log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (loadVisible) { if (loadVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible"; String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
@ -187,6 +162,7 @@ public class ConfigBuilderPlugin extends PluginBase {
else if (p.getType() == type && p.pluginDescription.visibleByDefault) { else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
p.setFragmentVisible(type, true); p.setFragmentVisible(type, true);
} }
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible()); log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible());
} }
} }
@ -195,9 +171,10 @@ public class ConfigBuilderPlugin extends PluginBase {
private void upgradeSettings() { private void upgradeSettings() {
if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled")) if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return; return;
if (Config.logPrefsChange) if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Upgrading stored settings"); log.debug("Upgrading stored settings");
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Processing " + p.getName()); log.debug("Processing " + p.getName());
for (int type = 1; type < 11; type++) { for (int type = 1; type < 11; type++) {
PluginType newType; PluginType newType;
@ -282,6 +259,7 @@ public class ConfigBuilderPlugin extends PluginBase {
} }
void logPluginStatus() { void logPluginStatus() {
if (L.isEnabled(L.CONFIGBUILDER))
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
log.debug(p.getName() + ":" + log.debug(p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") + (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
@ -310,6 +288,8 @@ public class ConfigBuilderPlugin extends PluginBase {
if (activeInsulin == null) { if (activeInsulin == null) {
activeInsulin = InsulinOrefRapidActingPlugin.getPlugin(); activeInsulin = InsulinOrefRapidActingPlugin.getPlugin();
InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(PluginType.INSULIN, true); InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(PluginType.INSULIN, true);
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Defaulting InsulinOrefRapidActingPlugin");
} }
this.setFragmentVisiblities(((PluginBase) activeInsulin).getName(), pluginsInCategory, PluginType.INSULIN); this.setFragmentVisiblities(((PluginBase) activeInsulin).getName(), pluginsInCategory, PluginType.INSULIN);
@ -319,6 +299,8 @@ public class ConfigBuilderPlugin extends PluginBase {
if (activeSensitivity == null) { if (activeSensitivity == null) {
activeSensitivity = SensitivityOref0Plugin.getPlugin(); activeSensitivity = SensitivityOref0Plugin.getPlugin();
SensitivityOref0Plugin.getPlugin().setPluginEnabled(PluginType.SENSITIVITY, true); SensitivityOref0Plugin.getPlugin().setPluginEnabled(PluginType.SENSITIVITY, true);
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Defaulting SensitivityOref0Plugin");
} }
this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY); this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY);
@ -334,12 +316,11 @@ public class ConfigBuilderPlugin extends PluginBase {
if (activePump == null) { if (activePump == null) {
activePump = VirtualPumpPlugin.getPlugin(); activePump = VirtualPumpPlugin.getPlugin();
VirtualPumpPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true); VirtualPumpPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Defaulting VirtualPumpPlugin");
} }
this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP); this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
// PluginType.LOOP
activeLoop = this.determineActivePlugin(PluginType.LOOP);
// PluginType.TREATMENT // PluginType.TREATMENT
activeTreatments = this.determineActivePlugin(PluginType.TREATMENT); activeTreatments = this.determineActivePlugin(PluginType.TREATMENT);
} }
@ -395,7 +376,7 @@ public class ConfigBuilderPlugin extends PluginBase {
private void setFragmentVisiblities(String activePluginName, ArrayList<PluginBase> pluginsInCategory, private void setFragmentVisiblities(String activePluginName, ArrayList<PluginBase> pluginsInCategory,
PluginType pluginType) { PluginType pluginType) {
if (Config.logConfigBuilder) if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Selected interface: " + activePluginName); log.debug("Selected interface: " + activePluginName);
for (PluginBase p : pluginsInCategory) { for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activePluginName)) { if (!p.getName().equals(activePluginName)) {
@ -421,247 +402,4 @@ public class ConfigBuilderPlugin extends PluginBase {
return found; return found;
} }
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return;
}
PumpInterface pump = getActivePump();
request.rateConstraint = new Constraint<>(request.rate);
request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value();
if (!pump.isInitialized()) {
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
getCommandQueue().cancelTempBasal(false, callback);
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
public void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
long lastBolusTime = activeTreatments.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
log.debug("SMB requested but still in 3 min interval");
if (callback != null) {
callback.result(new PumpEnactResult()
.comment(MainApp.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
PumpInterface pump = getActivePump();
if (!pump.isInitialized()) {
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (Config.logCongigBuilderActions)
log.debug("applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: bolus()");
getCommandQueue().bolus(detailedBolusInfo, callback);
}
@Subscribe
public void onProfileSwitch(EventProfileSwitchChange ignored) {
getCommandQueue().setProfile(getProfile(), new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
MainApp.bus().post(new EventNewBasalProfile());
}
});
}
public String getProfileName() {
return getProfileName(System.currentTimeMillis());
}
public String getProfileName(boolean customized) {
return getProfileName(System.currentTimeMillis(), customized);
}
public String getProfileName(long time) {
return getProfileName(time, true);
}
public String getProfileName(long time, boolean customized) {
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profileSwitch.profileName;
}
}
}
return MainApp.gs(R.string.noprofileselected);
}
public boolean isProfileValid(String from) {
return getProfile() != null && getProfile().isValid(from);
}
@Nullable
public Profile getProfile() {
return getProfile(System.currentTimeMillis());
}
public String getProfileUnits() {
Profile profile = getProfile();
return profile != null ? profile.getUnits() : Constants.MGDL;
}
@Nullable
public Profile getProfile(long time) {
if (activeTreatments == null) {
log.debug("getProfile activeTreatments == null: returning null");
return null; //app not initialized
}
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.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;
}
}
if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("time", time)
.putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString())
);
}
log.debug("getProfile at the end: returning null");
return null;
}
public void disconnectPump(int durationInMinutes, Profile profile) {
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
if (getActivePump().getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
}
}
});
}
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
public void suspendLoop(int durationInMinutes) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
} }

View file

@ -6,17 +6,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 08.08.2017. * Created by mike on 08.08.2017.
*/ */
public class DetailedBolusInfoStorage { public class DetailedBolusInfoStorage {
private static Logger log = LoggerFactory.getLogger(DetailedBolusInfoStorage.class); private static Logger log = LoggerFactory.getLogger(L.PUMP);
private static List<DetailedBolusInfo> store = new ArrayList<>(); private static List<DetailedBolusInfo> store = new ArrayList<>();
public static synchronized void add(DetailedBolusInfo detailedBolusInfo) { public static synchronized void add(DetailedBolusInfo detailedBolusInfo) {
@ -29,23 +29,16 @@ public class DetailedBolusInfoStorage {
DetailedBolusInfo found = null; DetailedBolusInfo found = null;
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; long infoTime = store.get(i).date;
if (L.isEnabled(L.PUMP))
log.debug("Existing bolus info: " + store.get(i)); log.debug("Existing bolus info: " + store.get(i));
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
found = store.get(i); found = store.get(i);
if (L.isEnabled(L.PUMP))
log.debug("Using & removing bolus info: " + store.get(i));
store.remove(i);
break; break;
} }
} }
return found; return found;
} }
public static synchronized void remove(long bolustime) {
for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date;
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
log.debug("Removing bolus info: " + store.get(i));
store.remove(i);
break;
}
}
}
} }

View file

@ -0,0 +1,142 @@
package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Intent;
import android.support.annotation.Nullable;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.FabricPrivacy;
public class ProfileFunctions {
private static Logger log = LoggerFactory.getLogger(L.PROFILE);
private static ProfileFunctions profileFunctions = null;
public static ProfileFunctions getInstance() {
if (profileFunctions == null)
profileFunctions = new ProfileFunctions();
return profileFunctions;
}
static {
ProfileFunctions.getInstance(); // register to bus at start
}
ProfileFunctions() {
MainApp.bus().register(this);
}
@Subscribe
public void onProfileSwitch(EventProfileSwitchChange ignored) {
if (L.isEnabled(L.PROFILE))
log.debug("onProfileSwitch");
MainApp.getConfigBuilder().getCommandQueue().setProfile(getProfile(), new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
MainApp.bus().post(new EventNewBasalProfile());
}
});
}
public String getProfileName() {
return getProfileName(System.currentTimeMillis());
}
public String getProfileName(boolean customized) {
return getProfileName(System.currentTimeMillis(), customized);
}
public String getProfileName(long time) {
return getProfileName(time, true);
}
public String getProfileName(long time, boolean customized) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface();
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profileSwitch.profileName;
}
}
}
return MainApp.gs(R.string.noprofileselected);
}
public boolean isProfileValid(String from) {
return getProfile() != null && getProfile().isValid(from);
}
@Nullable
public Profile getProfile() {
return getProfile(System.currentTimeMillis());
}
public String getProfileUnits() {
Profile profile = getProfile();
return profile != null ? profile.getUnits() : Constants.MGDL;
}
@Nullable
public Profile getProfile(long time) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface();
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.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;
}
}
if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("time", time)
.putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString())
);
}
log.error("getProfile at the end: returning null");
return null;
}
}

View file

@ -1,18 +1,15 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives; package info.nightscout.androidaps.plugins.ConstraintsObjectives;
import android.animation.LayoutTransition;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView; import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.text.Html; import android.text.Html;
import android.util.DisplayMetrics;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -21,28 +18,15 @@ import android.widget.CheckBox;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
public class ObjectivesFragment extends SubscriberFragment { public class ObjectivesFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class);
RecyclerView recyclerView; RecyclerView recyclerView;
CheckBox enableFake; CheckBox enableFake;
TextView reset; TextView reset;
@ -71,7 +55,7 @@ public class ObjectivesFragment extends SubscriberFragment {
enableFake.setOnClickListener(v -> updateGUI()); enableFake.setOnClickListener(v -> updateGUI());
reset.setOnClickListener(v -> { reset.setOnClickListener(v -> {
ObjectivesPlugin.getPlugin().reset(); ObjectivesPlugin.getPlugin().reset();
ObjectivesPlugin.saveProgress(); ObjectivesPlugin.getPlugin().saveProgress();
recyclerView.getAdapter().notifyDataSetChanged(); recyclerView.getAdapter().notifyDataSetChanged();
scrollToCurrentObjective(); scrollToCurrentObjective();
}); });
@ -93,7 +77,7 @@ public class ObjectivesFragment extends SubscriberFragment {
private void startUpdateTimer() { private void startUpdateTimer() {
handler.removeCallbacks(objectiveUpdater); handler.removeCallbacks(objectiveUpdater);
for (Objective objective : ObjectivesPlugin.getObjectives()) { for (Objective objective : ObjectivesPlugin.getPlugin().getObjectives()) {
if (objective.isStarted() && !objective.isAccomplished()) { if (objective.isStarted() && !objective.isAccomplished()) {
long timeTillNextMinute = (System.currentTimeMillis() - objective.getStartedOn().getTime()) % (60 * 1000); long timeTillNextMinute = (System.currentTimeMillis() - objective.getStartedOn().getTime()) % (60 * 1000);
handler.postDelayed(objectiveUpdater, timeTillNextMinute); handler.postDelayed(objectiveUpdater, timeTillNextMinute);
@ -103,8 +87,8 @@ public class ObjectivesFragment extends SubscriberFragment {
} }
private void scrollToCurrentObjective() { private void scrollToCurrentObjective() {
for (int i = 0; i < ObjectivesPlugin.getObjectives().size(); i++) { for (int i = 0; i < ObjectivesPlugin.getPlugin().getObjectives().size(); i++) {
Objective objective = ObjectivesPlugin.getObjectives().get(i); Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(i);
if (!objective.isStarted() || !objective.isAccomplished()) { if (!objective.isStarted() || !objective.isAccomplished()) {
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) { RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
@Override @Override
@ -134,7 +118,7 @@ public class ObjectivesFragment extends SubscriberFragment {
@Override @Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Objective objective = ObjectivesPlugin.getObjectives().get(position); Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(position);
holder.title.setText(MainApp.gs(R.string.nth_objective, position + 1)); holder.title.setText(MainApp.gs(R.string.nth_objective, position + 1));
if (objective.getObjective() != 0) { if (objective.getObjective() != 0) {
holder.objective.setVisibility(View.VISIBLE); holder.objective.setVisibility(View.VISIBLE);
@ -148,7 +132,7 @@ public class ObjectivesFragment extends SubscriberFragment {
holder.gate.setTextColor(0xFFFFFFFF); holder.gate.setTextColor(0xFFFFFFFF);
holder.verify.setVisibility(View.GONE); holder.verify.setVisibility(View.GONE);
holder.progress.setVisibility(View.GONE); holder.progress.setVisibility(View.GONE);
if (position == 0 || ObjectivesPlugin.getObjectives().get(position - 1).isAccomplished()) if (position == 0 || ObjectivesPlugin.getPlugin().getObjectives().get(position - 1).isAccomplished())
holder.start.setVisibility(View.VISIBLE); holder.start.setVisibility(View.VISIBLE);
else holder.start.setVisibility(View.GONE); else holder.start.setVisibility(View.GONE);
} else if (objective.isAccomplished()) { } else if (objective.isAccomplished()) {
@ -189,7 +173,7 @@ public class ObjectivesFragment extends SubscriberFragment {
@Override @Override
public int getItemCount() { public int getItemCount() {
return ObjectivesPlugin.getObjectives().size(); return ObjectivesPlugin.getPlugin().getObjectives().size();
} }
public class ViewHolder extends RecyclerView.ViewHolder { public class ViewHolder extends RecyclerView.ViewHolder {

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved; import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective;
@ -32,14 +33,14 @@ import info.nightscout.utils.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface { public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ObjectivesPlugin.class); private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
private static ObjectivesPlugin objectivesPlugin; private static ObjectivesPlugin objectivesPlugin;
public static List<Objective> objectives = new ArrayList<>(); public List<Objective> objectives = new ArrayList<>();
public static boolean bgIsAvailableInNS = false; public boolean bgIsAvailableInNS = false;
public static boolean pumpStatusIsAvailableInNS = false; public boolean pumpStatusIsAvailableInNS = false;
public static Integer manualEnacts = 0; public Integer manualEnacts = 0;
public static ObjectivesPlugin getPlugin() { public static ObjectivesPlugin getPlugin() {
if (objectivesPlugin == null) { if (objectivesPlugin == null) {
@ -52,8 +53,8 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
.fragmentClass(ObjectivesFragment.class.getName()) .fragmentClass(ObjectivesFragment.class.getName())
.alwaysEnabled(!Config.NSCLIENT && !Config.G5UPLOADER) .alwaysEnabled(!Config.NSCLIENT)
.showInList(!Config.NSCLIENT && !Config.G5UPLOADER) .showInList(!Config.NSCLIENT)
.pluginName(R.string.objectives) .pluginName(R.string.objectives)
.shortName(R.string.objectives_shortname) .shortName(R.string.objectives_shortname)
.description(R.string.description_objectives) .description(R.string.description_objectives)
@ -90,11 +91,11 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface
saveProgress(); saveProgress();
} }
public static void saveProgress() { public void saveProgress() {
SP.putBoolean("Objectives" + "bgIsAvailableInNS", bgIsAvailableInNS); SP.putBoolean("Objectives" + "bgIsAvailableInNS", bgIsAvailableInNS);
SP.putBoolean("Objectives" + "pumpStatusIsAvailableInNS", pumpStatusIsAvailableInNS); SP.putBoolean("Objectives" + "pumpStatusIsAvailableInNS", pumpStatusIsAvailableInNS);
SP.putString("Objectives" + "manualEnacts", Integer.toString(manualEnacts)); SP.putString("Objectives" + "manualEnacts", Integer.toString(manualEnacts));
if (Config.logPrefsChange) if (L.isEnabled(L.CONSTRAINTS))
log.debug("Objectives stored"); log.debug("Objectives stored");
MainApp.bus().post(new EventObjectivesSaved()); MainApp.bus().post(new EventObjectivesSaved());
} }
@ -107,11 +108,11 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
if (Config.logPrefsChange) if (L.isEnabled(L.CONSTRAINTS))
log.debug("Objectives loaded"); log.debug("Objectives loaded");
} }
public static List<Objective> getObjectives() { public List<Objective> getObjectives() {
return objectives; return objectives;
} }

View file

@ -9,6 +9,7 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.T;
public abstract class Objective { public abstract class Objective {
@ -128,9 +129,9 @@ public abstract class Objective {
} }
private String getDurationText(long duration) { private String getDurationText(long duration) {
int days = (int) Math.floor((double) duration / (24D * 60D * 60D * 1000D)); int days = (int) Math.floor((double) duration / T.days(1).msecs());
int hours = (int) Math.floor((double) duration / (60D * 60D * 1000D)); int hours = (int) Math.floor((double) duration / T.hours(1).msecs());
int minutes = (int) Math.floor((double) duration / (60D * 1000D)); int minutes = (int) Math.floor((double) duration / T.mins(1).msecs());
if (days > 0) return MainApp.gq(R.plurals.objective_days, days, days); if (days > 0) return MainApp.gq(R.plurals.objective_days, days, days);
else if (hours > 0) return MainApp.gq(R.plurals.objective_hours, hours, hours); else if (hours > 0) return MainApp.gq(R.plurals.objective_hours, hours, hours);
else return MainApp.gq(R.plurals.objective_minutes, minutes, minutes); else return MainApp.gq(R.plurals.objective_minutes, minutes, minutes);

View file

@ -27,7 +27,7 @@ public class Objective1 extends Objective {
tasks.add(new Task(R.string.objectives_bgavailableinns) { tasks.add(new Task(R.string.objectives_bgavailableinns) {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {
return ObjectivesPlugin.bgIsAvailableInNS; return ObjectivesPlugin.getPlugin().bgIsAvailableInNS;
} }
}); });
tasks.add(new Task(R.string.nsclienthaswritepermission) { tasks.add(new Task(R.string.nsclienthaswritepermission) {
@ -50,7 +50,7 @@ public class Objective1 extends Objective {
tasks.add(new Task(R.string.objectives_pumpstatusavailableinns) { tasks.add(new Task(R.string.objectives_pumpstatusavailableinns) {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {
return ObjectivesPlugin.pumpStatusIsAvailableInNS; return ObjectivesPlugin.getPlugin().pumpStatusIsAvailableInNS;
} }
}); });
tasks.add(new Task(R.string.hasbgdata) { tasks.add(new Task(R.string.hasbgdata) {

View file

@ -5,10 +5,11 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.utils.T;
public class Objective2 extends Objective { public class Objective2 extends Objective {
public static final int MANUAL_ENACTS_NEEDED = 20; public final int MANUAL_ENACTS_NEEDED = 20;
public Objective2() { public Objective2() {
super(1, R.string.objectives_1_objective, R.string.objectives_1_gate); super(1, R.string.objectives_1_objective, R.string.objectives_1_gate);
@ -16,17 +17,19 @@ public class Objective2 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new MinimumDurationTask(7L * 24L * 60L * 60L * 1000L)); tasks.add(new MinimumDurationTask(T.days(7).msecs()));
tasks.add(new Task(R.string.objectives_manualenacts) { tasks.add(new Task(R.string.objectives_manualenacts) {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {
return ObjectivesPlugin.manualEnacts >= MANUAL_ENACTS_NEEDED; return ObjectivesPlugin.getPlugin().manualEnacts >= MANUAL_ENACTS_NEEDED;
} }
@Override @Override
public String getProgress() { public String getProgress() {
if (ObjectivesPlugin.manualEnacts >= MANUAL_ENACTS_NEEDED) return MainApp.gs(R.string.completed_well_done); if (ObjectivesPlugin.getPlugin().manualEnacts >= MANUAL_ENACTS_NEEDED)
else return ObjectivesPlugin.manualEnacts + " / " + MANUAL_ENACTS_NEEDED; return MainApp.gs(R.string.completed_well_done);
else
return ObjectivesPlugin.getPlugin().manualEnacts + " / " + MANUAL_ENACTS_NEEDED;
} }
}); });
} }

View file

@ -5,6 +5,7 @@ import java.util.List;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin; import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
import info.nightscout.utils.T;
public class Objective4 extends Objective { public class Objective4 extends Objective {
@ -14,7 +15,7 @@ public class Objective4 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new MinimumDurationTask(5L * 24L * 60L * 60L * 1000L)); tasks.add(new MinimumDurationTask(T.days(5).msecs()));
tasks.add(new Task(R.string.closedmodeenabled) { tasks.add(new Task(R.string.closedmodeenabled) {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {

View file

@ -4,6 +4,7 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.T;
public class Objective5 extends Objective { public class Objective5 extends Objective {
@ -13,7 +14,7 @@ public class Objective5 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new MinimumDurationTask(24L * 60L * 60L * 1000L)); tasks.add(new MinimumDurationTask(T.days(1).msecs()));
tasks.add(new Task(R.string.maxiobset) { tasks.add(new Task(R.string.maxiobset) {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.T;
public class Objective6 extends Objective { public class Objective6 extends Objective {
@ -12,6 +13,6 @@ public class Objective6 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new MinimumDurationTask(7L * 24L * 60L * 60L * 1000L)); tasks.add(new MinimumDurationTask(T.days(7).msecs()));
} }
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.T;
public class Objective7 extends Objective { public class Objective7 extends Objective {
@ -12,6 +13,6 @@ public class Objective7 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new MinimumDurationTask(28L * 24L * 60L * 60L * 1000L)); tasks.add(new MinimumDurationTask(T.days(28).msecs()));
} }
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.T;
public class Objective8 extends Objective { public class Objective8 extends Objective {
@ -12,6 +13,6 @@ public class Objective8 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new MinimumDurationTask(28L * 24L * 60L * 60L * 1000L)); tasks.add(new MinimumDurationTask(T.days(28).msecs()));
} }
} }

View file

@ -10,6 +10,8 @@ import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
@ -57,7 +59,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
@Override @Override
public Constraint<Boolean> isClosedLoopAllowed(Constraint<Boolean> value) { public Constraint<Boolean> isClosedLoopAllowed(Constraint<Boolean> value) {
String mode = SP.getString("aps_mode", "open"); String mode = SP.getString(R.string.key_aps_mode, "open");
if (!mode.equals("closed")) if (!mode.equals("closed"))
value.set(false, MainApp.gs(R.string.closedmodedisabledinpreferences), this); value.set(false, MainApp.gs(R.string.closedmodedisabledinpreferences), this);
@ -121,6 +123,18 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
absoluteRate.setIfSmaller(maxFromDaily, String.format(MainApp.gs(R.string.limitingbasalratio), maxFromDaily, MainApp.gs(R.string.maxdailybasalmultiplier)), this); absoluteRate.setIfSmaller(maxFromDaily, String.format(MainApp.gs(R.string.limitingbasalratio), maxFromDaily, MainApp.gs(R.string.maxdailybasalmultiplier)), this);
absoluteRate.setIfSmaller(HardLimits.maxBasal(), String.format(MainApp.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), MainApp.gs(R.string.hardlimit)), this); absoluteRate.setIfSmaller(HardLimits.maxBasal(), String.format(MainApp.gs(R.string.limitingbasalratio), HardLimits.maxBasal(), MainApp.gs(R.string.hardlimit)), this);
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
// check for pump max
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
absoluteRate.setIfSmaller(pumpLimit, String.format(MainApp.gs(R.string.limitingbasalratio), pumpLimit, MainApp.gs(R.string.pumplimit)), this);
}
// do rounding
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
absoluteRate.set(Round.roundTo(absoluteRate.value(), pump.getPumpDescription().tempAbsoluteStep));
}
return absoluteRate; return absoluteRate;
} }
@ -136,13 +150,23 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
applyBasalConstraints(absoluteConstraint, profile); applyBasalConstraints(absoluteConstraint, profile);
percentRate.copyReasons(absoluteConstraint); percentRate.copyReasons(absoluteConstraint);
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
Integer percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue(); Integer percentRateAfterConst = Double.valueOf(absoluteConstraint.value() / currentBasal * 100).intValue();
if (pump != null) {
if (percentRateAfterConst < 100) if (percentRateAfterConst < 100)
percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, 10d).intValue(); percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
else percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, 10d).intValue(); else
percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, (double) pump.getPumpDescription().tempPercentStep).intValue();
}
percentRate.set(percentRateAfterConst, String.format(MainApp.gs(R.string.limitingpercentrate), percentRateAfterConst, MainApp.gs(R.string.pumplimit)), this); percentRate.set(percentRateAfterConst, String.format(MainApp.gs(R.string.limitingpercentrate), percentRateAfterConst, MainApp.gs(R.string.pumplimit)), this);
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
percentRate.setIfSmaller((int) pumpLimit, String.format(MainApp.gs(R.string.limitingbasalratio), pumpLimit, MainApp.gs(R.string.pumplimit)), this);
}
return percentRate; return percentRate;
} }
@ -154,6 +178,29 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
insulin.setIfSmaller(maxBolus, String.format(MainApp.gs(R.string.limitingbolus), maxBolus, MainApp.gs(R.string.maxvalueinpreferences)), this); insulin.setIfSmaller(maxBolus, String.format(MainApp.gs(R.string.limitingbolus), maxBolus, MainApp.gs(R.string.maxvalueinpreferences)), this);
insulin.setIfSmaller(HardLimits.maxBolus(), String.format(MainApp.gs(R.string.limitingbolus), HardLimits.maxBolus(), MainApp.gs(R.string.hardlimit)), this); insulin.setIfSmaller(HardLimits.maxBolus(), String.format(MainApp.gs(R.string.limitingbolus), HardLimits.maxBolus(), MainApp.gs(R.string.hardlimit)), this);
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
if (pump != null) {
double rounded = Round.roundTo(insulin.value(), pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulin.value()));
insulin.setIfDifferent(rounded, MainApp.gs(R.string.pumplimit), this);
}
return insulin;
}
@Override
public Constraint<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
insulin.setIfGreater(0d, String.format(MainApp.gs(R.string.limitingextendedbolus), 0d, MainApp.gs(R.string.itmustbepositivevalue)), this);
Double maxBolus = SP.getDouble(R.string.key_treatmentssafety_maxbolus, 3d);
insulin.setIfSmaller(maxBolus, String.format(MainApp.gs(R.string.limitingextendedbolus), maxBolus, MainApp.gs(R.string.maxvalueinpreferences)), this);
insulin.setIfSmaller(HardLimits.maxBolus(), String.format(MainApp.gs(R.string.limitingextendedbolus), HardLimits.maxBolus(), MainApp.gs(R.string.hardlimit)), this);
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
if (pump != null) {
double rounded = Round.roundTo(insulin.value(), pump.getPumpDescription().pumpType.determineCorrectExtendedBolusSize(insulin.value()));
insulin.setIfDifferent(rounded, MainApp.gs(R.string.pumplimit), this);
}
return insulin; return insulin;
} }

View file

@ -33,7 +33,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SpinnerHelper; import info.nightscout.utils.SpinnerHelper;
/** /**

View file

@ -33,13 +33,14 @@ import info.nightscout.androidaps.db.ICallback;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 24.09.2017. * Created by mike on 24.09.2017.
*/ */
public class FoodService extends OrmLiteBaseService<DatabaseHelper> { public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
private static Logger log = LoggerFactory.getLogger(FoodService.class); private Logger log = LoggerFactory.getLogger(L.DATAFOOD);
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledFoodEventPost = null; private static ScheduledFuture<?> scheduledFoodEventPost = null;
@ -110,6 +111,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
try { try {
if (L.isEnabled(L.DATAFOOD))
log.info("onCreate"); log.info("onCreate");
TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class);
} catch (SQLException e) { } catch (SQLException e) {
@ -119,13 +121,10 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
} }
public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {
if (oldVersion == 7 && newVersion == 8) { if (L.isEnabled(L.DATAFOOD))
log.debug("Upgrading database from v7 to v8");
} else {
log.info("onUpgrade"); log.info("onUpgrade");
// this.resetFood(); // this.resetFood();
} }
}
public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {
// this method is not supported right now // this method is not supported right now
@ -161,6 +160,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
if (L.isEnabled(L.DATAFOOD))
log.debug("Firing EventFoodChange"); log.debug("Firing EventFoodChange");
MainApp.bus().post(event); MainApp.bus().post(event);
callback.setPost(null); callback.setPost(null);
@ -271,7 +271,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void deleteByNSId(String _id) throws SQLException { public void deleteByNSId(String _id) throws SQLException {
Food stored = this.findByNSId(_id); Food stored = this.findByNSId(_id);
if (stored != null) { if (stored != null) {
log.debug("FOOD: Removing Food record from database: " + stored.toString()); if (L.isEnabled(L.DATAFOOD))
log.debug("Removing Food record from database: " + stored.toString());
this.delete(stored); this.delete(stored);
} }
} }
@ -324,7 +325,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void createOrUpdate(Food food) { public void createOrUpdate(Food food) {
try { try {
this.getDao().createOrUpdate(food); this.getDao().createOrUpdate(food);
log.debug("FOOD: Created or Updated: " + food.toString()); if (L.isEnabled(L.DATAFOOD))
log.debug("Created or Updated: " + food.toString());
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unable to createOrUpdate Food", e); log.error("Unable to createOrUpdate Food", e);
} }
@ -334,7 +336,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void create(Food food) { public void create(Food food) {
try { try {
this.getDao().create(food); this.getDao().create(food);
log.debug("FOOD: New record: " + food.toString()); if (L.isEnabled(L.DATAFOOD))
log.debug("New record: " + food.toString());
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unable to create Food", e); log.error("Unable to create Food", e);
} }

View file

@ -5,6 +5,7 @@ import com.squareup.otto.Bus;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -61,7 +62,7 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli
} }
public double getUserDefinedDia() { public double getUserDefinedDia() {
return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : MIN_DIA; return ProfileFunctions.getInstance().getProfile() != null ? ProfileFunctions.getInstance().getProfile().getDia() : MIN_DIA;
} }
public Iob iobCalcForTreatment(Treatment treatment, long time) { public Iob iobCalcForTreatment(Treatment treatment, long time) {

View file

@ -12,6 +12,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -26,7 +28,7 @@ import info.nightscout.utils.SP;
*/ */
public class AutosensData implements DataPointWithLabelInterface { public class AutosensData implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger("AUTOSENS"); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
public void setChartTime(long chartTime) { public void setChartTime(long chartTime) {
this.chartTime = chartTime; this.chartTime = chartTime;
@ -44,10 +46,11 @@ public class AutosensData implements DataPointWithLabelInterface {
remaining = t.carbs; remaining = t.carbs;
if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) {
double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME);
Profile profile = MainApp.getConfigBuilder().getProfile(t.date); Profile profile = ProfileFunctions.getInstance().getProfile(t.date);
double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits());
double ic = profile.getIc(t.date); double ic = profile.getIc(t.date);
min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic;
if (L.isEnabled(L.AUTOSENS))
log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + 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 { } else {
min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact);
@ -107,6 +110,7 @@ public class AutosensData implements DataPointWithLabelInterface {
activeCarbsList.remove(i--); activeCarbsList.remove(i--);
if (c.remaining > 0) if (c.remaining > 0)
cob -= c.remaining; cob -= c.remaining;
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString()); log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString());
} }
} }

View file

@ -5,11 +5,13 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 06.01.2017. * Created by mike on 06.01.2017.
*/ */
public class AutosensResult { public class AutosensResult {
private static Logger log = LoggerFactory.getLogger("AUTOSENS"); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
//default values to show when autosens algorithm is not called //default values to show when autosens algorithm is not called
public double ratio = 1d; public double ratio = 1d;

View file

@ -12,10 +12,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -32,7 +30,9 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin;
@ -48,7 +48,7 @@ import static info.nightscout.utils.DateUtil.now;
*/ */
public class IobCobCalculatorPlugin extends PluginBase { public class IobCobCalculatorPlugin extends PluginBase {
private Logger log = LoggerFactory.getLogger("AUTOSENS"); private Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private static IobCobCalculatorPlugin plugin = null; private static IobCobCalculatorPlugin plugin = null;
@ -98,37 +98,19 @@ public class IobCobCalculatorPlugin extends PluginBase {
return autosensDataTable; return autosensDataTable;
} }
public List<BgReading> getBgReadings() {
return bgReadings;
}
public void setBgReadings(List<BgReading> bgReadings) {
this.bgReadings = bgReadings;
}
public List<BgReading> getBucketedData() { public List<BgReading> getBucketedData() {
return bucketed_data; return bucketed_data;
} }
@Nullable // roundup to whole minute
public List<BgReading> getBucketedData(long fromTime) {
//log.debug("Locking getBucketedData");
synchronized (dataLock) {
if (bucketed_data == null) {
log.debug("No bucketed data available");
return null;
}
int index = indexNewerThan(fromTime);
if (index > -1) {
List<BgReading> part = bucketed_data.subList(0, index);
log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size());
return part;
}
}
//log.debug("Releasing getBucketedData");
return null;
}
private int indexNewerThan(long time) {
for (int index = 0; index < bucketed_data.size(); index++) {
if (bucketed_data.get(index).date < time)
return index - 1;
}
return -1;
}
public static long roundUpTime(long time) { public static long roundUpTime(long time) {
if (time % 60000 == 0) if (time % 60000 == 0)
return time; return time;
@ -136,16 +118,14 @@ public class IobCobCalculatorPlugin extends PluginBase {
return rounded; return rounded;
} }
void loadBgData(long start) { void loadBgData(long now) {
if (start < oldestDataAvailable()) { long start = (long) (now - 60 * 60 * 1000L * (24 + dia));
start = oldestDataAvailable(); bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false);
log.debug("Limiting BG data to oldest data available: " + DateUtil.dateAndTimeString(start)); if (L.isEnabled(L.AUTOSENS))
} log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now));
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (start - 60 * 60 * 1000L * (24 + dia)), false);
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start));
} }
private boolean isAbout5minData() { public boolean isAbout5minData() {
synchronized (dataLock) { synchronized (dataLock) {
if (bgReadings == null || bgReadings.size() < 3) { if (bgReadings == null || bgReadings.size() < 3) {
return true; return true;
@ -155,21 +135,26 @@ public class IobCobCalculatorPlugin extends PluginBase {
long bgTime = bgReadings.get(i).date; long bgTime = bgReadings.get(i).date;
long lastbgTime = bgReadings.get(i - 1).date; long lastbgTime = bgReadings.get(i - 1).date;
long diff = lastbgTime - bgTime; long diff = lastbgTime - bgTime;
diff %= T.mins(5).msecs();
if (diff > T.mins(2).plus(T.secs(30)).msecs())
diff = diff - T.mins(5).msecs();
totalDiff += diff; totalDiff += diff;
if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30 diff = Math.abs(diff);
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false); if (diff > T.secs(30).msecs()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "[s] is5minData: " + false);
return false; return false;
} }
} }
double intervals = totalDiff / (5 * 60 * 1000d); double averageDiff = totalDiff / (bgReadings.size() - 1) / 1000d;
double variability = Math.abs(intervals - Math.round(intervals)); boolean is5mindata = averageDiff < 10;
boolean is5mindata = variability < 0.02; if (L.isEnabled(L.AUTOSENS))
log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata); log.debug("Interval detection: values: " + bgReadings.size() + " averageDiff: " + averageDiff + "[s] is5minData: " + is5mindata);
return is5mindata; return is5mindata;
} }
} }
void createBucketedData() { public void createBucketedData() {
if (isAbout5minData()) if (isAbout5minData())
createBucketedData5min(); createBucketedData5min();
else else
@ -177,24 +162,26 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
@Nullable @Nullable
private BgReading findNewer(long time) { public BgReading findNewer(long time) {
BgReading lastFound = bgReadings.get(0); BgReading lastFound = bgReadings.get(0);
if (lastFound.date < time) return null; if (lastFound.date < time) return null;
for (int i = 1; i < bgReadings.size(); ++i) { for (int i = 1; i < bgReadings.size(); ++i) {
if (bgReadings.get(i).date == time) return bgReadings.get(i);
if (bgReadings.get(i).date > time) continue; if (bgReadings.get(i).date > time) continue;
lastFound = bgReadings.get(i); lastFound = bgReadings.get(i - 1);
if (bgReadings.get(i).date < time) break; if (bgReadings.get(i).date < time) break;
} }
return lastFound; return lastFound;
} }
@Nullable @Nullable
private BgReading findOlder(long time) { public BgReading findOlder(long time) {
BgReading lastFound = bgReadings.get(bgReadings.size() - 1); BgReading lastFound = bgReadings.get(bgReadings.size() - 1);
if (lastFound.date > time) return null; if (lastFound.date > time) return null;
for (int i = bgReadings.size() - 2; i >= 0; --i) { for (int i = bgReadings.size() - 2; i >= 0; --i) {
if (bgReadings.get(i).date == time) return bgReadings.get(i);
if (bgReadings.get(i).date < time) continue; if (bgReadings.get(i).date < time) continue;
lastFound = bgReadings.get(i); lastFound = bgReadings.get(i + 1);
if (bgReadings.get(i).date > time) break; if (bgReadings.get(i).date > time) break;
} }
return lastFound; return lastFound;
@ -207,7 +194,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
bucketed_data = new ArrayList<>(); bucketed_data = new ArrayList<>();
long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L; long currentTime = bgReadings.get(0).date - bgReadings.get(0).date % T.mins(5).msecs();
//log.debug("First reading: " + new Date(currentTime).toLocaleString()); //log.debug("First reading: " + new Date(currentTime).toLocaleString());
while (true) { while (true) {
@ -217,6 +204,9 @@ public class IobCobCalculatorPlugin extends PluginBase {
if (newer == null || older == null) if (newer == null || older == null)
break; break;
if (older.date == newer.date) { // direct hit
bucketed_data.add(newer);
} else {
double bgDelta = newer.value - older.value; double bgDelta = newer.value - older.value;
long timeDiffToNew = newer.date - currentTime; long timeDiffToNew = newer.date - currentTime;
@ -226,7 +216,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
newBgreading.value = Math.round(currentBg); newBgreading.value = Math.round(currentBg);
bucketed_data.add(newBgreading); 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() + ")"); //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; }
currentTime -= T.mins(5).msecs();
} }
} }
@ -267,7 +258,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
newBgreading.value = Math.round(nextbg); newBgreading.value = Math.round(nextbg);
//console.error("Interpolated", bucketed_data[j]); //console.error("Interpolated", bucketed_data[j]);
bucketed_data.add(newBgreading); bucketed_data.add(newBgreading);
//log.error("******************************************************************************************************* Adding:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
elapsed_minutes = elapsed_minutes - 5; elapsed_minutes = elapsed_minutes - 5;
lastbg = nextbg; lastbg = nextbg;
@ -278,28 +270,51 @@ public class IobCobCalculatorPlugin extends PluginBase {
newBgreading.value = bgReadings.get(i).value; newBgreading.value = bgReadings.get(i).value;
newBgreading.date = bgTime; newBgreading.date = bgTime;
bucketed_data.add(newBgreading); bucketed_data.add(newBgreading);
//log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
} else if (Math.abs(elapsed_minutes) > 2) { } else if (Math.abs(elapsed_minutes) > 2) {
j++; j++;
BgReading newBgreading = new BgReading(); BgReading newBgreading = new BgReading();
newBgreading.value = bgReadings.get(i).value; newBgreading.value = bgReadings.get(i).value;
newBgreading.date = bgTime; newBgreading.date = bgTime;
bucketed_data.add(newBgreading); bucketed_data.add(newBgreading);
//log.error("******************************************************************************************************* Copying:" + new Date(newBgreading.date).toString() + " " + newBgreading.value); if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
} else { } else {
bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2; bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2;
//log.error("***** Average"); //log.error("***** Average");
} }
} }
// Normalize bucketed data
for (int i = bucketed_data.size() - 2; i >= 0; i--) {
BgReading current = bucketed_data.get(i);
BgReading previous = bucketed_data.get(i + 1);
long msecDiff = current.date - previous.date;
long adjusted = (msecDiff - T.mins(5).msecs()) / 1000;
if (L.isEnabled(L.AUTOSENS))
log.debug("Adjusting bucketed data time. Current: " + DateUtil.toISOString(current.date) + " to: " + DateUtil.toISOString(previous.date + T.mins(5).msecs()) + " by " + adjusted + " sec");
current.date = previous.date + T.mins(5).msecs();
}
if (L.isEnabled(L.AUTOSENS))
log.debug("Bucketed data created. Size: " + bucketed_data.size()); log.debug("Bucketed data created. Size: " + bucketed_data.size());
} }
public long oldestDataAvailable() { public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) {
long now = System.currentTimeMillis(); Profile profile = ProfileFunctions.getInstance().getProfile(from);
double dia = Constants.defaultDIA;
if (profile != null) dia = profile.getDia();
long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable(); long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable();
long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - T.hours(1).msecs() * (24 + MainApp.getConfigBuilder().getProfile().getDia()))); long getBGDataFrom;
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); if (limitDataToOldestAvailable) {
getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia)));
if (getBGDataFrom == oldestDataAvailable)
if (L.isEnabled(L.AUTOSENS))
log.debug("Limiting data to oldest available temps: " + DateUtil.dateAndTimeFullString(oldestDataAvailable));
} else
getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia));
return getBGDataFrom; return getBGDataFrom;
} }
@ -343,11 +358,11 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
@Nullable @Nullable
private Long findPreviousTimeFromBucketedData(long time) { public Long findPreviousTimeFromBucketedData(long time) {
if (bucketed_data == null) if (bucketed_data == null)
return null; return null;
for (int index = 0; index < bucketed_data.size(); index++) { for (int index = 0; index < bucketed_data.size(); index++) {
if (bucketed_data.get(index).date < time) if (bucketed_data.get(index).date <= time)
return bucketed_data.get(index).date; return bucketed_data.get(index).date;
} }
return null; return null;
@ -404,11 +419,13 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable @Nullable
public AutosensData getLastAutosensDataSynchronized(String reason) { public AutosensData getLastAutosensDataSynchronized(String reason) {
if (thread != null && thread.isAlive()) { if (thread != null && thread.isAlive()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason); log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason);
try { try {
thread.join(5000); thread.join(5000);
} catch (InterruptedException ignored) { } catch (InterruptedException ignored) {
} }
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA finished waiting for calculation thread: " + reason); log.debug("AUTOSENSDATA finished waiting for calculation thread: " + reason);
} }
synchronized (dataLock) { synchronized (dataLock) {
@ -447,6 +464,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable @Nullable
public AutosensData getLastAutosensData(String reason) { public AutosensData getLastAutosensData(String reason) {
if (autosensDataTable.size() < 1) { if (autosensDataTable.size() < 1) {
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")"); log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")");
return null; return null;
} }
@ -461,9 +479,11 @@ public class IobCobCalculatorPlugin extends PluginBase {
return null; return null;
} }
if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) { if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) {
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time)); log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time));
return null; return null;
} else { } else {
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA (" + reason + ") " + data.toString()); log.debug("AUTOSENSDATA (" + reason + ") " + data.toString());
return data; return data;
} }
@ -510,7 +530,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) {
synchronized (dataLock) { synchronized (dataLock) {
return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime); return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(this, fromTime, toTime);
} }
} }
@ -526,41 +546,46 @@ public class IobCobCalculatorPlugin extends PluginBase {
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void onEventAppInitialized(EventAppInitialized ev) { public void onEventAppInitialized(EventAppInitialized ev) {
if (this != getPlugin()) { if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance"); log.debug("Ignoring event for non default instance");
return; return;
} }
runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, ev); runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev);
} }
@Subscribe @Subscribe
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void onEventNewBG(EventNewBG ev) { public void onEventNewBG(EventNewBG ev) {
if (this != getPlugin()) { if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance"); log.debug("Ignoring event for non default instance");
return; return;
} }
stopCalculation("onEventNewBG"); stopCalculation("onEventNewBG");
runCalculation("onEventNewBG", System.currentTimeMillis(), true, ev); runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, ev);
} }
private void stopCalculation(String from) { public void stopCalculation(String from) {
if (thread != null && thread.getState() != Thread.State.TERMINATED) { if (thread != null && thread.getState() != Thread.State.TERMINATED) {
stopCalculationTrigger = true; stopCalculationTrigger = true;
if (L.isEnabled(L.AUTOSENS))
log.debug("Stopping calculation thread: " + from); log.debug("Stopping calculation thread: " + from);
while (thread.getState() != Thread.State.TERMINATED) { while (thread.getState() != Thread.State.TERMINATED) {
SystemClock.sleep(100); SystemClock.sleep(100);
} }
if (L.isEnabled(L.AUTOSENS))
log.debug("Calculation thread stopped: " + from); log.debug("Calculation thread stopped: " + from);
} }
} }
public void runCalculation(String from, long start, boolean bgDataReload, Event cause) { public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) {
log.debug("Starting calculation thread: " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end));
if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (thread == null || thread.getState() == Thread.State.TERMINATED) {
if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY))
thread = new IobCobOref1Thread(this, from, start, bgDataReload, cause); thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause);
else else
thread = new IobCobThread(this, from, start, bgDataReload, cause); thread = new IobCobThread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause);
thread.start(); thread.start();
} }
} }
@ -568,12 +593,13 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe @Subscribe
public void onNewProfile(EventNewBasalProfile ev) { public void onNewProfile(EventNewBasalProfile ev) {
if (this != getPlugin()) { if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance"); log.debug("Ignoring event for non default instance");
return; return;
} }
if (MainApp.getConfigBuilder() == null) if (MainApp.getConfigBuilder() == null)
return; // app still initializing return; // app still initializing
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) if (profile == null)
return; // app still initializing return; // app still initializing
dia = profile.getDia(); dia = profile.getDia();
@ -582,16 +608,18 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
stopCalculation("onNewProfile"); stopCalculation("onNewProfile");
synchronized (dataLock) { synchronized (dataLock) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
runCalculation("onNewProfile", System.currentTimeMillis(), false, ev); runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev);
} }
@Subscribe @Subscribe
public void onEventPreferenceChange(EventPreferenceChange ev) { public void onEventPreferenceChange(EventPreferenceChange ev) {
if (this != getPlugin()) { if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance"); log.debug("Ignoring event for non default instance");
return; return;
} }
@ -605,33 +633,37 @@ public class IobCobCalculatorPlugin extends PluginBase {
) { ) {
stopCalculation("onEventPreferenceChange"); stopCalculation("onEventPreferenceChange");
synchronized (dataLock) { synchronized (dataLock) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, ev); runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, ev);
} }
} }
@Subscribe @Subscribe
public void onEventConfigBuilderChange(EventConfigBuilderChange ev) { public void onEventConfigBuilderChange(EventConfigBuilderChange ev) {
if (this != getPlugin()) { if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance"); log.debug("Ignoring event for non default instance");
return; return;
} }
stopCalculation("onEventConfigBuilderChange"); stopCalculation("onEventConfigBuilderChange");
synchronized (dataLock) { synchronized (dataLock) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, ev); runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, ev);
} }
// When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated
@Subscribe @Subscribe
public void onEventNewHistoryData(EventNewHistoryData ev) { public void onEventNewHistoryData(EventNewHistoryData ev) {
if (this != getPlugin()) { if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance"); log.debug("Ignoring event for non default instance");
return; return;
} }
@ -640,11 +672,12 @@ public class IobCobCalculatorPlugin extends PluginBase {
synchronized (dataLock) { synchronized (dataLock) {
// clear up 5 min back for proper COB calculation // clear up 5 min back for proper COB calculation
long time = ev.time - 5 * 60 * 1000L; long time = ev.time - 5 * 60 * 1000L;
log.debug("Invalidating cached data to: " + new Date(time).toLocaleString()); if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data to: " + DateUtil.dateAndTimeFullString(time));
for (int index = iobTable.size() - 1; index >= 0; index--) { for (int index = iobTable.size() - 1; index >= 0; index--) {
if (iobTable.keyAt(index) > time) { if (iobTable.keyAt(index) > time) {
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); log.debug("Removing from iobTable: " + DateUtil.dateAndTimeFullString(iobTable.keyAt(index)));
iobTable.removeAt(index); iobTable.removeAt(index);
} else { } else {
break; break;
@ -652,8 +685,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
for (int index = autosensDataTable.size() - 1; index >= 0; index--) { for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
if (autosensDataTable.keyAt(index) > time) { if (autosensDataTable.keyAt(index) > time) {
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString()); log.debug("Removing from autosensDataTable: " + DateUtil.dateAndTimeFullString(autosensDataTable.keyAt(index)));
autosensDataTable.removeAt(index); autosensDataTable.removeAt(index);
} else { } else {
break; break;
@ -661,20 +694,21 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
for (int index = basalDataTable.size() - 1; index >= 0; index--) { for (int index = basalDataTable.size() - 1; index >= 0; index--) {
if (basalDataTable.keyAt(index) > time) { if (basalDataTable.keyAt(index) > time) {
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString()); log.debug("Removing from basalDataTable: " + DateUtil.dateAndTimeFullString(basalDataTable.keyAt(index)));
basalDataTable.removeAt(index); basalDataTable.removeAt(index);
} else { } else {
break; break;
} }
} }
} }
runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, ev); runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, true, ev);
//log.debug("Releasing onNewHistoryData"); //log.debug("Releasing onNewHistoryData");
} }
public void clearCache() { public void clearCache() {
synchronized (dataLock) { synchronized (dataLock) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Clearing cached data."); log.debug("Clearing cached data.");
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();

View file

@ -17,7 +17,6 @@ import java.util.GregorianCalendar;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -26,9 +25,13 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
@ -43,24 +46,26 @@ import static java.util.Calendar.MINUTE;
*/ */
public class IobCobOref1Thread extends Thread { public class IobCobOref1Thread extends Thread {
private static Logger log = LoggerFactory.getLogger("AUTOSENS"); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private final Event cause; private final Event cause;
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
private boolean bgDataReload; private boolean bgDataReload;
private boolean limitDataToOldestAvailable;
private String from; private String from;
private long start; private long end;
private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mWakeLock;
public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long start, boolean bgDataReload, Event cause) { public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) {
super(); super();
this.iobCobCalculatorPlugin = plugin; this.iobCobCalculatorPlugin = plugin;
this.bgDataReload = bgDataReload; this.bgDataReload = bgDataReload;
this.limitDataToOldestAvailable = limitDataToOldestAvailable;
this.from = from; this.from = from;
this.cause = cause; this.cause = cause;
this.start = start; this.end = end;
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread");
@ -70,33 +75,38 @@ public class IobCobOref1Thread extends Thread {
public final void run() { public final void run() {
mWakeLock.acquire(); mWakeLock.acquire();
try { try {
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread started: " + from); log.debug("AUTOSENSDATA thread started: " + from);
if (MainApp.getConfigBuilder() == null) { if (MainApp.getConfigBuilder() == null) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from);
return; // app still initializing return; // app still initializing
} }
if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) { if (!ProfileFunctions.getInstance().isProfileValid("IobCobThread")) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (No profile): " + from); log.debug("Aborting calculation thread (No profile): " + from);
return; // app still initializing return; // app still initializing
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable);
synchronized (iobCobCalculatorPlugin.dataLock) { synchronized (iobCobCalculatorPlugin.dataLock) {
if (bgDataReload) { if (bgDataReload) {
iobCobCalculatorPlugin.loadBgData(start); iobCobCalculatorPlugin.loadBgData(end);
iobCobCalculatorPlugin.createBucketedData(); iobCobCalculatorPlugin.createBucketedData();
} }
List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData(); List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData();
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { if (bucketed_data == null || bucketed_data.size() < 3) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (No bucketed data available): " + from); log.debug("Aborting calculation thread (No bucketed data available): " + from);
return; return;
} }
long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date);
if (L.isEnabled(L.AUTOSENS))
log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString());
AutosensData previous = autosensDataTable.get(prevDataTime); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
@ -106,6 +116,7 @@ public class IobCobOref1Thread extends Thread {
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false; iobCobCalculatorPlugin.stopCalculationTrigger = false;
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (trigger): " + from); log.debug("Aborting calculation thread (trigger): " + from);
return; return;
} }
@ -121,13 +132,14 @@ public class IobCobOref1Thread extends Thread {
continue; continue;
} }
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime); Profile profile = ProfileFunctions.getInstance().getProfile(bgTime);
if (profile == null) { if (profile == null) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (no profile): " + from); log.debug("Aborting calculation thread (no profile): " + from);
return; // profile not set yet return; // profile not set yet
} }
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")");
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
@ -166,15 +178,28 @@ public class IobCobOref1Thread extends Thread {
// https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169
if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope
long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L;
AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()); log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString());
int past = 1; int past = 1;
try { try {
for (; past < 12; past++) { for (; past < 12; past++) {
AutosensData ad = autosensDataTable.valueAt(initialIndex + past); AutosensData ad = autosensDataTable.valueAt(initialIndex + past);
if (L.isEnabled(L.AUTOSENS)) {
log.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null));
if (ad == null) {
log.debug(autosensDataTable.toString());
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
}
}
// let it here crash on NPE to get more data as i cannot reproduce this bug
double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5; double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5;
if (ad.avgDeviation > maxDeviation) { if (ad.avgDeviation > maxDeviation) {
slopeFromMaxDeviation = Math.min(0, deviationSlope); slopeFromMaxDeviation = Math.min(0, deviationSlope);
@ -185,7 +210,7 @@ public class IobCobOref1Thread extends Thread {
minDeviation = ad.avgDeviation; minDeviation = ad.avgDeviation;
} }
//if (Config.logAutosensData) //if (Config.isEnabled(L.AUTOSENS))
// log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation);
} }
} catch (Exception e) { } catch (Exception e) {
@ -198,7 +223,17 @@ public class IobCobOref1Thread extends Thread {
.putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()) .putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString())
.putCustomAttribute("past", past) .putCustomAttribute("past", past)
); );
log.debug(autosensDataTable.toString());
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
} }
} else {
if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null");
} }
} }
@ -338,13 +373,13 @@ public class IobCobOref1Thread extends Thread {
previous = autosensData; previous = autosensData;
if (bgTime < now()) if (bgTime < now())
autosensDataTable.put(bgTime, autosensData); autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime());
AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Sensitivity result: " + sensitivity.toString()); log.debug("Sensitivity result: " + sensitivity.toString());
autosensData.autosensResult = sensitivity; autosensData.autosensResult = sensitivity;
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug(autosensData.toString()); log.debug(autosensData.toString());
} }
} }
@ -355,6 +390,7 @@ public class IobCobOref1Thread extends Thread {
} finally { } finally {
mWakeLock.release(); mWakeLock.release();
MainApp.bus().post(new EventIobCalculationProgress("")); MainApp.bus().post(new EventIobCalculationProgress(""));
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread ended: " + from); log.debug("AUTOSENSDATA thread ended: " + from);
} }
} }

View file

@ -15,7 +15,6 @@ import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -24,9 +23,13 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
@ -42,24 +45,26 @@ import static info.nightscout.utils.DateUtil.now;
*/ */
public class IobCobThread extends Thread { public class IobCobThread extends Thread {
private static Logger log = LoggerFactory.getLogger("AUTOSENS"); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private final Event cause; private final Event cause;
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
private boolean bgDataReload; private boolean bgDataReload;
private boolean limitDataToOldestAvailable;
private String from; private String from;
private long start; private long end;
private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mWakeLock;
public IobCobThread(IobCobCalculatorPlugin plugin, String from, long start, boolean bgDataReload, Event cause) { public IobCobThread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) {
super(); super();
this.iobCobCalculatorPlugin = plugin; this.iobCobCalculatorPlugin = plugin;
this.bgDataReload = bgDataReload; this.bgDataReload = bgDataReload;
this.limitDataToOldestAvailable = limitDataToOldestAvailable;
this.from = from; this.from = from;
this.cause = cause; this.cause = cause;
this.start = start; this.end = end;
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread");
@ -69,33 +74,38 @@ public class IobCobThread extends Thread {
public final void run() { public final void run() {
mWakeLock.acquire(); mWakeLock.acquire();
try { try {
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread started: " + from); log.debug("AUTOSENSDATA thread started: " + from);
if (MainApp.getConfigBuilder() == null) { if (MainApp.getConfigBuilder() == null) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from);
return; // app still initializing return; // app still initializing
} }
if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) { if (!ProfileFunctions.getInstance().isProfileValid("IobCobThread")) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (No profile): " + from); log.debug("Aborting calculation thread (No profile): " + from);
return; // app still initializing return; // app still initializing
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable);
synchronized (iobCobCalculatorPlugin.dataLock) { synchronized (iobCobCalculatorPlugin.dataLock) {
if (bgDataReload) { if (bgDataReload) {
iobCobCalculatorPlugin.loadBgData(start); iobCobCalculatorPlugin.loadBgData(end);
iobCobCalculatorPlugin.createBucketedData(); iobCobCalculatorPlugin.createBucketedData();
} }
List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData(); List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData();
LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { if (bucketed_data == null || bucketed_data.size() < 3) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (No bucketed data available): " + from); log.debug("Aborting calculation thread (No bucketed data available): " + from);
return; return;
} }
long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date);
if (L.isEnabled(L.AUTOSENS))
log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString());
AutosensData previous = autosensDataTable.get(prevDataTime); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
@ -105,6 +115,7 @@ public class IobCobThread extends Thread {
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false; iobCobCalculatorPlugin.stopCalculationTrigger = false;
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (trigger): " + from); log.debug("Aborting calculation thread (trigger): " + from);
return; return;
} }
@ -120,13 +131,14 @@ public class IobCobThread extends Thread {
continue; continue;
} }
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime); Profile profile = ProfileFunctions.getInstance().getProfile(bgTime);
if (profile == null) { if (profile == null) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (no profile): " + from); log.debug("Aborting calculation thread (no profile): " + from);
return; // profile not set yet return; // profile not set yet
} }
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")");
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
@ -165,15 +177,28 @@ public class IobCobThread extends Thread {
// https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169
if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope
long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L;
AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()); log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString());
int past = 1; int past = 1;
try { try {
for (; past < 12; past++) { for (; past < 12; past++) {
AutosensData ad = autosensDataTable.valueAt(initialIndex + past); AutosensData ad = autosensDataTable.valueAt(initialIndex + past);
if (L.isEnabled(L.AUTOSENS)) {
log.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null));
if (ad == null) {
log.debug(autosensDataTable.toString());
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
}
}
// let it here crash on NPE to get more data as i cannot reproduce this bug
double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5; double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5;
if (ad.avgDeviation > maxDeviation) { if (ad.avgDeviation > maxDeviation) {
slopeFromMaxDeviation = Math.min(0, deviationSlope); slopeFromMaxDeviation = Math.min(0, deviationSlope);
@ -184,7 +209,7 @@ public class IobCobThread extends Thread {
minDeviation = ad.avgDeviation; minDeviation = ad.avgDeviation;
} }
//if (Config.logAutosensData) //if (Config.isEnabled(L.AUTOSENS))
// log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation);
} }
} catch (Exception e) { } catch (Exception e) {
@ -197,7 +222,17 @@ public class IobCobThread extends Thread {
.putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()) .putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString())
.putCustomAttribute("past", past) .putCustomAttribute("past", past)
); );
log.debug(autosensDataTable.toString());
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
} }
} else {
if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null");
} }
} }
@ -265,13 +300,13 @@ public class IobCobThread extends Thread {
previous = autosensData; previous = autosensData;
if (bgTime < now()) if (bgTime < now())
autosensDataTable.put(bgTime, autosensData); autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime());
AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Sensitivity result: " + sensitivity.toString()); log.debug("Sensitivity result: " + sensitivity.toString());
autosensData.autosensResult = sensitivity; autosensData.autosensResult = sensitivity;
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug(autosensData.toString()); log.debug(autosensData.toString());
} }
} }
@ -282,6 +317,7 @@ public class IobCobThread extends Thread {
} finally { } finally {
mWakeLock.release(); mWakeLock.release();
MainApp.bus().post(new EventIobCalculationProgress("")); MainApp.bus().post(new EventIobCalculationProgress(""));
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread ended: " + from); log.debug("AUTOSENSDATA thread ended: " + from);
} }
} }

View file

@ -15,21 +15,30 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
/** /**
* Created by mike on 09.06.2016. * Created by mike on 09.06.2016.
*/ */
public class APSResult { public class APSResult {
private static Logger log = LoggerFactory.getLogger(APSResult.class); private static Logger log = LoggerFactory.getLogger(L.APS);
public long date = 0; public long date = 0;
public String reason; public String reason;
public double rate; public double rate;
public int percent;
public boolean usePercent = false;
public int duration; public int duration;
public boolean tempBasalRequested = false; public boolean tempBasalRequested = false;
public boolean bolusRequested = false; public boolean bolusRequested = false;
@ -42,8 +51,39 @@ public class APSResult {
public Constraint<Double> inputConstraints; public Constraint<Double> inputConstraints;
public Constraint<Double> rateConstraint; public Constraint<Double> rateConstraint;
public Constraint<Integer> percentConstraint;
public Constraint<Double> smbConstraint; public Constraint<Double> smbConstraint;
public APSResult rate(double rate) {
this.rate = rate;
return this;
}
public APSResult duration(int duration) {
this.duration = duration;
return this;
}
public APSResult percent(int percent) {
this.percent = percent;
return this;
}
public APSResult tempBasalRequested(boolean tempBasalRequested) {
this.tempBasalRequested = tempBasalRequested;
return this;
}
public APSResult usePercent(boolean usePercent) {
this.usePercent = usePercent;
return this;
}
public APSResult json(JSONObject json) {
this.json = json;
return this;
}
@Override @Override
public String toString() { public String toString() {
final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
@ -54,6 +94,10 @@ public class APSResult {
ret = MainApp.gs(R.string.canceltemp) + "\n"; ret = MainApp.gs(R.string.canceltemp) + "\n";
else if (rate == -1) else if (rate == -1)
ret = MainApp.gs(R.string.let_temp_basal_run) + "\n"; ret = MainApp.gs(R.string.let_temp_basal_run) + "\n";
else if (usePercent)
ret = MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)\n" +
MainApp.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n";
else else
ret = MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + ret = MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) \n" + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) \n" +
@ -79,9 +123,13 @@ public class APSResult {
ret = MainApp.gs(R.string.canceltemp) + "<br>"; ret = MainApp.gs(R.string.canceltemp) + "<br>";
else if (rate == -1) else if (rate == -1)
ret = MainApp.gs(R.string.let_temp_basal_run) + "<br>"; ret = MainApp.gs(R.string.let_temp_basal_run) + "<br>";
else if (usePercent)
ret = "<b>" + MainApp.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(percent) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.getBaseBasalRate() / 100d) + " U/h)<br>" +
"<b>" + MainApp.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
else else
ret = "<b>" + MainApp.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " + ret = "<b>" + MainApp.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) <br>" + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100d) + "%) <br>" +
"<b>" + MainApp.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>"; "<b>" + MainApp.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
// smb // smb
@ -100,21 +148,33 @@ public class APSResult {
public APSResult clone() { public APSResult clone() {
APSResult newResult = new APSResult(); APSResult newResult = new APSResult();
newResult.reason = reason; doClone(newResult);
return newResult;
}
protected void doClone(APSResult newResult) {
newResult.date = date;
newResult.reason = reason != null ? new String(reason) : null;
newResult.rate = rate; newResult.rate = rate;
newResult.duration = duration; newResult.duration = duration;
newResult.tempBasalRequested = tempBasalRequested; newResult.tempBasalRequested = tempBasalRequested;
newResult.bolusRequested = bolusRequested; newResult.bolusRequested = bolusRequested;
newResult.iob = iob; newResult.iob = iob;
newResult.json = json; try {
newResult.json = new JSONObject(json.toString());
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
newResult.hasPredictions = hasPredictions; newResult.hasPredictions = hasPredictions;
newResult.smb = smb; newResult.smb = smb;
newResult.deliverAt = deliverAt; newResult.deliverAt = deliverAt;
newResult.rateConstraint = rateConstraint; newResult.rateConstraint = rateConstraint;
newResult.smbConstraint = smbConstraint; newResult.smbConstraint = smbConstraint;
return newResult; newResult.percent = percent;
newResult.usePercent = usePercent;
} }
public JSONObject json() { public JSONObject json() {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
try { try {
@ -227,6 +287,114 @@ public class APSResult {
} }
public boolean isChangeRequested() { public boolean isChangeRequested() {
Constraint<Boolean> closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed();
// closed loop mode: handle change at driver level
if (closedLoopEnabled.value()) {
if (L.isEnabled(L.APS))
log.debug("DEFAULT: Closed mode");
return tempBasalRequested || bolusRequested; return tempBasalRequested || bolusRequested;
} }
// open loop mode: try to limit request
if (!tempBasalRequested && !bolusRequested) {
if (L.isEnabled(L.APS))
log.debug("FALSE: No request");
return false;
}
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (usePercent) {
if (activeTemp == null && percent == 100) {
if (L.isEnabled(L.APS))
log.debug("FALSE: No temp running, asking cancel temp");
return false;
}
if (activeTemp != null && Math.abs(percent - activeTemp.tempBasalConvertedToPercent(now, profile)) < pump.getPumpDescription().basalStep) {
if (L.isEnabled(L.APS))
log.debug("FALSE: Temp equal");
return false;
}
// always report zerotemp
if (percent == 0) {
if (L.isEnabled(L.APS))
log.debug("TRUE: Zero temp");
return true;
}
// always report hightemp
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
if (percent == pumpLimit) {
if (L.isEnabled(L.APS))
log.debug("TRUE: Pump limit");
return true;
}
}
// report change bigger than 30%
double percentMinChangeChange = SP.getDouble(R.string.key_loop_openmode_min_change, 30d);
percentMinChangeChange /= 100d;
double lowThreshold = 1 - percentMinChangeChange;
double highThreshold = 1 + percentMinChangeChange;
double change = percent / 100d;
if (activeTemp != null)
change = percent / (double) activeTemp.tempBasalConvertedToPercent(now, profile);
if (change < lowThreshold || change > highThreshold) {
if (L.isEnabled(L.APS))
log.debug("TRUE: Outside allowed range " + (change * 100d) + "%");
return true;
} else {
if (L.isEnabled(L.APS))
log.debug("TRUE: Inside allowed range " + (change * 100d) + "%");
return false;
}
} else {
if (activeTemp == null && rate == pump.getBaseBasalRate()) {
if (L.isEnabled(L.APS))
log.debug("FALSE: No temp running, asking cancel temp");
return false;
}
if (activeTemp != null && Math.abs(rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (L.isEnabled(L.APS))
log.debug("FALSE: Temp equal");
return false;
}
// always report zerotemp
if (rate == 0) {
if (L.isEnabled(L.APS))
log.debug("TRUE: Zero temp");
return true;
}
// always report hightemp
if (pump != null && pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
double pumpLimit = pump.getPumpDescription().pumpType.getTbrSettings().getMaxDose();
if (rate == pumpLimit) {
if (L.isEnabled(L.APS))
log.debug("TRUE: Pump limit");
return true;
}
}
// report change bigger than 30%
double percentMinChangeChange = SP.getDouble(R.string.key_loop_openmode_min_change, 30d);
percentMinChangeChange /= 100d;
double lowThreshold = 1 - percentMinChangeChange;
double highThreshold = 1 + percentMinChangeChange;
double change = rate / profile.getBasal();
if (activeTemp != null)
change = rate / activeTemp.tempBasalConvertedToAbsolute(now, profile);
if (change < lowThreshold || change > highThreshold) {
if (L.isEnabled(L.APS))
log.debug("TRUE: Outside allowed range " + (change * 100d) + "%");
return true;
} else {
if (L.isEnabled(L.APS))
log.debug("TRUE: Inside allowed range " + (change * 100d) + "%");
return false;
}
}
}
} }

View file

@ -1,17 +1,11 @@
package info.nightscout.androidaps.plugins.Loop; package info.nightscout.androidaps.plugins.Loop;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
/* /*
{ {
@ -371,7 +365,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
*/ */
public class DeviceStatus { public class DeviceStatus {
private static Logger log = LoggerFactory.getLogger(DeviceStatus.class); private static Logger log = LoggerFactory.getLogger(L.APS);
public String device = null; public String device = null;
public JSONObject pump = null; public JSONObject pump = null;
@ -381,12 +375,12 @@ public class DeviceStatus {
public int uploaderBattery = 0; public int uploaderBattery = 0;
public String created_at = null; public String created_at = null;
public JSONObject mongoRecord () { public JSONObject mongoRecord() {
JSONObject record = new JSONObject(); JSONObject record = new JSONObject();
try { try {
if (device != null) record.put("device" , device); if (device != null) record.put("device", device);
if (pump != null) record.put("pump" , pump); if (pump != null) record.put("pump", pump);
if (suggested != null) { if (suggested != null) {
JSONObject openaps = new JSONObject(); JSONObject openaps = new JSONObject();
if (enacted != null) openaps.put("enacted", enacted); if (enacted != null) openaps.put("enacted", enacted);
@ -395,7 +389,7 @@ public class DeviceStatus {
record.put("openaps", openaps); record.put("openaps", openaps);
} }
if (uploaderBattery != 0) record.put("uploaderBattery", uploaderBattery); if (uploaderBattery != 0) record.put("uploaderBattery", uploaderBattery);
if (created_at != null) record.put("created_at" , created_at); if (created_at != null) record.put("created_at", created_at);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }

View file

@ -28,8 +28,6 @@ import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
public class LoopFragment extends SubscriberFragment { public class LoopFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(LoopFragment.class);
@BindView(R.id.loop_run) @BindView(R.id.loop_run)
Button runNowButton; Button runNowButton;
@BindView(R.id.loop_lastrun) @BindView(R.id.loop_lastrun)

View file

@ -21,47 +21,58 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.T;
import info.nightscout.utils.ToastUtils;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class LoopPlugin extends PluginBase { public class LoopPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(LoopPlugin.class); private static Logger log = LoggerFactory.getLogger(L.APS);
public static final String CHANNEL_ID = "AndroidAPS-Openloop"; private static final String CHANNEL_ID = "AndroidAPS-Openloop";
long lastBgTriggeredRun = 0; private long lastBgTriggeredRun = 0;
protected static LoopPlugin loopPlugin; private static LoopPlugin loopPlugin;
@NonNull @NonNull
public static LoopPlugin getPlugin() { public static LoopPlugin getPlugin() {
@ -94,7 +105,7 @@ public class LoopPlugin extends PluginBase {
.fragmentClass(LoopFragment.class.getName()) .fragmentClass(LoopFragment.class.getName())
.pluginName(R.string.loop) .pluginName(R.string.loop)
.shortName(R.string.loop_shortname) .shortName(R.string.loop_shortname)
.preferencesId(R.xml.pref_closedmode) .preferencesId(R.xml.pref_loop)
.description(R.string.description_loop) .description(R.string.description_loop)
); );
loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L); loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L);
@ -138,9 +149,7 @@ public class LoopPlugin extends PluginBase {
* has current data to work with. However, autosens calculation can be triggered by multiple * has current data to work with. However, autosens calculation can be triggered by multiple
* sources and currently only a new BG should trigger a loop run. Hence we return early if * sources and currently only a new BG should trigger a loop run. Hence we return early if
* the event causing the calculation is not EventNewBg. * the event causing the calculation is not EventNewBg.
* * <p>
* Callers of {@link info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin#runCalculation(String, long, boolean, Event)}
* are sources triggering a calculation which triggers this method upon completion.
*/ */
@Subscribe @Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) { public void onStatusEvent(final EventAutosensCalculationFinished ev) {
@ -249,18 +258,19 @@ public class LoopPlugin extends PluginBase {
return isDisconnected; return isDisconnected;
} }
public synchronized void invoke(String initiator, boolean allowNotification){ public synchronized void invoke(String initiator, boolean allowNotification) {
invoke(initiator, allowNotification, false); invoke(initiator, allowNotification, false);
} }
public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) { public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) {
try { try {
if (Config.logFunctionCalls) if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator); log.debug("invoke from " + initiator);
Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed(); Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
if (!loopEnabled.value()) { if (!loopEnabled.value()) {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
if (L.isEnabled(L.APS))
log.debug(message); log.debug(message);
MainApp.bus().post(new EventLoopSetLastRunGui(message)); MainApp.bus().post(new EventLoopSetLastRunGui(message));
return; return;
@ -271,9 +281,10 @@ public class LoopPlugin extends PluginBase {
if (!isEnabled(PluginType.LOOP)) if (!isEnabled(PluginType.LOOP))
return; return;
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (!MainApp.getConfigBuilder().isProfileValid("Loop")) { if (!ProfileFunctions.getInstance().isProfileValid("Loop")) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected)); log.debug(MainApp.gs(R.string.noprofileselected));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return; return;
@ -294,16 +305,27 @@ public class LoopPlugin extends PluginBase {
return; return;
} }
// Prepare for pumps using % basals
if (pump.getPumpDescription().tempBasalStyle == PumpDescription.PERCENT) {
result.usePercent = true;
}
result.percent = (int) (result.rate / profile.getBasal() * 100);
// check rate for constrais // check rate for constrais
final APSResult resultAfterConstraints = result.clone(); final APSResult resultAfterConstraints = result.clone();
resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate); resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate);
resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent);
resultAfterConstraints.percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value();
resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb); resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb);
resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value(); resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value();
// safety check for multiple SMBs // safety check for multiple SMBs
long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requsted but still in 3 min interval"); log.debug("SMB requsted but still in 3 min interval");
resultAfterConstraints.smb = 0; resultAfterConstraints.smb = 0;
} }
@ -319,12 +341,14 @@ public class LoopPlugin extends PluginBase {
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
if (isSuspended()) { if (isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.loopsuspended)); log.debug(MainApp.gs(R.string.loopsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return; return;
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.pumpsuspended)); log.debug(MainApp.gs(R.string.pumpsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return; return;
@ -333,7 +357,7 @@ public class LoopPlugin extends PluginBase {
Constraint<Boolean> closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); Constraint<Boolean> closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed();
if (closedLoopEnabled.value()) { if (closedLoopEnabled.value()) {
if (result.isChangeRequested() if (resultAfterConstraints.isChangeRequested()
&& !ConfigBuilderPlugin.getCommandQueue().bolusInQueue() && !ConfigBuilderPlugin.getCommandQueue().bolusInQueue()
&& !ConfigBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BOLUS)) { && !ConfigBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BOLUS)) {
final PumpEnactResult waiting = new PumpEnactResult(); final PumpEnactResult waiting = new PumpEnactResult();
@ -344,13 +368,13 @@ public class LoopPlugin extends PluginBase {
lastRun.smbSetByPump = waiting; lastRun.smbSetByPump = waiting;
MainApp.bus().post(new EventLoopUpdateGui()); MainApp.bus().post(new EventLoopUpdateGui());
FabricPrivacy.getInstance().logCustom(new CustomEvent("APSRequest")); FabricPrivacy.getInstance().logCustom(new CustomEvent("APSRequest"));
MainApp.getConfigBuilder().applyTBRRequest(resultAfterConstraints, profile, new Callback() { applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override @Override
public void run() { public void run() {
if (result.enacted || result.success) { if (result.enacted || result.success) {
lastRun.tbrSetByPump = result; lastRun.tbrSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun; lastRun.lastEnact = lastRun.lastAPSRun;
MainApp.getConfigBuilder().applySMBRequest(resultAfterConstraints, new Callback() { applySMBRequest(resultAfterConstraints, new Callback() {
@Override @Override
public void run() { public void run() {
//Callback is only called if a bolus was acutally requested //Callback is only called if a bolus was acutally requested
@ -376,7 +400,7 @@ public class LoopPlugin extends PluginBase {
lastRun.smbSetByPump = null; lastRun.smbSetByPump = null;
} }
} else { } else {
if (result.isChangeRequested() && allowNotification) { if (resultAfterConstraints.isChangeRequested() && allowNotification) {
NotificationCompat.Builder builder = NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID); new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon) builder.setSmallIcon(R.drawable.notif_icon)
@ -385,7 +409,8 @@ public class LoopPlugin extends PluginBase {
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH) .setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_ALARM) .setCategory(Notification.CATEGORY_ALARM)
.setVisibility(Notification.VISIBILITY_PUBLIC); .setVisibility(Notification.VISIBILITY_PUBLIC)
.setLocalOnly(true);
// Creates an explicit intent for an Activity in your app // Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class); Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class);
@ -407,14 +432,243 @@ public class LoopPlugin extends PluginBase {
// mId allows you to update the notification later on. // mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build()); mNotificationManager.notify(Constants.notificationID, builder.build());
MainApp.bus().post(new EventNewOpenLoopNotification()); MainApp.bus().post(new EventNewOpenLoopNotification());
// Send to Wear
ActionStringHandler.handleInitiate("changeRequest");
} else if (allowNotification) {
// dismiss notifications
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
ActionStringHandler.handleInitiate("cancelChangeRequest");
} }
} }
MainApp.bus().post(new EventLoopUpdateGui()); MainApp.bus().post(new EventLoopUpdateGui());
} finally { } finally {
if (Config.logFunctionCalls) if (L.isEnabled(L.APS))
log.debug("invoke end"); log.debug("invoke end");
} }
} }
public void acceptChangeRequest() {
Profile profile = ProfileFunctions.getInstance().getProfile();
applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() {
@Override
public void run() {
if (result.enacted) {
lastRun.tbrSetByPump = result;
lastRun.lastEnact = new Date();
lastRun.lastOpenModeAccept = new Date();
NSUpload.uploadDeviceStatus();
ObjectivesPlugin objectivesPlugin = MainApp.getSpecificPlugin(ObjectivesPlugin.class);
if (objectivesPlugin != null) {
ObjectivesPlugin.getPlugin().manualEnacts++;
ObjectivesPlugin.getPlugin().saveProgress();
}
}
MainApp.bus().post(new EventAcceptOpenLoopChange());
}
});
FabricPrivacy.getInstance().logCustom(new CustomEvent("AcceptTemp"));
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
* TODO: update pump drivers to support APS request in %
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
boolean allowPercentage = VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return;
}
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if (request.usePercent && allowPercentage) {
if (request.percent == 100 && request.duration == 0) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().percent(request.percent).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& request.percent == activeTemp.percentRate) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().percent(request.percent)
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: tempBasalPercent()");
MainApp.getConfigBuilder().getCommandQueue().tempBasalPercent(request.percent, request.duration, false, profile, callback);
}
} else {
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: setTempBasalAbsolute()");
MainApp.getConfigBuilder().getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
}
public void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
long lastBolusTime = activeTreatments.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requested but still in 3 min interval");
if (callback != null) {
callback.result(new PumpEnactResult()
.comment(MainApp.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: bolus()");
MainApp.getConfigBuilder().getCommandQueue().bolus(detailedBolusInfo, callback);
}
public void disconnectPump(int durationInMinutes, Profile profile) {
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
MainApp.getConfigBuilder().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
MainApp.getConfigBuilder().getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
}
}
});
}
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
public void suspendLoop(int durationInMinutes) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
} }

View file

@ -0,0 +1,160 @@
package info.nightscout.androidaps.plugins.Maintenance;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.OKDialog;
import info.nightscout.utils.ToastUtils;
/**
* Created by mike on 03.07.2016.
*/
public class ImportExportPrefs {
private static Logger log = LoggerFactory.getLogger(L.CORE);
static File path = new File(Environment.getExternalStorageDirectory().toString());
static public final File file = new File(path, MainApp.gs(R.string.app_name) + "Preferences");
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
public static void verifyStoragePermissions(Fragment fragment) {
int permission = ContextCompat.checkSelfPermission(fragment.getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
fragment.requestPermissions(PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
}
public static void exportSharedPreferences(final Fragment f) {
exportSharedPreferences(f.getContext());
}
public static void exportSharedPreferences(final Context c) {
new AlertDialog.Builder(c)
.setMessage(MainApp.gs(R.string.export_to) + " " + file + " ?")
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
try {
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
Map<String, ?> prefsMap = prefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
pw.println(entry.getKey() + "::" + entry.getValue().toString());
}
pw.close();
fw.close();
ToastUtils.showToastInUiThread(c, MainApp.gs(R.string.exported));
} catch (FileNotFoundException e) {
ToastUtils.showToastInUiThread(c, MainApp.gs(R.string.filenotfound) + " " + file);
log.error("Unhandled exception", e);
} catch (IOException e) {
log.error("Unhandled exception", e);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
public static void importSharedPreferences(final Fragment fragment) {
importSharedPreferences(fragment.getContext());
}
public static void importSharedPreferences(final Context context) {
new AlertDialog.Builder(context)
.setMessage(MainApp.gs(R.string.import_from) + " " + file + " ?")
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
String line;
String[] lineParts;
try {
editor.clear();
editor.commit();
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
lineParts = line.split("::");
if (lineParts.length == 2) {
if (lineParts[1].equals("true") || lineParts[1].equals("false")) {
editor.putBoolean(lineParts[0], Boolean.parseBoolean(lineParts[1]));
} else {
editor.putString(lineParts[0], lineParts[1]);
}
}
}
reader.close();
editor.commit();
OKDialog.show(context, MainApp.gs(R.string.setting_imported), MainApp.gs(R.string.restartingapp), () -> {
log.debug("Exiting");
MainApp.instance().stopKeepAliveService();
MainApp.bus().post(new EventAppExit());
MainApp.closeDbHelper();
if (context instanceof Activity) {
((Activity)context).finish();
}
System.runFinalization();
System.exit(0);
});
} catch (FileNotFoundException e) {
ToastUtils.showToastInUiThread(context, MainApp.gs(R.string.filenotfound) + " " + file);
log.error("Unhandled exception", e);
} catch (IOException e) {
log.error("Unhandled exception", e);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
}

View file

@ -0,0 +1,29 @@
package info.nightscout.androidaps.plugins.Maintenance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import info.nightscout.androidaps.logging.L;
/**
* This class provides serveral methods for log-handling (eg. sending logs as emails).
*/
public class LoggerUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(L.CORE);
public static String SUFFIX = ".log.zip";
/**
* Returns the directory, in which the logs are stored on the system. This is configured in the
* logback.xml file.
*
* @return
*/
public static String getLogDirectory() {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
return lc.getProperty("EXT_FILES_DIR");
}
}

View file

@ -0,0 +1,83 @@
package info.nightscout.androidaps.plugins.Maintenance;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Food.FoodPlugin;
import info.nightscout.androidaps.plugins.Maintenance.activities.LogSettingActivity;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
/**
*
*/
public class MaintenanceFragment extends Fragment {
private Fragment f;
@Override
public void onResume() {
super.onResume();
this.f = this;
}
@Override
public void onPause() {
super.onPause();
this.f = null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.maintenance_fragment, container, false);
final Fragment f = this;
view.findViewById(R.id.log_send).setOnClickListener(view1 -> MaintenancePlugin.getPlugin().sendLogs());
view.findViewById(R.id.log_delete).setOnClickListener(view1 -> MaintenancePlugin.getPlugin().deleteLogs());
view.findViewById(R.id.nav_resetdb).setOnClickListener(view1 -> new AlertDialog.Builder(f.getContext())
.setTitle(R.string.nav_resetdb)
.setMessage(R.string.reset_db_confirm)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
MainApp.getDbHelper().resetDatabases();
// should be handled by Plugin-Interface and
// additional service interface and plugin registry
FoodPlugin.getPlugin().getService().resetFood();
TreatmentsPlugin.getPlugin().getService().resetTreatments();
})
.create()
.show());
view.findViewById(R.id.nav_export).setOnClickListener(view1 -> {
// start activity for checking permissions...
ImportExportPrefs.verifyStoragePermissions(f);
ImportExportPrefs.exportSharedPreferences(f);
});
view.findViewById(R.id.nav_import).setOnClickListener(view1 -> {
// start activity for checking permissions...
ImportExportPrefs.verifyStoragePermissions(f);
ImportExportPrefs.importSharedPreferences(f);
});
view.findViewById(R.id.nav_logsettings).setOnClickListener(view1 -> {
startActivity(new Intent(getActivity(), LogSettingActivity.class));
});
return view;
}
}

View file

@ -0,0 +1,261 @@
package info.nightscout.androidaps.plugins.Maintenance;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.utils.SP;
public class MaintenancePlugin extends PluginBase {
private static final Logger LOG = LoggerFactory.getLogger(L.CORE);
private final Context ctx;
private static MaintenancePlugin maintenancePlugin;
public static MaintenancePlugin getPlugin() {
return maintenancePlugin;
}
public static MaintenancePlugin initPlugin(Context ctx) {
if (maintenancePlugin == null) {
maintenancePlugin = new MaintenancePlugin(ctx);
}
return maintenancePlugin;
}
public MaintenancePlugin() {
// required for testing
super(null);
this.ctx = null;
}
MaintenancePlugin(Context ctx) {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(MaintenanceFragment.class.getName())
.alwayVisible(false)
.alwaysEnabled(true)
.pluginName(R.string.maintenance)
.shortName(R.string.maintenance_shortname)
.preferencesId(R.xml.pref_maintenance)
.description(R.string.description_maintenance)
);
this.ctx = ctx;
}
public void sendLogs() {
String recipient = SP.getString("key_maintenance_logs_email", "logs@androidaps.org");
int amount = SP.getInt("key_maintenance_logs_amount", 2);
String logDirectory = LoggerUtils.getLogDirectory();
List<File> logs = this.getLogfiles(logDirectory, amount);
File zipDir = this.ctx.getExternalFilesDir("exports");
File zipFile = new File(zipDir, this.constructName());
LOG.debug("zipFile: {}", zipFile.getAbsolutePath());
File zip = this.zipLogs(zipFile, logs);
Uri attachementUri = FileProvider.getUriForFile(this.ctx, BuildConfig.APPLICATION_ID + ".fileprovider", zip);
Intent emailIntent = this.sendMail(attachementUri, recipient, "Log Export");
LOG.debug("sending emailIntent");
ctx.startActivity(emailIntent);
}
//todo replace this with a call on startup of the application, specifically to remove
// unnecessary garbage from the log exports
public void deleteLogs() {
String logDirectory = LoggerUtils.getLogDirectory();
File logDir = new File(logDirectory);
File[] files = logDir.listFiles((file, name) -> name.startsWith("AndroidAPS")
&& name.endsWith(".zip"));
Arrays.sort(files, (f1, f2) -> f1.getName().compareTo(f2.getName()));
List<File> delFiles = Arrays.asList(files);
int amount = SP.getInt("key_logshipper_amount", 2);
int keepIndex = amount - 1;
if (keepIndex < delFiles.size()) {
delFiles = delFiles.subList(keepIndex, delFiles.size());
for (File file : delFiles) {
file.delete();
}
}
File exportDir = new File(logDirectory, "exports");
if (exportDir.exists()) {
File[] expFiles = exportDir.listFiles();
for (File file : expFiles) {
file.delete();
}
exportDir.delete();
}
}
/**
* returns a list of log files. The number of returned logs is given via the amount
* parameter.
*
* The log files are sorted by the name descending.
*
* @param directory
* @param amount
* @return
*/
public List<File> getLogfiles(String directory, int amount) {
LOG.debug("getting {} logs from directory {}", amount, directory);
File logDir = new File(directory);
File[] files = logDir.listFiles((file, name) -> name.startsWith("AndroidAPS")
&& (name.endsWith(".log")
|| (name.endsWith(".zip") && !name.endsWith(LoggerUtils.SUFFIX))));
Arrays.sort(files, (f1, f2) -> f2.getName().compareTo(f1.getName()));
List<File> result = Arrays.asList(files);
int toIndex = amount++;
if (toIndex > result.size()) {
toIndex = result.size();
}
LOG.debug("returning sublist 0 to {}", toIndex);
return result.subList(0, toIndex);
}
public File zipLogs(File zipFile, List<File> files) {
LOG.debug("creating zip {}", zipFile.getAbsolutePath());
try {
zip(zipFile, files);
} catch (IOException e) {
LOG.error("Cannot retrieve zip", e);
}
return zipFile;
}
/**
* construct the name of zip file which is used to export logs.
*
* The name is constructed using the following scheme:
* AndroidAPS_LOG_ + Long Time + .log.zip
*
* @return
*/
public String constructName() {
return "AndroidAPS_LOG_" + String.valueOf(new Date().getTime()) + LoggerUtils.SUFFIX;
}
public void zip(File zipFile, List<File> files) throws IOException {
final int BUFFER_SIZE = 2048;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
for (File file : files) {
byte data[] = new byte[BUFFER_SIZE];
try(FileInputStream fileInputStream = new FileInputStream( file )) {
try(BufferedInputStream origin = new BufferedInputStream(fileInputStream, BUFFER_SIZE)) {
ZipEntry entry = new ZipEntry(file.getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
}
}
}
out.close();
}
public static Intent sendMail(Uri attachementUri, String recipient, String subject) {
StringBuilder builder =new StringBuilder();
builder.append("ADD TIME OF EVENT HERE: " + System.lineSeparator());
builder.append("ADD ISSUE DESCRIPTION OR GITHUB ISSUE REFERENCE NUMBER: " + System.lineSeparator());
builder.append("-------------------------------------------------------" + System.lineSeparator());
builder.append(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator());
if (Config.NSCLIENT)
builder.append("NSCLIENT" + System.lineSeparator());
builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator());
builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator());
builder.append(MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName + System.lineSeparator());
if (MainApp.engineeringMode)
builder.append(MainApp.gs(R.string.engineering_mode_enabled));
return sendMail(attachementUri, recipient, subject, builder.toString());
}
/**
* send a mail with the given file to the recipients with the given subject.
*
* the returned intent should be used to really send the mail using
*
* startActivity(Intent.createChooser(emailIntent , "Send email..."));
*
* @param attachementUri
* @param recipient
* @param subject
* @param body
*
* @return
*/
public static Intent sendMail(Uri attachementUri, String recipient, String subject, String body) {
LOG.debug("sending email to {} with subject {}", recipient, subject);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{recipient});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
LOG.debug("put path {}", attachementUri.toString());
emailIntent.putExtra(Intent.EXTRA_STREAM, attachementUri);
emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return emailIntent;
}
}

View file

@ -0,0 +1,80 @@
package info.nightscout.androidaps.plugins.Maintenance.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
public class LogSettingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logsetting);
ButterKnife.bind(this);
createViewsForSettings(L.getLogElements());
}
private void createViewsForSettings(List<L.LogElement> elements) {
if (elements.size() == 0) return;
LinearLayout container = (LinearLayout) findViewById(R.id.logsettings_placeholder);
container.removeAllViews();
for (L.LogElement element : elements) {
PluginViewHolder pluginViewHolder = new PluginViewHolder(element);
container.addView(pluginViewHolder.getBaseView());
}
}
@OnClick(R.id.logsettings_reset)
public void onResetClick() {
L.resetToDefaults();
createViewsForSettings(L.getLogElements());
}
public class PluginViewHolder {
private Unbinder unbinder;
private L.LogElement element;
LinearLayout baseView;
@BindView(R.id.logsettings_description)
TextView description;
@BindView(R.id.logsettings_visibility)
CheckBox enabled;
public PluginViewHolder(L.LogElement element) {
this.element = element;
baseView = (LinearLayout) getLayoutInflater().inflate(R.layout.logsettings_item, null);
unbinder = ButterKnife.bind(this, baseView);
description.setText(element.name);
enabled.setChecked(element.enabled);
}
public View getBaseView() {
return baseView;
}
@OnClick(R.id.logsettings_visibility)
void onEnagledChanged() {
element.setEnabled(enabled.isChecked());
}
public void unbind() {
unbinder.unbind();
}
}
}

View file

@ -34,8 +34,6 @@ import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static Logger log = LoggerFactory.getLogger(NSClientFragment.class);
private TextView logTextView; private TextView logTextView;
private TextView queueTextView; private TextView queueTextView;
private TextView urlTextView; private TextView urlTextView;
@ -133,9 +131,7 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) { switch (buttonView.getId()) {
case R.id.nsclientinternal_paused: case R.id.nsclientinternal_paused:
SP.putBoolean(R.string.key_nsclientinternal_paused, isChecked); NSClientPlugin.getPlugin().pause(isChecked);
NSClientPlugin.getPlugin().paused = isChecked;
MainApp.bus().post(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
updateGUI(); updateGUI();
FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientPause")); FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientPause"));
break; break;
@ -156,10 +152,9 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
protected void updateGUI() { protected void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override
public void run() {
NSClientPlugin.getPlugin().updateLog(); NSClientPlugin.getPlugin().updateLog();
pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false));
logTextView.setText(NSClientPlugin.getPlugin().textLog); logTextView.setText(NSClientPlugin.getPlugin().textLog);
if (NSClientPlugin.getPlugin().autoscroll) { if (NSClientPlugin.getPlugin().autoscroll) {
logScrollview.fullScroll(ScrollView.FOCUS_DOWN); logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
@ -168,7 +163,6 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " <b>" + UploadQueue.size() + "</b>"); Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " <b>" + UploadQueue.size() + "</b>");
queueTextView.setText(queuetext); queueTextView.setText(queuetext);
statusTextView.setText(NSClientPlugin.getPlugin().status); statusTextView.setText(NSClientPlugin.getPlugin().status);
}
}); });
} }

View file

@ -29,6 +29,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI;
@ -37,7 +38,7 @@ import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
public class NSClientPlugin extends PluginBase { public class NSClientPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(NSClientPlugin.class); private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
static NSClientPlugin nsClientPlugin; static NSClientPlugin nsClientPlugin;
@ -53,8 +54,8 @@ public class NSClientPlugin extends PluginBase {
private final List<EventNSClientNewLog> listLog = new ArrayList<>(); private final List<EventNSClientNewLog> listLog = new ArrayList<>();
Spanned textLog = Html.fromHtml(""); Spanned textLog = Html.fromHtml("");
public boolean paused = false; public boolean paused;
boolean autoscroll = true; boolean autoscroll;
public String status = ""; public String status = "";
@ -72,7 +73,7 @@ public class NSClientPlugin extends PluginBase {
.description(R.string.description_ns_client) .description(R.string.description_ns_client)
); );
if (Config.NSCLIENT || Config.G5UPLOADER) { if (Config.NSCLIENT) {
pluginDescription.alwaysEnabled(true).visibleByDefault(true); pluginDescription.alwaysEnabled(true).visibleByDefault(true);
} }
paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false); paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false);
@ -132,11 +133,13 @@ public class NSClientPlugin extends PluginBase {
private ServiceConnection mConnection = new ServiceConnection() { private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
if (L.isEnabled(L.NSCLIENT))
log.debug("Service is disconnected"); log.debug("Service is disconnected");
nsClientService = null; nsClientService = null;
} }
public void onServiceConnected(ComponentName name, IBinder service) { public void onServiceConnected(ComponentName name, IBinder service) {
if (L.isEnabled(L.NSCLIENT))
log.debug("Service is connected"); log.debug("Service is connected");
NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service; NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service;
if (mLocalBinder != null) // is null when running in roboelectric if (mLocalBinder != null) // is null when running in roboelectric
@ -155,6 +158,7 @@ public class NSClientPlugin extends PluginBase {
@Subscribe @Subscribe
public void onStatusEvent(final EventNSClientNewLog ev) { public void onStatusEvent(final EventNSClientNewLog ev) {
addToLog(ev); addToLog(ev);
if (L.isEnabled(L.NSCLIENT))
log.debug(ev.action + " " + ev.logText); log.debug(ev.action + " " + ev.logText);
} }
@ -165,21 +169,16 @@ public class NSClientPlugin extends PluginBase {
} }
synchronized void clearLog() { synchronized void clearLog() {
handler.post(new Runnable() { handler.post(() -> {
@Override
public void run() {
synchronized (listLog) { synchronized (listLog) {
listLog.clear(); listLog.clear();
} }
MainApp.bus().post(new EventNSClientUpdateGUI()); MainApp.bus().post(new EventNSClientUpdateGUI());
}
}); });
} }
private synchronized void addToLog(final EventNSClientNewLog ev) { private synchronized void addToLog(final EventNSClientNewLog ev) {
handler.post(new Runnable() { handler.post(() -> {
@Override
public void run() {
synchronized (listLog) { synchronized (listLog) {
listLog.add(ev); listLog.add(ev);
// remove the first line if log is too large // remove the first line if log is too large
@ -188,7 +187,6 @@ public class NSClientPlugin extends PluginBase {
} }
} }
MainApp.bus().post(new EventNSClientUpdateGUI()); MainApp.bus().post(new EventNSClientUpdateGUI());
}
}); });
} }
@ -211,6 +209,12 @@ public class NSClientPlugin extends PluginBase {
nsClientService.resend(reason); nsClientService.resend(reason);
} }
public void pause(boolean newState) {
SP.putBoolean(R.string.key_nsclientinternal_paused, newState);
paused = newState;
MainApp.bus().post(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
}
public UploadQueue queue() { public UploadQueue queue() {
return NSClientService.uploadQueue; return NSClientService.uploadQueue;
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.utils; package info.nightscout.androidaps.plugins.NSClientInternal;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -8,6 +8,7 @@ import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray; import org.json.JSONArray;
@ -23,7 +24,9 @@ import java.util.Locale;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
@ -37,13 +40,16 @@ import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus; import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
import info.nightscout.utils.BatteryLevel;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.05.2017. * Created by mike on 26.05.2017.
*/ */
public class NSUpload { public class NSUpload {
private static Logger log = LoggerFactory.getLogger(NSUpload.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) { public static void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) {
try { try {
@ -52,6 +58,7 @@ public class NSUpload {
data.put("eventType", CareportalEvent.TEMPBASAL); data.put("eventType", CareportalEvent.TEMPBASAL);
data.put("duration", temporaryBasal.durationInMinutes); data.put("duration", temporaryBasal.durationInMinutes);
data.put("absolute", temporaryBasal.absoluteRate); data.put("absolute", temporaryBasal.absoluteRate);
data.put("rate", temporaryBasal.absoluteRate);
if (temporaryBasal.pumpId != 0) if (temporaryBasal.pumpId != 0)
data.put("pumpId", temporaryBasal.pumpId); data.put("pumpId", temporaryBasal.pumpId);
data.put("created_at", DateUtil.toISOString(temporaryBasal.date)); data.put("created_at", DateUtil.toISOString(temporaryBasal.date));
@ -65,7 +72,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -76,12 +83,16 @@ public class NSUpload {
try { try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false); boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
Profile profile = ProfileFunctions.getInstance().getProfile(temporaryBasal.date);
double absoluteRate = 0;
if (profile != null) {
absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d;
}
if (useAbsolute) { if (useAbsolute) {
TemporaryBasal t = temporaryBasal.clone(); TemporaryBasal t = temporaryBasal.clone();
t.isAbsolute = true; t.isAbsolute = true;
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile != null) { if (profile != null) {
t.absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d; t.absoluteRate = absoluteRate;
uploadTempBasalStartAbsolute(t, null); uploadTempBasalStartAbsolute(t, null);
} }
} else { } else {
@ -90,6 +101,8 @@ public class NSUpload {
data.put("eventType", CareportalEvent.TEMPBASAL); data.put("eventType", CareportalEvent.TEMPBASAL);
data.put("duration", temporaryBasal.durationInMinutes); data.put("duration", temporaryBasal.durationInMinutes);
data.put("percent", temporaryBasal.percentRate - 100); data.put("percent", temporaryBasal.percentRate - 100);
if (profile != null)
data.put("rate", absoluteRate);
if (temporaryBasal.pumpId != 0) if (temporaryBasal.pumpId != 0)
data.put("pumpId", temporaryBasal.pumpId); data.put("pumpId", temporaryBasal.pumpId);
data.put("created_at", DateUtil.toISOString(temporaryBasal.date)); data.put("created_at", DateUtil.toISOString(temporaryBasal.date));
@ -101,7 +114,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
} catch (JSONException e) { } catch (JSONException e) {
@ -127,7 +140,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -155,7 +168,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -183,7 +196,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -191,8 +204,8 @@ public class NSUpload {
} }
public static void uploadDeviceStatus() { public static void uploadDeviceStatus() {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
String profileName = MainApp.getConfigBuilder().getProfileName(); String profileName = ProfileFunctions.getInstance().getProfileName();
if (profile == null || profileName == null) { if (profile == null || profileName == null) {
log.error("Profile is null. Skipping upload"); log.error("Profile is null. Skipping upload");
@ -232,6 +245,7 @@ public class NSUpload {
deviceStatus.enacted.put("requested", requested); deviceStatus.enacted.put("requested", requested);
} }
} else { } else {
if (L.isEnabled(L.NSCLIENT))
log.debug("OpenAPS data too old to upload"); log.debug("OpenAPS data too old to upload");
} }
deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL; deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL;
@ -252,7 +266,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, deviceStatus.mongoRecord().toString()); DbLogger.dbAdd(intent, deviceStatus.mongoRecord().toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -298,7 +312,7 @@ public class NSUpload {
public static void uploadTempTarget(TempTarget tempTarget) { public static void uploadTempTarget(TempTarget tempTarget) {
try { try {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) { if (profile == null) {
log.error("Profile is null. Skipping upload"); log.error("Profile is null. Skipping upload");
@ -333,7 +347,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
} catch (JSONException e) { } catch (JSONException e) {
@ -381,7 +395,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -399,7 +413,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbRemove(intent, _id); DbLogger.dbRemove(intent, _id);
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -422,7 +436,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -452,7 +466,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
@ -476,7 +490,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
@ -490,7 +504,7 @@ public class NSUpload {
try { try {
data.put("eventType", "Note"); data.put("eventType", "Note");
data.put("created_at", DateUtil.toISOString(new Date())); data.put("created_at", DateUtil.toISOString(new Date()));
data.put("notes", MainApp.gs(R.string.androidaps_start)+" - "+ Build.MANUFACTURER + " "+ Build.MODEL); data.put("notes", MainApp.gs(R.string.androidaps_start) + " - " + Build.MANUFACTURER + " " + Build.MODEL);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
@ -498,7 +512,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
} }
@ -523,7 +537,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
@ -537,7 +551,7 @@ public class NSUpload {
Intent intent = new Intent(Intents.ACTION_DATABASE); Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle); intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
DbLogger.dbRemove(intent, _id); DbLogger.dbRemove(intent, _id);
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);

View file

@ -16,13 +16,14 @@ import java.sql.SQLException;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
/** /**
* Created by mike on 21.02.2016. * Created by mike on 21.02.2016.
*/ */
public class UploadQueue { public class UploadQueue {
private static Logger log = LoggerFactory.getLogger(UploadQueue.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static String status() { public static String status() {
return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS);
@ -43,16 +44,14 @@ public class UploadQueue {
public static void add(final DbRequest dbr) { public static void add(final DbRequest dbr) {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override if (L.isEnabled(L.NSCLIENT))
public void run() { log.debug("Adding to queue: " + dbr.data);
log.debug("QUEUE adding: " + dbr.data);
MainApp.getDbHelper().create(dbr); MainApp.getDbHelper().create(dbr);
NSClientPlugin plugin = NSClientPlugin.getPlugin(); NSClientPlugin plugin = NSClientPlugin.getPlugin();
if (plugin != null) { if (plugin != null) {
plugin.resend("newdata"); plugin.resend("newdata");
} }
}
}); });
} }
} }
@ -60,13 +59,12 @@ public class UploadQueue {
public static void clearQueue() { public static void clearQueue() {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override if (L.isEnabled(L.NSCLIENT))
public void run() { log.debug("ClearQueue");
log.debug("QUEUE ClearQueue");
MainApp.getDbHelper().deleteAllDbRequests(); MainApp.getDbHelper().deleteAllDbRequests();
if (L.isEnabled(L.NSCLIENT))
log.debug(status()); log.debug(status());
}
}); });
} }
} }
@ -74,9 +72,7 @@ public class UploadQueue {
public static void removeID(final JSONObject record) { public static void removeID(final JSONObject record) {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override
public void run() {
try { try {
String id; String id;
if (record.has("NSCLIENT_ID")) { if (record.has("NSCLIENT_ID")) {
@ -85,12 +81,12 @@ public class UploadQueue {
return; return;
} }
if (MainApp.getDbHelper().deleteDbRequest(id) == 1) { if (MainApp.getDbHelper().deleteDbRequest(id) == 1) {
if (L.isEnabled(L.NSCLIENT))
log.debug("Removed item from UploadQueue. " + UploadQueue.status()); log.debug("Removed item from UploadQueue. " + UploadQueue.status());
} }
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
}
}); });
} }
} }
@ -100,18 +96,17 @@ public class UploadQueue {
return; return;
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override
public void run() {
MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id);
} if (L.isEnabled(L.NSCLIENT))
log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status());
}); });
} }
} }
public String textList() { public String textList() {
String result = ""; String result = "";
CloseableIterator<DbRequest> iterator = null; CloseableIterator<DbRequest> iterator;
try { try {
iterator = MainApp.getDbHelper().getDbRequestInterator(); iterator = MainApp.getDbHelper().getDbRequestInterator();
try { try {

View file

@ -1,13 +1,13 @@
package info.nightscout.androidaps.plugins.NSClientInternal.acks; package info.nightscout.androidaps.plugins.NSClientInternal.acks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
import io.socket.client.Ack; import io.socket.client.Ack;
@ -15,16 +15,17 @@ import io.socket.client.Ack;
* Created by mike on 29.12.2015. * Created by mike on 29.12.2015.
*/ */
public class NSAddAck extends Event implements Ack { public class NSAddAck extends Event implements Ack {
private static Logger log = LoggerFactory.getLogger(NSAddAck.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public String _id = null; public String _id = null;
public String nsClientID = null; public String nsClientID = null;
public JSONObject json = null; public JSONObject json = null;
public void call(Object...args) {
public void call(Object... args) {
// Regular response // Regular response
try { try {
JSONArray responsearray = (JSONArray) (args[0]); JSONArray responsearray = (JSONArray) (args[0]);
JSONObject response = null; JSONObject response = null;
if (responsearray.length()>0) { if (responsearray.length() > 0) {
response = responsearray.getJSONObject(0); response = responsearray.getJSONObject(0);
_id = response.getString("_id"); _id = response.getString("_id");
json = response; json = response;
@ -35,6 +36,7 @@ public class NSAddAck extends Event implements Ack {
MainApp.bus().post(this); MainApp.bus().post(this);
return; return;
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e);
} }
// Check for not authorized // Check for not authorized
try { try {
@ -45,6 +47,7 @@ public class NSAddAck extends Event implements Ack {
MainApp.bus().post(new EventNSClientRestart()); MainApp.bus().post(new EventNSClientRestart());
return; return;
} }
if (L.isEnabled(L.NSCLIENT))
log.debug("DBACCESS " + response.getString("result")); log.debug("DBACCESS " + response.getString("result"));
} }
return; return;

View file

@ -7,15 +7,16 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import io.socket.client.Ack; import io.socket.client.Ack;
/** /**
* Created by mike on 21.02.2016. * Created by mike on 21.02.2016.
*/ */
public class NSUpdateAck extends Event implements Ack { public class NSUpdateAck extends Event implements Ack {
private static Logger log = LoggerFactory.getLogger(NSUpdateAck.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public boolean result = false; public boolean result = false;
public String _id = null; public String _id;
public String action; public String action;
public void call(Object...args) { public void call(Object...args) {
JSONObject response = (JSONObject)args[0]; JSONObject response = (JSONObject)args[0];
@ -29,6 +30,7 @@ public class NSUpdateAck extends Event implements Ack {
} }
MainApp.bus().post(this); MainApp.bus().post(this);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e);
} }
} }

View file

@ -2,18 +2,12 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSAlarm;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -22,7 +16,6 @@ import info.nightscout.utils.SP;
*/ */
public class BroadcastAckAlarm { public class BroadcastAckAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastAckAlarm.class);
public static void handleClearAlarm(NSAlarm originalAlarm, Context context, long silenceTimeInMsec) { public static void handleClearAlarm(NSAlarm originalAlarm, Context context, long silenceTimeInMsec) {
@ -35,7 +28,7 @@ public class BroadcastAckAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putInt("level", originalAlarm.getLevel()); bundle.putInt("level", originalAlarm.getLevel());
bundle.putString("group", originalAlarm.getGroup()); bundle.putString("group", originalAlarm.getGroup());

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastAlarm { public class BroadcastAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastAlarm.class);
public static void handleAlarm(JSONObject alarm, Context context) { public static void handleAlarm(JSONObject alarm, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", alarm.toString()); bundle.putString("data", alarm.toString());
@ -31,7 +24,7 @@ public class BroadcastAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", alarm.toString()); bundle.putString("data", alarm.toString());
intent = new Intent(Intents.ACTION_ALARM); intent = new Intent(Intents.ACTION_ALARM);

View file

@ -2,28 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastAnnouncement { public class BroadcastAnnouncement {
private static Logger log = LoggerFactory.getLogger(BroadcastAnnouncement.class);
public static void handleAnnouncement(JSONObject announcement, Context context) { public static void handleAnnouncement(JSONObject announcement, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", announcement.toString()); bundle.putString("data", announcement.toString());
@ -32,7 +24,7 @@ public class BroadcastAnnouncement {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", announcement.toString()); bundle.putString("data", announcement.toString());
intent = new Intent(Intents.ACTION_ANNOUNCEMENT); intent = new Intent(Intents.ACTION_ANNOUNCEMENT);

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastCals { public class BroadcastCals {
private static Logger log = LoggerFactory.getLogger(BroadcastCals.class);
public static void handleNewCal(JSONArray cals, Context context, boolean isDelta) { public static void handleNewCal(JSONArray cals, Context context, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -33,7 +26,7 @@ public class BroadcastCals {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("cals", cals.toString()); bundle.putString("cals", cals.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastClearAlarm { public class BroadcastClearAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastClearAlarm.class);
public static void handleClearAlarm(JSONObject clearalarm, Context context) { public static void handleClearAlarm(JSONObject clearalarm, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", clearalarm.toString()); bundle.putString("data", clearalarm.toString());
@ -31,7 +24,7 @@ public class BroadcastClearAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", clearalarm.toString()); bundle.putString("data", clearalarm.toString());
intent = new Intent(Intents.ACTION_CLEAR_ALARM); intent = new Intent(Intents.ACTION_CLEAR_ALARM);

View file

@ -2,45 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class BroadcastDeviceStatus { public class BroadcastDeviceStatus {
private static Logger log = LoggerFactory.getLogger(BroadcastDeviceStatus.class);
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);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
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 static void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) { public static void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(statuses); List<JSONArray> splitted = BroadcastTreatment.splitArray(statuses);
@ -54,7 +29,7 @@ public class BroadcastDeviceStatus {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
splitted = BroadcastTreatment.splitArray(statuses); splitted = BroadcastTreatment.splitArray(statuses);
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -67,31 +42,4 @@ public class BroadcastDeviceStatus {
} }
} }
} }
public static void handleNewFoods(JSONArray foods, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(foods);
for (JSONArray part: splitted) {
Bundle bundle = new Bundle();
bundle.putString("foods", part.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_FOOD);
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(foods);
for (JSONArray part : splitted) {
Bundle bundle = new Bundle();
bundle.putString("foods", part.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_FOOD);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
}
}
}
} }

View file

@ -6,26 +6,18 @@ import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 20.02.2016. * Created by mike on 20.02.2016.
*/ */
public class BroadcastFood { public class BroadcastFood {
private static Logger log = LoggerFactory.getLogger(BroadcastFood.class);
public static void handleNewFood(JSONArray foods, Context context, boolean isDelta) { public static void handleNewFood(JSONArray foods, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(foods); List<JSONArray> splitted = BroadcastTreatment.splitArray(foods);
@ -39,7 +31,7 @@ public class BroadcastFood {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("foods", part.toString()); bundle.putString("foods", part.toString());
@ -65,7 +57,7 @@ public class BroadcastFood {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("foods", part.toString()); bundle.putString("foods", part.toString());
@ -89,7 +81,7 @@ public class BroadcastFood {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("foods", foods.toString()); bundle.putString("foods", foods.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastMbgs { public class BroadcastMbgs {
private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class);
public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) { public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -33,7 +26,7 @@ public class BroadcastMbgs {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("mbgs", mbgs.toString()); bundle.putString("mbgs", mbgs.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -2,18 +2,12 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -22,8 +16,6 @@ import info.nightscout.utils.SP;
* Created by mike on 20.02.2016. * Created by mike on 20.02.2016.
*/ */
public class BroadcastProfile { public class BroadcastProfile {
private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class);
public static void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) { public static void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -34,7 +26,7 @@ public class BroadcastProfile {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("profile", profile.getData().toString()); bundle.putString("profile", profile.getData().toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -1,35 +0,0 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.utils.SP;
/**
* Created by mike on 28.02.2016.
*/
public class BroadcastQueueStatus {
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");
wakeLock.acquire();
try {
Bundle bundle = new Bundle();
bundle.putInt("size", size);
Intent intent = new Intent(Intents.ACTION_QUEUE_STATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
} finally {
wakeLock.release();
}
}
}

View file

@ -2,49 +2,22 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 22.02.2016. * Created by mike on 22.02.2016.
*/ */
public class BroadcastSgvs { public class BroadcastSgvs {
private static Logger log = LoggerFactory.getLogger(BroadcastSgvs.class);
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);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
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 static void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) { public static void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(sgvs); List<JSONArray> splitted = BroadcastTreatment.splitArray(sgvs);
@ -58,7 +31,7 @@ public class BroadcastSgvs {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("sgvs", part.toString()); bundle.putString("sgvs", part.toString());

View file

@ -3,18 +3,16 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -23,13 +21,13 @@ import info.nightscout.utils.SP;
* Created by mike on 24.02.2016. * Created by mike on 24.02.2016.
*/ */
public class BroadcastStatus { public class BroadcastStatus {
private static Logger log = LoggerFactory.getLogger(BroadcastStatus.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static void handleNewStatus(NSSettingsStatus status, Context context, boolean isDelta) { public static void handleNewStatus(NSSettingsStatus status, Context context, boolean isDelta) {
LocalBroadcastManager.getInstance(MainApp.instance()) LocalBroadcastManager.getInstance(MainApp.instance())
.sendBroadcast(createIntent(status, isDelta)); .sendBroadcast(createIntent(status, isDelta));
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
context.sendBroadcast(createIntent(status, isDelta)); context.sendBroadcast(createIntent(status, isDelta));
} }
} }

View file

@ -15,14 +15,15 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 20.02.2016. * Created by mike on 20.02.2016.
*/ */
public class BroadcastTreatment { public class BroadcastTreatment {
private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static void handleNewTreatment(JSONObject treatment, boolean isDelta, boolean isLocalBypass) { public static void handleNewTreatment(JSONObject treatment, boolean isDelta, boolean isLocalBypass) {
@ -35,7 +36,7 @@ public class BroadcastTreatment {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("treatment", treatment.toString()); bundle.putString("treatment", treatment.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);
@ -59,7 +60,7 @@ public class BroadcastTreatment {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
splitted = splitArray(treatments); splitted = splitArray(treatments);
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -73,28 +74,6 @@ public class BroadcastTreatment {
} }
} }
public void handleChangedTreatment(JSONObject treatment, 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);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
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);
MainApp.instance().getApplicationContext().sendBroadcast(intent);
}
}
public static void handleChangedTreatment(JSONArray treatments, boolean isDelta) { public static void handleChangedTreatment(JSONArray treatments, boolean isDelta) {
List<JSONArray> splitted = splitArray(treatments); List<JSONArray> splitted = splitArray(treatments);
@ -108,7 +87,7 @@ public class BroadcastTreatment {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
splitted = splitArray(treatments); splitted = splitArray(treatments);
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -122,28 +101,6 @@ public class BroadcastTreatment {
} }
} }
public static void handleRemovedTreatment(JSONObject treatment, 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);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
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);
MainApp.instance().getApplicationContext().sendBroadcast(intent);
}
}
public static void handleRemovedTreatment(JSONArray treatments, boolean isDelta) { public static void handleRemovedTreatment(JSONArray treatments, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -155,7 +112,7 @@ public class BroadcastTreatment {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("treatments", treatments.toString()); bundle.putString("treatments", treatments.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastUrgentAlarm { public class BroadcastUrgentAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastUrgentAlarm.class);
public static void handleUrgentAlarm(JSONObject urgentalarm, Context context) { public static void handleUrgentAlarm(JSONObject urgentalarm, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", urgentalarm.toString()); bundle.putString("data", urgentalarm.toString());
@ -31,7 +24,7 @@ public class BroadcastUrgentAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", urgentalarm.toString()); bundle.putString("data", urgentalarm.toString());
intent = new Intent(Intents.ACTION_URGENT_ALARM); intent = new Intent(Intents.ACTION_URGENT_ALARM);

Some files were not shown because too many files have changed in this diff Show more