- gradle fixes

- remove formatting changes
- moved plugins/general/overview/Dialogs/ to plugins/general/overview/dialogs/
- fixing treatment changes that are received from NS, and extending copying of data to ignore pumpId
This commit is contained in:
Andy Rozman 2019-04-10 16:24:16 +01:00
parent 26a50bbbc4
commit 7392eaeb58
47 changed files with 842 additions and 1329 deletions

View file

@ -1,276 +0,0 @@
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter()
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
classpath 'com.dicedmelon.gradle:jacoco-android:0.1.3'
}
}
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
apply plugin: "io.fabric"
apply plugin: "jacoco-android"
apply plugin: 'com.jakewharton.butterknife'
ext {
supportLibraryVersion = "27.1.1"
ormLiteVersion = "4.46"
powermockVersion = "1.7.3"
dexmakerVersion = "1.2"
butterknifeVersion = "8.8.1"
playServicesWearVersion = "10.2.1" // 10.2.1
}
repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter { url "https://jcenter.bintray.com/" }
}
def generateGitBuild = { ->
StringBuilder stringBuilder = new StringBuilder();
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--always'
standardOutput = stdout
}
String commitObject = stdout.toString().trim()
stringBuilder.append(commitObject)
} catch (ignored) {
stringBuilder.append('NoGitSystemAvailable')
}
return stringBuilder.toString()
}
def generateDate = { ->
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append((new Date()).format('yyyy.MM.dd-HH:mm'))
return stringBuilder.toString()
}
tasks.matching { it instanceof Test }.all {
testLogging.events = ["failed", "skipped", "started"]
testLogging.exceptionFormat = "full"
}
android {
compileSdkVersion 27
defaultConfig {
minSdkVersion 21
targetSdkVersion 25
multiDexEnabled true
versionCode 1500
// dev_version: 2.2.3-dev
version "medtronic-0.9.1-SNAPSHOT"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
buildConfigField "String", "DEV_VERSION", '"2.2.3-dev"'
buildConfigField "String", "DEV_DATE", '"7.4.2019"'
buildConfigField "String", "DEV_CHECKIN", '"a076b00363067fd43c83cbbd91cc964fa6978ddd"'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
// if you change minSdkVersion to less than 11, you need to change executeTask for wear
ndk {
moduleName "BleCommandUtil"
}
}
lintOptions {
// TODO remove once wear dependency com.google.android.gms:play-services-wearable:7.3.0
// has been upgraded (requiring significant code changes), which currently fails release
// build with a deprecation warning
// abortOnError false
// (disabled entirely to avoid reports on the error, which would still be displayed
// and it's easy to overlook that it's ignored)
checkReleaseBuilds false
disable 'MissingTranslation'
disable 'ExtraTranslation'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled(project.hasProperty('coverage'))
}
}
productFlavors {
flavorDimensions "standard"
full {
applicationId "info.nightscout.androidaps"
dimension "standard"
resValue "string", "app_name", "AndroidAPS"
versionName version
manifestPlaceholders = [
appIcon : "@mipmap/ic_launcher",
appIconRound: "@mipmap/ic_launcher_round"
]
}
pumpcontrol {
applicationId "info.nightscout.aapspumpcontrol"
dimension "standard"
resValue "string", "app_name", "Pumpcontrol"
versionName version + "-pumpcontrol"
manifestPlaceholders = [
appIcon : "@mipmap/ic_pumpcontrol",
appIconRound: "@null"
]
}
nsclient {
applicationId "info.nightscout.nsclient"
dimension "standard"
resValue "string", "app_name", "NSClient"
versionName version + "-nsclient"
manifestPlaceholders = [
appIcon : "@mipmap/ic_yellowowl",
appIconRound: "@null"
]
}
nsclient2 {
applicationId "info.nightscout.nsclient2"
dimension "standard"
resValue "string", "app_name", "NSClient2"
versionName version + "-nsclient"
manifestPlaceholders = [
appIcon : "@mipmap/ic_yellowowl",
appIconRound: "@null"
]
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests.returnDefaultValues = true
unitTests.includeAndroidResources = true
}
useLibrary "org.apache.http.legacy"
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
flatDir {
dirs 'libs'
}
}
}
configurations {
libs
}
dependencies {
wearApp project(':wear')
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.google.android.gms:play-services-wearable:16.0.1"
implementation 'com.google.firebase:firebase-core:16.0.8'
//implementation 'com.google.android.gms:play-services-auth:16.0.1'
//implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation("com.crashlytics.sdk.android:crashlytics:2.9.9@aar") {
transitive = true;
}
libs "MilosKozak:danars-support-lib:master@zip"
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:cardview-v7:${supportLibraryVersion}"
implementation "com.android.support:recyclerview-v7:${supportLibraryVersion}"
implementation "com.android.support:gridlayout-v7:${supportLibraryVersion}"
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation "com.android.support:design:${supportLibraryVersion}"
implementation "com.android.support:percent:${supportLibraryVersion}"
implementation "com.wdullaer:materialdatetimepicker:2.3.0"
implementation "com.squareup:otto:1.3.7"
implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}"
implementation "com.j256.ormlite:ormlite-android:${ormLiteVersion}"
implementation("com.github.tony19:logback-android-classic:1.1.1-6") {
exclude group: "com.google.android", module: "android"
}
implementation "org.apache.commons:commons-lang3:3.7"
implementation "org.slf4j:slf4j-api:1.7.21"
// Graphview cannot be upgraded
implementation "com.jjoe64:graphview:4.0.1"
implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.1.1"
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation(name: "android-edittext-validator-v1.3.4-mod", ext: "aar")
implementation 'com.madgag.spongycastle:core:1.58.0.0'
implementation("com.google.android:flexbox:0.3.0") {
exclude group: "com.android.support"
}
implementation("io.socket:socket.io-client:1.0.0") {
// excluding org.json which is provided by Android
exclude group: "org.json", module: "json"
}
implementation "com.google.code.gson:gson:2.8.2"
implementation "com.google.guava:guava:24.1-jre"
implementation "net.danlew:android.joda:2.9.9.1"
implementation "uk.com.robust-it:cloning:1.9.9"
implementation 'org.mozilla:rhino:1.7.7.2'
implementation "com.jakewharton:butterknife:${butterknifeVersion}"
annotationProcessor "com.jakewharton:butterknife-compiler:${butterknifeVersion}"
testImplementation "junit:junit:4.12"
testImplementation "org.json:json:20140107"
testImplementation "org.mockito:mockito-core:2.8.47"
testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4-rule:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4:${powermockVersion}"
testImplementation "joda-time:joda-time:2.9.9"
testImplementation "com.google.truth:truth:0.39"
testImplementation 'org.robolectric:robolectric:3.8'
testImplementation "org.skyscreamer:jsonassert:1.5.0"
testImplementation "org.hamcrest:hamcrest-all:1.3"
testImplementation "uk.org.lidalia:slf4j-test:1.2.0"
androidTestImplementation "org.mockito:mockito-core:2.8.47"
androidTestImplementation "com.google.dexmaker:dexmaker:${dexmakerVersion}"
androidTestImplementation "com.google.dexmaker:dexmaker-mockito:${dexmakerVersion}"
}
task unzip(type: Copy) {
def zipPath = configurations.libs.find { it.name.startsWith("danars") }
def zipFile = file(zipPath)
def outputDir = file("${buildDir}/unpacked/dist")
from zipTree(zipFile)
into outputDir
}
task copyLibs(dependsOn: unzip, type: Copy) {
def src = file("${buildDir}/unpacked/dist/danars-support-lib-master")
def target = file("src/main/jniLibs/")
from src
into target
}
task full_clean(type: Delete) {
delete file("src/main/jniLibs")
}
clean.dependsOn full_clean
preBuild.dependsOn copyLibs

1
app/build.gradle Symbolic link
View file

@ -0,0 +1 @@
/home/andy/Dropbox/workspaces/aaps/andy_AndroidAPS_Medtronic_Shared/app/build.gradle

View file

@ -47,15 +47,11 @@
</activity>
<activity android:name=".activities.PreferencesActivity" />
<activity
android:name=".plugins.general.overview.Dialogs.BolusProgressHelperActivity"
android:name=".plugins.general.overview.dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".plugins.general.overview.Dialogs.ErrorHelperActivity"
android:name=".plugins.general.overview.dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".plugins.general.overview.Dialogs.MessageHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".activities.AgreementActivity" />
<activity android:name=".plugins.pump.danaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.pump.danaR.activities.DanaRUserOptionsActivity" />
@ -80,7 +76,8 @@
<receiver
android:name=".receivers.DataReceiver"
android:enabled="true"
android:exported="true">
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<!-- Receive new SMS messages -->
@ -180,57 +177,57 @@
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_data" />
android:pathPrefix="/nightscout_watch_data"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_data_resend" />
android:pathPrefix="/nightscout_watch_data_resend"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_cancel_bolus" />
android:pathPrefix="/nightscout_watch_cancel_bolus"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_confirmactionstring" />
android:pathPrefix="/nightscout_watch_confirmactionstring"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_initiateactionstring" />
android:pathPrefix="/nightscout_watch_initiateactionstring"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/openwearsettings" />
android:pathPrefix="/openwearsettings"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/sendstatustowear" />
android:pathPrefix="/sendstatustowear"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/sendpreferencestowear" />
android:pathPrefix="/sendpreferencestowear"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_basal" />
android:pathPrefix="/nightscout_watch_basal"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_bolusprogress" />
android:pathPrefix="/nightscout_watch_bolusprogress"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_actionconfirmationrequest" />
android:pathPrefix="/nightscout_watch_actionconfirmationrequest"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_changeconfirmationrequest" />
android:pathPrefix="/nightscout_watch_changeconfirmationrequest"
android:scheme="wear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_cancelnotificationrequest" />
android:pathPrefix="/nightscout_watch_cancelnotificationrequest"
android:scheme="wear" />
</intent-filter>
</service>
<service
@ -262,38 +259,39 @@
<activity
android:name=".activities.SingleFragmentActivity"
android:theme="@style/AppTheme" />
<activity android:name=".plugins.general.maintenance.activities.LogSettingActivity"></activity>
<activity android:name=".plugins.general.maintenance.activities.LogSettingActivity" />
<activity
android:name=".plugins.pump.insight.activities.InsightPairingActivity"
android:theme="@style/AppTheme"
android:label="@string/insight_pairing" />
android:label="@string/insight_pairing"
android:theme="@style/AppTheme" />
<activity
android:name=".plugins.pump.insight.activities.InsightAlertActivity"
android:label="@string/pump_alert"
android:theme="@style/InsightAlertDialog" />
<activity
android:name=".plugins.pump.insight.activities.InsightPairingInformationActivity"
android:theme="@style/AppTheme"
android:label="@string/pairing_information" />
android:label="@string/pairing_information"
android:theme="@style/AppTheme" />
<!-- Medtronic service and activities -->
<service
android:name=".plugins.pump.medtronic.service.RileyLinkMedtronicService"
android:enabled="true"
android:exported="true" />
<activity
android:name=".plugins.general.overview.dialogs.MessageHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".plugins.pump.common.dialog.RileyLinkBLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpCommon.dialog.RileyLinkBLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity"
android:label="@string/title_activity_rileylink_settings"
android:theme="@style/Theme.AppCompat.NoTitle" />
<activity android:name=".plugins.pump.medtronic.dialog.MedtronicHistoryActivity" />
</application>

View file

@ -1,5 +1,25 @@
package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
@ -11,25 +31,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.OverlappingIntervals;
@ -437,6 +438,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
Log.d("DatabaseHelper", "WR: Firing EventNewBg");
MainApp.bus().post(new EventNewBG(bgReading));
scheduledBgPost = null;
}
@ -805,8 +807,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try {
String units = JsonHelper.safeGetString(trJson, "units", Constants.MGDL);
TempTarget tempTarget = new TempTarget().date(trJson.getLong("mills"))
.duration(JsonHelper.safeGetInt(trJson, "duration"))
TempTarget tempTarget = new TempTarget().date(trJson.getLong("mills")).duration(trJson.getInt("duration"))
.low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
.high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
.reason(JsonHelper.safeGetString(trJson, "reason", ""))._id(trJson.getString("_id"))

View file

@ -1,11 +1,12 @@
package info.nightscout.androidaps.db;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.util.Objects;
import info.nightscout.androidaps.logging.L;
@ -13,9 +14,9 @@ import info.nightscout.androidaps.logging.L;
* Created by mike on 20.09.2017.
*/
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS)
public class TDD {
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
@ -36,9 +37,7 @@ public class TDD {
}
public TDD() {
}
public TDD() { }
public TDD(long date, double bolus, double basal, double total){
this.date = date;
@ -46,15 +45,4 @@ public class TDD {
this.basal = basal;
this.total = total;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this) //
.add("date", date) //
.add("bolus", bolus) //
.add("basal", basal) //
.add("total", total) //
.toString();
}
}

View file

@ -3,16 +3,16 @@ package info.nightscout.androidaps.interfaces;
import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileIntervals;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.ProfileIntervals;
/**
* Created by mike on 14.06.2016.
@ -20,94 +20,48 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
public interface TreatmentsInterface {
void updateTotalIOBTreatments();
void updateTotalIOBTempBasals();
IobTotal getLastCalculationTreatments();
IobTotal getCalculationToTimeTreatments(long time);
IobTotal getLastCalculationTempBasals();
IobTotal getCalculationToTimeTempBasals(long time, Profile profile);
MealData getMealData();
List<Treatment> getTreatmentsFromHistory();
List<Treatment> getTreatments5MinBackFromHistory(long time);
List<Treatment> getTreatmentsFromHistoryXMinutesAgo(int minutesAgo);
long getLastBolusTime();
// real basals (not faked by extended bolus)
boolean isInHistoryRealTempBasalInProgress();
TemporaryBasal getRealTempBasalFromHistory(long time);
boolean addToHistoryTempBasal(TemporaryBasal tempBasal);
// basal that can be faked by extended boluses
boolean isTempBasalInProgress();
TemporaryBasal getTempBasalFromHistory(long time);
Intervals<TemporaryBasal> getTemporaryBasalsFromHistory();
boolean isInHistoryExtendedBoluslInProgress();
ExtendedBolus getExtendedBolusFromHistory(long time);
Intervals<ExtendedBolus> getExtendedBolusesFromHistory();
boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus);
boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate);
TempTarget getTempTargetFromHistory();
TempTarget getTempTargetFromHistory(long time);
Intervals<TempTarget> getTempTargetsFromHistory();
void addToHistoryTempTarget(TempTarget tempTarget);
ProfileSwitch getProfileSwitchFromHistory(long time);
ProfileIntervals<ProfileSwitch> getProfileSwitchesFromHistory();
void addToHistoryProfileSwitch(ProfileSwitch profileSwitch);
long oldestDataAvailable();
List<Treatment> getTreatmentsFromHistoryXMinutesAgo(int minutesAgo);
}

View file

@ -23,7 +23,7 @@ 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.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.FabricPrivacy;

View file

@ -1,9 +1,5 @@
package info.nightscout.androidaps.plugins.general.actions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
@ -44,8 +40,8 @@ import info.nightscout.androidaps.plugins.general.actions.dialogs.FillDialog;
import info.nightscout.androidaps.plugins.general.actions.dialogs.NewExtendedBolusDialog;
import info.nightscout.androidaps.plugins.general.actions.dialogs.NewTempBasalDialog;
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SingleClickButton;
@ -58,7 +54,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
static ActionsPlugin actionsPlugin = new ActionsPlugin();
static public ActionsPlugin getPlugin() {
return actionsPlugin;
}
@ -77,14 +72,14 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
private Map<String, CustomAction> pumpCustomActions = new HashMap<>();
private List<SingleClickButton> pumpCustomButtons = new ArrayList<>();
public ActionsFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.actions_fragment, container, false);
@ -119,47 +114,39 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
return null;
}
@Subscribe
public void onStatusEvent(final EventInitializationChanged ev) {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventRefreshOverview ev) {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventCustomActionsChanged ev) {
updateGUI();
}
@Override
protected void updateGUI() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null
&& ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
profileSwitch.setVisibility(View.VISIBLE);
} else {
profileSwitch.setVisibility(View.GONE);
@ -184,30 +171,27 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
else
profileSwitch.setVisibility(View.VISIBLE);
if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized()
|| pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE);
} else {
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(
System.currentTimeMillis());
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
if (activeExtendedBolus != null) {
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.VISIBLE);
extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " "
+ activeExtendedBolus.toString());
extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
} else {
extendedBolus.setVisibility(View.VISIBLE);
extendedBolusCancel.setVisibility(View.GONE);
}
}
if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) {
tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.GONE);
} else {
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(
System.currentTimeMillis());
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.VISIBLE);
@ -239,6 +223,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
});
}
View.OnClickListener pumpCustomActionsListener = v -> {
SingleClickButton btn = (SingleClickButton) v;
@ -260,7 +245,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
return;
}
// add new actions
List<CustomAction> customActions = activePump.getCustomActions();
if (customActions != null && customActions.size() > 0) {

View file

@ -35,7 +35,7 @@ import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.NumberPicker;

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.NumberPicker;
import info.nightscout.androidaps.utils.SafeParse;

View file

@ -24,7 +24,7 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.NumberPicker;
import info.nightscout.androidaps.utils.SafeParse;

View file

@ -1,5 +1,20 @@
package info.nightscout.androidaps.plugins.general.overview;
import static info.nightscout.androidaps.utils.DateUtil.now;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
@ -37,19 +52,6 @@ import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
@ -88,17 +90,17 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotifi
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.NewCarbsDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.NewInsulinDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.NewTreatmentDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.WizardDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.NewCarbsDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.NewInsulinDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.NewTreatmentDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.WizardDialog;
import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity;
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationRecyclerViewAdapter;
@ -119,7 +121,6 @@ import info.nightscout.androidaps.utils.BolusWizard;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.SP;
@ -127,9 +128,8 @@ import info.nightscout.androidaps.utils.SingleClickButton;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils;
import static info.nightscout.androidaps.utils.DateUtil.now;
public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
TextView timeView;
@ -197,18 +197,27 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
Handler sLoopHandler = new Handler();
Runnable sRefreshLoop = null;
public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN, DEVSLOPE}
public enum CHARTTYPE {
PRE,
BAS,
IOB,
COB,
DEV,
SEN,
DEVSLOPE
}
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledUpdate = null;
public OverviewFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// check screen width
final DisplayMetrics dm = new DisplayMetrics();
@ -346,6 +355,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return view;
}
private void setupChartMenu(View view) {
chartButton = (ImageButton)view.findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(v -> {
@ -367,48 +377,59 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.PRE.ordinal(), Menu.NONE, "Predictions");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)),
0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showprediction", true));
}
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
item = popup.getMenu().add(Menu.NONE, 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);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showbasals", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
item = popup.getMenu().add(Menu.NONE, 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);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showiob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
item = popup.getMenu().add(Menu.NONE, 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);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showcob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
item = popup.getMenu().add(Menu.NONE, 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);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdeviations", false));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
item = popup.getMenu().add(Menu.NONE, 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);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showratios", false));
@ -417,13 +438,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
item = popup.getMenu().add(Menu.NONE, 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);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)),
0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdevslope", false));
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == CHARTTYPE.PRE.ordinal()) {
@ -447,6 +470,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
});
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);
@ -462,8 +486,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
super.onCreateContextMenu(menu, v, menuInfo);
if (v == apsModeView) {
final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
final PumpDescription pumpDescription =
ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription();
final PumpDescription pumpDescription = ConfigBuilderPlugin.getPlugin().getActivePump()
.getPumpDescription();
if (!ProfileFunctions.getInstance().isProfileValid("ContexMenuCreation"))
return;
menu.setHeaderTitle(MainApp.gs(R.string.loop));
@ -494,7 +518,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
} else if (v == activeProfileView) {
menu.setHeaderTitle(MainApp.gs(R.string.profile));
menu.add(MainApp.gs(R.string.danar_viewprofile));
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null
&& ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
menu.add(MainApp.gs(R.string.careportal_profileswitch));
}
} else if (v == tempTargetView) {
@ -509,8 +534,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
private void showSuspendtPump(ContextMenu menu,
PumpDescription pumpDescription) {
private void showSuspendtPump(ContextMenu menu, PumpDescription pumpDescription) {
if (pumpDescription.tempDurationStep15mAllowed)
menu.add(MainApp.gs(R.string.disconnectpumpfor15m));
if (pumpDescription.tempDurationStep30mAllowed)
@ -520,6 +545,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
menu.add(MainApp.gs(R.string.disconnectpumpfor3h));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final Profile profile = ProfileFunctions.getInstance().getProfile();
@ -532,10 +558,12 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
ConfigBuilderPlugin.getPlugin().storeSettings("DisablingLoop");
updateGUI("suspendmenu");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),
MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
@ -548,15 +576,17 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
updateGUI("suspendmenu");
NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.gs(R.string.resume)) ||
item.getTitle().equals(MainApp.gs(R.string.reconnect))) {
} else if (item.getTitle().equals(MainApp.gs(R.string.resume))
|| item.getTitle().equals(MainApp.gs(R.string.reconnect))) {
loopPlugin.suspendTo(0L);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),
MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
@ -611,34 +641,23 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
} else if (item.getTitle().equals(MainApp.gs(R.string.eatingsoon))) {
DefaultValueHelper defHelper = new DefaultValueHelper();
double target = defHelper.determineEatingSoonTT(profile.getUnits());
TempTarget tempTarget = new TempTarget()
.date(System.currentTimeMillis())
.duration(defHelper.determineEatingSoonTTDuration())
.reason(MainApp.gs(R.string.eatingsoon))
.source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits()))
TempTarget tempTarget = new TempTarget().date(System.currentTimeMillis())
.duration(defHelper.determineEatingSoonTTDuration()).reason(MainApp.gs(R.string.eatingsoon))
.source(Source.USER).low(Profile.toMgdl(target, profile.getUnits()))
.high(Profile.toMgdl(target, profile.getUnits()));
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
} else if (item.getTitle().equals(MainApp.gs(R.string.activity))) {
DefaultValueHelper defHelper = new DefaultValueHelper();
double target = defHelper.determineActivityTT(profile.getUnits());
TempTarget tempTarget = new TempTarget()
.date(now())
.duration(defHelper.determineActivityTTDuration())
.reason(MainApp.gs(R.string.activity))
.source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits()))
.high(Profile.toMgdl(target, profile.getUnits()));
TempTarget tempTarget = new TempTarget().date(now()).duration(defHelper.determineActivityTTDuration())
.reason(MainApp.gs(R.string.activity)).source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits())).high(Profile.toMgdl(target, profile.getUnits()));
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
} else if (item.getTitle().equals(MainApp.gs(R.string.hypo))) {
DefaultValueHelper defHelper = new DefaultValueHelper();
double target = defHelper.determineHypoTT(profile.getUnits());
TempTarget tempTarget = new TempTarget()
.date(now())
.duration(defHelper.determineHypoTTDuration())
.reason(MainApp.gs(R.string.hypo))
.source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits()))
TempTarget tempTarget = new TempTarget().date(now()).duration(defHelper.determineHypoTTDuration())
.reason(MainApp.gs(R.string.hypo)).source(Source.USER).low(Profile.toMgdl(target, profile.getUnits()))
.high(Profile.toMgdl(target, profile.getUnits()));
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
} else if (item.getTitle().equals(MainApp.gs(R.string.custom))) {
@ -648,18 +667,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
newTTDialog.show(getFragmentManager(), "NewNSTreatmentDialog");
} else if (item.getTitle().equals(MainApp.gs(R.string.cancel))) {
TempTarget tempTarget = new TempTarget()
.source(Source.USER)
.date(now())
.duration(0)
.low(0)
.high(0);
TempTarget tempTarget = new TempTarget().source(Source.USER).date(now()).duration(0).low(0).high(0);
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
}
return super.onContextItemSelected(item);
}
@Override
public void onClick(View v) {
boolean xdrip = SourceXdripPlugin.getPlugin().isEnabled(PluginType.BGSOURCE);
@ -668,7 +683,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
String units = ProfileFunctions.getInstance().getProfileUnits();
FragmentManager manager = getFragmentManager();
// try to fix https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days
// try to fix
// https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days
// https://stackoverflow.com/questions/14860239/checking-if-state-is-saved-before-committing-a-fragmenttransaction
if (manager.isStateSaved())
return;
@ -719,13 +735,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
new NewCarbsDialog().show(manager, "CarbsDialog");
break;
case R.id.overview_pumpstatus:
if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized())
if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended()
|| !ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized())
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("RefreshClicked", null);
break;
}
}
public boolean openCgmApp(String packageName) {
PackageManager packageManager = getContext().getPackageManager();
try {
@ -737,14 +755,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
getContext().startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
new AlertDialog.Builder(getContext())
.setMessage(R.string.error_starting_cgm)
.setPositiveButton("OK", null)
new AlertDialog.Builder(getContext()).setMessage(R.string.error_starting_cgm).setPositiveButton("OK", null)
.show();
return false;
}
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
@ -756,16 +773,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return false;
}
private void onClickAcceptTemp() {
Profile profile = ProfileFunctions.getInstance().getProfile();
Context context = getContext();
if (context == null) return;
if (context == null)
return;
if (LoopPlugin.getPlugin().isEnabled(PluginType.LOOP) && profile != null) {
LoopPlugin.getPlugin().invoke("Accept temp button", false);
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.isChangeRequested()) {
if (finalLastRun != null && finalLastRun.lastAPSRun != null
&& finalLastRun.constraintsProcessed.isChangeRequested()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(MainApp.gs(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
@ -780,6 +800,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
void onClickQuickwizard() {
final BgReading actualBg = DatabaseHelper.actualBg();
final Profile profile = ProfileFunctions.getInstance().getProfile();
@ -816,16 +837,21 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
String confirmMessage = MainApp.gs(R.string.entertreatmentquestion);
Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value();
Double insulinAfterConstraints = MainApp.getConstraintChecker()
.applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker()
.applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value();
confirmMessage += "\n" + MainApp.gs(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + MainApp.gs(R.string.bolus) + ": "
+ formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01 || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01
|| !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.gs(R.string.treatmentdeliveryerror));
builder.setMessage(MainApp.gs(R.string.constraints_violation) + "\n" + MainApp.gs(R.string.changeyourinput));
builder.setMessage(MainApp.gs(R.string.constraints_violation) + "\n"
+ MainApp.gs(R.string.changeyourinput));
builder.setPositiveButton(MainApp.gs(R.string.ok), null);
builder.show();
return;
@ -838,7 +864,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
accepted = false;
builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage);
builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
builder.setPositiveButton(
MainApp.gs(R.string.ok),
(dialog, id) -> {
synchronized (builder) {
if (accepted) {
if (L.isEnabled(L.OVERVIEW))
@ -846,14 +874,17 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return;
}
accepted = true;
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01 || finalCarbsAfterConstraints > 0) {
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01
|| finalCarbsAfterConstraints > 0) {
if (wizard.superBolus) {
final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
if (loopPlugin.isEnabled(PluginType.LOOP)) {
loopPlugin.superBolusTo(System.currentTimeMillis() + T.hours(2).msecs());
MainApp.bus().post(new EventRefreshOverview("WizardDialog"));
}
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, 120, true, profile, new Callback() {
ConfigBuilderPlugin.getPlugin().getCommandQueue()
.tempBasalPercent(0, 120, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
@ -874,8 +905,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
detailedBolusInfo.context = context;
detailedBolusInfo.boluscalc = boluscalcJSON;
detailedBolusInfo.source = Source.USER;
if (finalInsulinAfterConstraints > 0 || ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() {
if (finalInsulinAfterConstraints > 0
|| ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo) {
ConfigBuilderPlugin.getPlugin().getCommandQueue()
.bolus(detailedBolusInfo, new Callback() {
@Override
public void run() {
if (!result.success) {
@ -901,6 +935,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
@Override
public void onPause() {
super.onPause();
@ -911,6 +946,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
unregisterForContextMenu(tempTargetView);
}
@Override
public void onResume() {
super.onResume();
@ -926,66 +962,79 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
updateGUI("onResume");
}
@Subscribe
public void onStatusEvent(final EventInitializationChanged ev) {
scheduleUpdateGUI("EventInitializationChanged");
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange ev) {
scheduleUpdateGUI("EventPreferenceChange");
}
@Subscribe
public void onStatusEvent(final EventRefreshOverview ev) {
scheduleUpdateGUI(ev.from);
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
scheduleUpdateGUI("EventAutosensCalculationFinished");
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
scheduleUpdateGUI("EventTreatmentChange");
}
@Subscribe
public void onStatusEvent(final EventCareportalEventChange ev) {
scheduleUpdateGUI("EventCareportalEventChange");
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
scheduleUpdateGUI("EventTempBasalChange");
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
scheduleUpdateGUI("EventExtendedBolusChange");
}
@Subscribe
public void onStatusEvent(final EventNewOpenLoopNotification ev) {
scheduleUpdateGUI("EventNewOpenLoopNotification");
}
@Subscribe
public void onStatusEvent(final EventAcceptOpenLoopChange ev) {
scheduleUpdateGUI("EventAcceptOpenLoopChange");
}
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
scheduleUpdateGUI("EventTempTargetChange");
}
@Subscribe
public void onStatusEvent(final EventProfileSwitchChange ev) {
scheduleUpdateGUI("EventProfileSwitchChange");
}
@Subscribe
public void onStatusEvent(final EventPumpStatusChanged s) {
Activity activity = getActivity();
@ -993,6 +1042,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
activity.runOnUiThread(() -> updatePumpStatus(s.textStatus()));
}
@Subscribe
public void onStatusEvent(final EventIobCalculationProgress e) {
Activity activity = getActivity();
@ -1003,6 +1053,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
});
}
private void hideTempRecommendation() {
Activity activity = getActivity();
if (activity != null)
@ -1012,14 +1063,16 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
});
}
private void clearNotification() {
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager notificationManager = (NotificationManager)MainApp.instance().getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
ActionStringHandler.handleInitiate("cancelChangeRequest");
}
private void updatePumpStatus(String status) {
if (!status.equals("")) {
pumpStatusView.setText(status);
@ -1031,8 +1084,10 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
public void scheduleUpdateGUI(final String from) {
class UpdateRunnable implements Runnable {
public void run() {
Activity activity = getActivity();
if (activity != null)
@ -1051,6 +1106,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
scheduledUpdate = worker.schedule(task, msec, TimeUnit.MILLISECONDS);
}
@SuppressLint("SetTextI18n")
public void updateGUI(final String from) {
if (L.isEnabled(L.OVERVIEW))
@ -1103,12 +1159,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null) {
if (deltaView != null)
deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
deltaView.setText("Δ "
+ Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL,
units) + " " + units);
if (deltaShortView != null)
deltaShortView.setText(Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units));
deltaShortView.setText(Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta
* Constants.MGDL_TO_MMOLL, units));
if (avgdeltaView != null)
avgdeltaView.setText("øΔ15m: " + Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
" øΔ40m: " + Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
avgdeltaView.setText("øΔ15m: "
+ Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta
* Constants.MGDL_TO_MMOLL, units)
+ " øΔ40m: "
+ Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta
* Constants.MGDL_TO_MMOLL, units));
} else {
if (deltaView != null)
deltaView.setText("Δ " + MainApp.gs(R.string.notavailable));
@ -1181,32 +1244,27 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// **** Temp button ****
if (acceptTempLayout != null) {
boolean showAcceptButton = !closedLoopEnabled.value(); // Open mode needed
showAcceptButton = showAcceptButton && finalLastRun != null && finalLastRun.lastAPSRun != null; // aps
// result
// must
// exist
showAcceptButton = showAcceptButton
&& (finalLastRun.lastOpenModeAccept == null || finalLastRun.lastOpenModeAccept.getTime() < finalLastRun.lastAPSRun
.getTime()); // never accepted or before last result
showAcceptButton = showAcceptButton && finalLastRun.constraintsProcessed.isChangeRequested(); // change is
// requested
showAcceptButton = showAcceptButton && finalLastRun != null && finalLastRun.lastAPSRun != null; // aps result must exist
showAcceptButton = showAcceptButton && (finalLastRun.lastOpenModeAccept == null || finalLastRun.lastOpenModeAccept.getTime() < finalLastRun.lastAPSRun.getTime()); // never accepted or before last result
showAcceptButton = showAcceptButton && finalLastRun.constraintsProcessed.isChangeRequested(); // change is requested
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended()
&& LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
acceptTempLayout.setVisibility(View.VISIBLE);
acceptTempButton.setText(MainApp.gs(R.string.setbasalquestion) + "\n"
+ finalLastRun.constraintsProcessed);
acceptTempButton.setText(MainApp.gs(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
} else {
acceptTempLayout.setVisibility(View.GONE);
}
}
// **** Calibration & CGM buttons ****
boolean xDripIsBgSource = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE);
boolean g5IsBgSource = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null && MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginType.BGSOURCE);
boolean xDripIsBgSource = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null
&& MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE);
boolean g5IsBgSource = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null
&& MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginType.BGSOURCE);
boolean bgAvailable = DatabaseHelper.actualBg() != null;
if (calibrationButton != null) {
if ((xDripIsBgSource || g5IsBgSource) && bgAvailable && SP.getBoolean(R.string.key_show_calibration_button, true)) {
if ((xDripIsBgSource || g5IsBgSource) && bgAvailable
&& SP.getBoolean(R.string.key_show_calibration_button, true)) {
calibrationButton.setVisibility(View.VISIBLE);
} else {
calibrationButton.setVisibility(View.GONE);
@ -1222,7 +1280,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(
System.currentTimeMillis());
String basalText = "";
if (shorttextmode) {
if (activeTemp != null) {
@ -1231,7 +1290,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
basalText = DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h";
}
baseBasalView.setOnClickListener(v -> {
String fullText = MainApp.gs(R.string.pump_basebasalrate_label) + ": " + DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h\n";
String fullText = MainApp.gs(R.string.pump_basebasalrate_label) + ": "
+ DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h\n";
if (activeTemp != null) {
fullText += MainApp.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull();
}
@ -1257,7 +1317,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
baseBasalView.setText(basalText);
final ExtendedBolus extendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
final ExtendedBolus extendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(
System.currentTimeMillis());
String extendedBolusText = "";
if (extendedBolusView != null) { // must not exists in all layouts
if (shorttextmode) {
@ -1271,7 +1332,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
extendedBolusView.setText(extendedBolusText);
if (Config.NSCLIENT) {
extendedBolusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.extendedbolus), extendedBolus.toString(), null));
extendedBolusView.setOnClickListener(v -> OKDialog.show(getActivity(),
MainApp.gs(R.string.extendedbolus), extendedBolus.toString(), null));
}
if (extendedBolusText.equals(""))
extendedBolusView.setVisibility(Config.NSCLIENT ? View.INVISIBLE : View.GONE);
@ -1292,7 +1354,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && lastBG != null && pump.isInitialized() && !pump.isSuspended()) {
quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs())
+ "g";
BolusWizard wizard = quickWizardEntry.doCalc(profile, tempTarget, lastBG, false);
text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.calculatedTotalInsulin) + "U";
quickWizardButton.setText(text);
@ -1304,8 +1367,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// **** Various treatment buttons ****
if (carbsButton != null) {
if (SP.getBoolean(R.string.key_show_carbs_button, true)
&& (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo ||
(pump.isInitialized() && !pump.isSuspended()))) {
&& (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo || (pump
.isInitialized() && !pump.isSuspended()))) {
carbsButton.setVisibility(View.VISIBLE);
} else {
carbsButton.setVisibility(View.GONE);
@ -1374,8 +1437,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
iobView.setText(iobtext);
} else {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "/"
+ DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "/" + DecimalFormatter.to2Decimal(basalIob.basaliob)
+ ")";
iobView.setText(iobtext);
}
@ -1416,7 +1479,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
if (iageView != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
double insulinAge = careportalEvent != null ? careportalEvent.getHoursFromStart() : Double.MAX_VALUE;
double insulinAge = careportalEvent != null ? careportalEvent.getHoursFromStart()
: Double.MAX_VALUE;
applyStatuslight(iageView, "INS", insulinAge, iageWarn, iageUrgent, Double.MAX_VALUE, true);
}
@ -1453,19 +1517,22 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// pump status from ns
if (pumpDeviceStatusView != null) {
pumpDeviceStatusView.setText(NSDeviceStatus.getInstance().getPumpStatus());
pumpDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.pump), NSDeviceStatus.getInstance().getExtendedPumpStatus(), null));
pumpDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.pump),
NSDeviceStatus.getInstance().getExtendedPumpStatus(), null));
}
// OpenAPS status from ns
if (openapsDeviceStatusView != null) {
openapsDeviceStatusView.setText(NSDeviceStatus.getInstance().getOpenApsStatus());
openapsDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.openaps), NSDeviceStatus.getInstance().getExtendedOpenApsStatus(), null));
openapsDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.openaps),
NSDeviceStatus.getInstance().getExtendedOpenApsStatus(), null));
}
// Uploader status from ns
if (uploaderDeviceStatusView != null) {
uploaderDeviceStatusView.setText(NSDeviceStatus.getInstance().getUploaderStatusSpanned());
uploaderDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null));
uploaderDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(),
MainApp.gs(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null));
}
// Sensitivity
@ -1504,17 +1571,18 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
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
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview
// specific
fromTime = toTime - T.hours(hoursToFetch).msecs();
endTime = toTime + T.hours(predHours).msecs();
} else {
hoursToFetch = rangeToDisplay;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview
// specific
fromTime = toTime - T.hours(hoursToFetch).msecs();
endTime = toTime;
}
final long now = System.currentTimeMillis();
// ------------------ 1st graph
@ -1528,8 +1596,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// **** BG ****
if (finalPredictionsAvailable && SP.getBoolean("showprediction", false))
graphData.addBgReadings(fromTime, toTime, lowLine, highLine,
apsResult.getPredictions());
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, apsResult.getPredictions());
else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
@ -1594,10 +1661,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
FragmentActivity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(() -> {
if (SP.getBoolean("showiob", true)
|| SP.getBoolean("showcob", true)
|| SP.getBoolean("showdeviations", false)
|| SP.getBoolean("showratios", false)
if (SP.getBoolean("showiob", true) || SP.getBoolean("showcob", true)
|| SP.getBoolean("showdeviations", false) || SP.getBoolean("showratios", false)
|| SP.getBoolean("showdevslope", false)) {
iobGraph.setVisibility(View.VISIBLE);
} else {
@ -1616,6 +1681,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
Profiler.log(log, from, updateGUIStart);
}
// Notifications
void updateNotifications() {
@ -1631,23 +1697,18 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
public static boolean useNewRibbonColors = true;
boolean useNewRibbonColors = true;
public int getBackgroundColor(OverviewColorScheme scheme) {
return MainApp.gc(scheme.getBackground(useNewRibbonColors));
}
public int getTextColor(OverviewColorScheme scheme) {
return MainApp.gc(scheme.getTextColor(useNewRibbonColors));
}
public static void applyStatuslight(TextView view, String text, double value, double warnThreshold,
double urgentThreshold, double invalid, boolean checkAscending) {
Function<Double, Boolean> check = checkAscending ? (Double threshold) -> value >= threshold
: (Double threshold) -> value <= threshold;
public static void applyStatuslight(TextView view, String text, double value, double warnThreshold, double urgentThreshold, double invalid, boolean checkAscending) {
Function<Double, Boolean> check = checkAscending ? (Double threshold) -> value >= threshold : (Double threshold) -> value <= threshold;
if (value != invalid) {
view.setText(text);
if (check.apply(urgentThreshold)) {

View file

@ -18,7 +18,7 @@ import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.QuickWizard;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.EditQuickWizardDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange;
import info.nightscout.androidaps.utils.DateUtil;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.app.Activity;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.content.Context;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.os.Bundle;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.content.Intent;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -16,7 +16,7 @@ import info.nightscout.androidaps.R;
public class MessageDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(MessageDialog.class);
// Button muteButton;
Button okButton;
TextView statusView;
MessageHelperActivity helperActivity;
@ -25,8 +25,6 @@ public class MessageDialog extends DialogFragment implements View.OnClickListene
static String title;
// static int soundId;
public MessageDialog() {
super();
}
@ -51,14 +49,11 @@ public class MessageDialog extends DialogFragment implements View.OnClickListene
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().setTitle(title);
View view = inflater.inflate(R.layout.overview_message_dialog, container, false);
// muteButton = (Button)view.findViewById(R.id.overview_error_mute);
okButton = (Button)view.findViewById(R.id.overview_message_ok);
statusView = (TextView)view.findViewById(R.id.overview_message_status);
// muteButton.setOnClickListener(this);
okButton.setOnClickListener(this);
setCancelable(false);
// startAlarm();
return view;
}
@ -86,7 +81,7 @@ public class MessageDialog extends DialogFragment implements View.OnClickListene
switch (view.getId()) {
case R.id.overview_message_ok:
log.debug("Error dialog ok button pressed");
log.debug("Message dialog ok button pressed");
dismiss();
break;
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
@ -9,16 +9,15 @@ public class MessageHelperActivity extends AppCompatActivity {
super();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MessageDialog messageDialog = new MessageDialog();
messageDialog.setHelperActivity(this);
messageDialog.setStatus(getIntent().getStringExtra("status"));
messageDialog.setTitle(getIntent().getStringExtra("title"));
messageDialog.show(this.getSupportFragmentManager(), "Message");
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.os.Bundle;
import android.os.HandlerThread;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.content.Context;
import android.content.Intent;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.content.Context;
import android.content.DialogInterface;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.app.Activity;
import android.content.Context;

View file

@ -43,7 +43,6 @@ public class WearPlugin extends PluginBase {
return wearPlugin;
}
public static WearPlugin initPlugin(Context ctx) {
if (wearPlugin == null) {
@ -53,15 +52,18 @@ public class WearPlugin extends PluginBase {
return wearPlugin;
}
WearPlugin(Context ctx) {
super(new PluginDescription().mainType(PluginType.GENERAL).fragmentClass(WearFragment.class.getName())
.pluginName(R.string.wear).shortName(R.string.wear_shortname).preferencesId(R.xml.pref_wear)
.description(R.string.description_wear));
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(WearFragment.class.getName())
.pluginName(R.string.wear)
.shortName(R.string.wear_shortname)
.preferencesId(R.xml.pref_wear)
.description(R.string.description_wear)
);
this.ctx = ctx;
}
@Override
protected void onStart() {
MainApp.bus().register(this);
@ -71,13 +73,11 @@ public class WearPlugin extends PluginBase {
super.onStart();
}
@Override
protected void onStop() {
MainApp.bus().unregister(this);
}
private void sendDataToWatch(boolean status, boolean basals, boolean bgValue) {
//Log.d(TAG, "WR: WearPlugin:sendDataToWatch (status=" + status + ",basals=" + basals + ",bgValue=" + bgValue + ")");
@ -89,30 +89,25 @@ public class WearPlugin extends PluginBase {
}
if (basals) {
ctx.startService(new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_BASALS));
ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BASALS));
}
if (status) {
ctx.startService(new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_STATUS));
ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_STATUS));
}
}
}
void resendDataToWatch() {
//Log.d(TAG, "WR: WearPlugin:resendDataToWatch");
ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_RESEND));
}
void openSettings() {
//Log.d(TAG, "WR: WearPlugin:openSettings");
ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_OPEN_SETTINGS));
}
void requestNotificationCancel(String actionstring) {
//Log.d(TAG, "WR: WearPlugin:requestNotificationCancel");
@ -131,43 +126,36 @@ public class WearPlugin extends PluginBase {
sendDataToWatch(true, false, false);
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
sendDataToWatch(true, true, false);
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
sendDataToWatch(true, true, false);
}
@Subscribe
public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
sendDataToWatch(true, true, false);
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
sendDataToWatch(true, true, false);
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
sendDataToWatch(true, true, true);
}
@Subscribe
public void onStatusEvent(final EventNewBasalProfile ev) {
sendDataToWatch(false, true, false);
}
@Subscribe
public void onStatusEvent(final EventRefreshOverview ev) {
if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) {
@ -179,31 +167,26 @@ public class WearPlugin extends PluginBase {
@Subscribe
public void onStatusEvent(final EventOverviewBolusProgress ev) {
if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) {
Intent intent = new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
intent.putExtra("progresspercent", ev.percent);
intent.putExtra("progressstatus", ev.status);
ctx.startService(intent);
}
}
@Subscribe
public void onStatusEvent(final EventBolusRequested ev) {
String status = String.format(MainApp.gs(R.string.bolusrequested), ev.getAmount());
Intent intent = new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
intent.putExtra("progresspercent", 0);
intent.putExtra("progressstatus", status);
ctx.startService(intent);
}
@Subscribe
public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) {
if (ev.result == null)
return;
if (ev.result == null) return;
String status;
if (ev.result.success) {
@ -211,41 +194,34 @@ public class WearPlugin extends PluginBase {
} else {
status = MainApp.gs(R.string.nosuccess);
}
Intent intent = new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
intent.putExtra("progresspercent", 100);
intent.putExtra("progressstatus", status);
ctx.startService(intent);
}
public void requestActionConfirmation(String title, String message, String actionstring) {
Intent intent = new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_ACTIONCONFIRMATIONREQUEST);
Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_ACTIONCONFIRMATIONREQUEST);
intent.putExtra("title", title);
intent.putExtra("message", message);
intent.putExtra("actionstring", actionstring);
ctx.startService(intent);
}
public void requestChangeConfirmation(String title, String message, String actionstring) {
Intent intent = new Intent(ctx, WatchUpdaterService.class)
.setAction(WatchUpdaterService.ACTION_SEND_CHANGECONFIRMATIONREQUEST);
Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_CHANGECONFIRMATIONREQUEST);
intent.putExtra("title", title);
intent.putExtra("message", message);
intent.putExtra("actionstring", actionstring);
ctx.startService(intent);
}
public static void registerWatchUpdaterService(WatchUpdaterService wus) {
watchUS = wus;
}
public static void unRegisterWatchUpdaterService() {
watchUS = null;
}

View file

@ -1,14 +1,5 @@
package info.nightscout.androidaps.plugins.iob.iobCobCalculator;
import static info.nightscout.androidaps.utils.DateUtil.now;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@ -16,6 +7,13 @@ import android.support.v4.util.LongSparseArray;
import com.squareup.otto.Subscribe;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -33,27 +31,27 @@ 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.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.T;
import static info.nightscout.androidaps.utils.DateUtil.now;
/**
* Created by mike on 24.04.2017.
*/
public class IobCobCalculatorPlugin extends PluginBase {
private Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private static IobCobCalculatorPlugin plugin = null;
public static IobCobCalculatorPlugin getPlugin() {
if (plugin == null)
plugin = new IobCobCalculatorPlugin();
@ -72,47 +70,44 @@ public class IobCobCalculatorPlugin extends PluginBase {
boolean stopCalculationTrigger = false;
private Thread thread = null;
public IobCobCalculatorPlugin() {
super(new PluginDescription().mainType(PluginType.GENERAL).pluginName(R.string.iobcobcalculator)
.showInList(false).neverVisible(true).alwaysEnabled(true));
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.pluginName(R.string.iobcobcalculator)
.showInList(false)
.neverVisible(true)
.alwaysEnabled(true)
);
}
@Override
protected void onStart() {
MainApp.bus().register(this);
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
MainApp.bus().unregister(this);
}
public LongSparseArray<AutosensData> getAutosensDataTable() {
return autosensDataTable;
}
public List<BgReading> getBgReadings() {
return bgReadings;
}
public void setBgReadings(List<BgReading> bgReadings) {
this.bgReadings = bgReadings;
}
public List<BgReading> getBucketedData() {
return bucketed_data;
}
// roundup to whole minute
public static long roundUpTime(long time) {
if (time % 60000 == 0)
@ -121,30 +116,24 @@ public class IobCobCalculatorPlugin extends PluginBase {
return rounded;
}
void loadBgData(long to) {
Profile profile = ProfileFunctions.getInstance().getProfile(to);
double dia = Constants.defaultDIA;
if (profile != null)
dia = profile.getDia();
if (profile != null) dia = profile.getDia();
long start = to - T.hours((long) (24 + dia)).msecs();
if (DateUtil.isCloseToNow(to)) {
// if close to now expect there can be some readings with time in close future (caused by wrong time
// setting)
// if close to now expect there can be some readings with time in close future (caused by wrong time setting)
// so read all records
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, false);
if (L.isEnabled(L.AUTOSENS))
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: "
+ DateUtil.dateAndTimeString(start));
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start));
} else {
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, to, false);
if (L.isEnabled(L.AUTOSENS))
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: "
+ DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(to));
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(to));
}
}
public boolean isAbout5minData() {
synchronized (dataLock) {
if (bgReadings == null || bgReadings.size() < 3) {
@ -162,21 +151,18 @@ public class IobCobCalculatorPlugin extends PluginBase {
diff = Math.abs(diff);
if (diff > T.secs(30).msecs()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000)
+ "[s] is5minData: " + false);
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "[s] is5minData: " + false);
return false;
}
}
long averageDiff = totalDiff / bgReadings.size() / 1000;
boolean is5mindata = averageDiff < 1;
if (L.isEnabled(L.AUTOSENS))
log.debug("Interval detection: values: " + bgReadings.size() + " averageDiff: " + averageDiff
+ "[s] is5minData: " + is5mindata);
log.debug("Interval detection: values: " + bgReadings.size() + " averageDiff: " + averageDiff + "[s] is5minData: " + is5mindata);
return is5mindata;
}
}
public void createBucketedData() {
if (isAbout5minData())
createBucketedData5min();
@ -184,43 +170,32 @@ public class IobCobCalculatorPlugin extends PluginBase {
createBucketedDataRecalculated();
}
@Nullable
public BgReading findNewer(long time) {
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) {
if (bgReadings.get(i).date == time)
return bgReadings.get(i);
if (bgReadings.get(i).date > time)
continue;
if (bgReadings.get(i).date == time) return bgReadings.get(i);
if (bgReadings.get(i).date > time) continue;
lastFound = bgReadings.get(i - 1);
if (bgReadings.get(i).date < time)
break;
if (bgReadings.get(i).date < time) break;
}
return lastFound;
}
@Nullable
public BgReading findOlder(long time) {
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) {
if (bgReadings.get(i).date == time)
return bgReadings.get(i);
if (bgReadings.get(i).date < time)
continue;
if (bgReadings.get(i).date == time) return bgReadings.get(i);
if (bgReadings.get(i).date < time) continue;
lastFound = bgReadings.get(i + 1);
if (bgReadings.get(i).date > time)
break;
if (bgReadings.get(i).date > time) break;
}
return lastFound;
}
private void createBucketedDataRecalculated() {
if (bgReadings == null || bgReadings.size() < 3) {
bucketed_data = null;
@ -249,9 +224,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
newBgreading.date = currentTime;
newBgreading.value = Math.round(currentBg);
bucketed_data.add(newBgreading);
// log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() +
// ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value +
// " (" + new Date(newer.date).toLocaleString() + ")");
//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 -= T.mins(5).msecs();
@ -268,14 +241,12 @@ public class IobCobCalculatorPlugin extends PluginBase {
bucketed_data = new ArrayList<>();
bucketed_data.add(bgReadings.get(0));
if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgReadings.get(0).date) + " lastbgTime: "
+ "none-first-value" + " " + bgReadings.get(0).toString());
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgReadings.get(0).date) + " lastbgTime: " + "none-first-value" + " " + bgReadings.get(0).toString());
int j = 0;
for (int i = 1; i < bgReadings.size(); ++i) {
long bgTime = bgReadings.get(i).date;
long lastbgTime = bgReadings.get(i - 1).date;
// log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + bgReadings.get(i).value +
// " Previous: " + new Date(lastbgTime).toString() + " " + bgReadings.get(i - 1).value);
//log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + bgReadings.get(i).value + " Previous: " + new Date(lastbgTime).toString() + " " + bgReadings.get(i - 1).value);
if (bgReadings.get(i).value < 39 || bgReadings.get(i - 1).value < 39) {
throw new IllegalStateException("<39");
}
@ -299,8 +270,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
//console.error("Interpolated", bucketed_data[j]);
bucketed_data.add(newBgreading);
if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: "
+ DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
elapsed_minutes = elapsed_minutes - 5;
lastbg = nextbg;
@ -312,8 +282,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
newBgreading.date = bgTime;
bucketed_data.add(newBgreading);
if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: "
+ DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
} else if (Math.abs(elapsed_minutes) > 2) {
j++;
BgReading newBgreading = new BgReading();
@ -321,8 +290,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
newBgreading.date = bgTime;
bucketed_data.add(newBgreading);
if (L.isEnabled(L.AUTOSENS))
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: "
+ DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
log.debug("Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString());
} else {
bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2;
//log.error("***** Average");
@ -336,8 +304,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
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");
log.debug("Adjusting bucketed data time. Current: " + DateUtil.toISOString(current.date) + " to: " + DateUtil.toISOString(previous.date + T.mins(5).msecs()) + " by " + adjusted + " sec");
if (Math.abs(adjusted) > 90) {
// too big adjustment, fallback to non 5 min data
if (L.isEnabled(L.AUTOSENS))
@ -352,12 +319,10 @@ public class IobCobCalculatorPlugin extends PluginBase {
log.debug("Bucketed data created. Size: " + bucketed_data.size());
}
public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) {
Profile profile = ProfileFunctions.getInstance().getProfile(from);
double dia = Constants.defaultDIA;
if (profile != null)
dia = profile.getDia();
if (profile != null) dia = profile.getDia();
long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable();
long getBGDataFrom;
@ -365,21 +330,18 @@ public class IobCobCalculatorPlugin extends PluginBase {
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));
log.debug("Limiting data to oldest available temps: " + DateUtil.dateAndTimeFullString(oldestDataAvailable));
} else
getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia));
return getBGDataFrom;
}
public IobTotal calculateFromTreatmentsAndTempsSynchronized(long time, Profile profile) {
synchronized (dataLock) {
return calculateFromTreatmentsAndTemps(time, profile);
}
}
public IobTotal calculateFromTreatmentsAndTemps(long time, Profile profile) {
long now = System.currentTimeMillis();
time = roundUpTime(time);
@ -390,12 +352,14 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
}
IobTotal bolusIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTreatments(time).round();
IobTotal basalIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTempBasals(time, profile, true, now)
.round();
IobTotal basalIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTempBasals(time, profile, true, now).round();
if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) {
// Add expected zero temp basal for next 240 mins
IobTotal basalIobWithZeroTemp = basalIob.copy();
TemporaryBasal t = new TemporaryBasal().date(now + 60 * 1000L).duration(240).absolute(0);
TemporaryBasal t = new TemporaryBasal()
.date(now + 60 * 1000L)
.duration(240)
.absolute(0);
if (t.date < time) {
IobTotal calc = t.iobCalc(time, profile);
basalIobWithZeroTemp.plus(calc);
@ -411,7 +375,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return iobTotal;
}
@Nullable
public Long findPreviousTimeFromBucketedData(long time) {
if (bucketed_data == null)
@ -423,7 +386,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return null;
}
public BasalData getBasalData(Profile profile, long time) {
long now = System.currentTimeMillis();
time = roundUpTime(time);
@ -449,7 +411,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return retval;
}
@Nullable
public AutosensData getAutosensData(long time) {
synchronized (dataLock) {
@ -473,7 +434,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
@Nullable
public AutosensData getLastAutosensDataSynchronized(String reason) {
if (thread != null && thread.isAlive()) {
@ -494,8 +454,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
@NonNull
public CobInfo getCobInfo(boolean _synchronized, String reason) {
AutosensData autosensData = _synchronized ? getLastAutosensDataSynchronized(reason)
: getLastAutosensData(reason);
AutosensData autosensData = _synchronized ? getLastAutosensDataSynchronized(reason) : getLastAutosensData(reason);
Double displayCob = null;
double futureCarbs = 0;
long now = now();
@ -504,17 +463,15 @@ public class IobCobCalculatorPlugin extends PluginBase {
if (autosensData != null) {
displayCob = autosensData.cob;
for (Treatment treatment : treatments) {
if (!treatment.isValid)
continue;
if (IobCobCalculatorPlugin.roundUpTime(treatment.date) > IobCobCalculatorPlugin
.roundUpTime(autosensData.time) && treatment.date <= now && treatment.carbs > 0) {
if (!treatment.isValid) continue;
if (IobCobCalculatorPlugin.roundUpTime(treatment.date) > IobCobCalculatorPlugin.roundUpTime(autosensData.time)
&& treatment.date <= now && treatment.carbs > 0) {
displayCob += treatment.carbs;
}
}
}
for (Treatment treatment : treatments) {
if (!treatment.isValid)
continue;
if (!treatment.isValid) continue;
if (treatment.date > now && treatment.carbs > 0) {
futureCarbs += treatment.carbs;
}
@ -522,7 +479,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return new CobInfo(displayCob, futureCarbs);
}
@Nullable
public AutosensData getLastAutosensData(String reason) {
if (autosensDataTable.size() < 1) {
@ -546,8 +502,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
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;
} else {
if (L.isEnabled(L.AUTOSENS))
@ -556,7 +511,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
public String lastDataTime() {
if (autosensDataTable.size() > 0)
return DateUtil.dateAndTimeString(autosensDataTable.valueAt(autosensDataTable.size() - 1).time);
@ -564,7 +518,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return "autosensDataTable empty";
}
public IobTotal[] calculateIobArrayInDia(Profile profile) {
// predict IOB out to DIA plus 30m
long time = System.currentTimeMillis();
@ -581,7 +534,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return array;
}
public IobTotal[] calculateIobArrayForSMB(Profile profile) {
// predict IOB out to DIA plus 30m
long time = System.currentTimeMillis();
@ -598,14 +550,12 @@ public class IobCobCalculatorPlugin extends PluginBase {
return array;
}
public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) {
synchronized (dataLock) {
return ConfigBuilderPlugin.getPlugin().getActiveSensitivity().detectSensitivity(this, fromTime, toTime);
}
}
public static JSONArray convertToJSONArray(IobTotal[] iobArray) {
JSONArray array = new JSONArray();
for (int i = 0; i < iobArray.length; i++) {
@ -614,7 +564,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return array;
}
@Subscribe
@SuppressWarnings("unused")
public void onEventAppInitialized(EventAppInitialized ev) {
@ -626,7 +575,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev);
}
@Subscribe
@SuppressWarnings("unused")
public void onEventNewBG(EventNewBG ev) {
@ -639,7 +587,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, ev);
}
public void stopCalculation(String from) {
if (thread != null && thread.getState() != Thread.State.TERMINATED) {
stopCalculationTrigger = true;
@ -653,9 +600,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable,
Event cause) {
public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end));
if (thread == null || thread.getState() == Thread.State.TERMINATED) {
@ -667,7 +612,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
@Subscribe
public void onNewProfile(EventNewBasalProfile ev) {
if (this != getPlugin()) {
@ -683,15 +627,13 @@ public class IobCobCalculatorPlugin extends PluginBase {
stopCalculation("onNewProfile");
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<>();
autosensDataTable = new LongSparseArray<>();
}
runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev);
}
@Subscribe
public void onEventPreferenceChange(EventPreferenceChange ev) {
if (this != getPlugin()) {
@ -699,15 +641,18 @@ public class IobCobCalculatorPlugin extends PluginBase {
log.debug("Ignoring event for non default instance");
return;
}
if (ev.isChanged(R.string.key_openapsama_autosens_period) || ev.isChanged(R.string.key_age)
|| ev.isChanged(R.string.key_absorption_maxtime) || ev.isChanged(R.string.key_openapsama_min_5m_carbimpact)
|| ev.isChanged(R.string.key_absorption_cutoff) || ev.isChanged(R.string.key_openapsama_autosens_max)
|| ev.isChanged(R.string.key_openapsama_autosens_min)) {
if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
ev.isChanged(R.string.key_age) ||
ev.isChanged(R.string.key_absorption_maxtime) ||
ev.isChanged(R.string.key_openapsama_min_5m_carbimpact) ||
ev.isChanged(R.string.key_absorption_cutoff) ||
ev.isChanged(R.string.key_openapsama_autosens_max) ||
ev.isChanged(R.string.key_openapsama_autosens_min)
) {
stopCalculation("onEventPreferenceChange");
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<>();
autosensDataTable = new LongSparseArray<>();
}
@ -715,7 +660,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
@Subscribe
public void onEventConfigBuilderChange(EventConfigBuilderChange ev) {
if (this != getPlugin()) {
@ -726,15 +670,13 @@ public class IobCobCalculatorPlugin extends PluginBase {
stopCalculation("onEventConfigBuilderChange");
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<>();
autosensDataTable = new LongSparseArray<>();
}
runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, ev);
}
// When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated
@Subscribe
public void onEventNewHistoryData(EventNewHistoryData ev) {
@ -762,8 +704,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
if (autosensDataTable.keyAt(index) > time) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from autosensDataTable: "
+ DateUtil.dateAndTimeFullString(autosensDataTable.keyAt(index)));
log.debug("Removing from autosensDataTable: " + DateUtil.dateAndTimeFullString(autosensDataTable.keyAt(index)));
autosensDataTable.removeAt(index);
} else {
break;
@ -772,8 +713,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
for (int index = basalDataTable.size() - 1; index >= 0; index--) {
if (basalDataTable.keyAt(index) > time) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from basalDataTable: "
+ DateUtil.dateAndTimeFullString(basalDataTable.keyAt(index)));
log.debug("Removing from basalDataTable: " + DateUtil.dateAndTimeFullString(basalDataTable.keyAt(index)));
basalDataTable.removeAt(index);
} else {
break;
@ -784,7 +724,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.debug("Releasing onNewHistoryData");
}
public void clearCache() {
synchronized (dataLock) {
if (L.isEnabled(L.AUTOSENS))
@ -794,22 +733,20 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
// From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2
// Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method
public static double percentile(Double[] arr, double p) {
if (arr.length == 0)
return 0;
if (p <= 0)
return arr[0];
if (p >= 1)
return arr[arr.length - 1];
if (arr.length == 0) return 0;
if (p <= 0) return arr[0];
if (p >= 1) return arr[arr.length - 1];
double index = arr.length * p, lower = Math.floor(index), upper = lower + 1, weight = index % 1;
double index = arr.length * p,
lower = Math.floor(index),
upper = lower + 1,
weight = index % 1;
if (upper >= arr.length)
return arr[(int)lower];
if (upper >= arr.length) return arr[(int) lower];
return arr[(int) lower] * (1 - weight) + arr[(int) upper] * weight;
}
}

View file

@ -34,16 +34,19 @@ public enum PumpCapability {
PumpCapability[] children;
PumpCapability() {
PumpCapability()
{
}
PumpCapability(PumpCapability... children) {
PumpCapability(PumpCapability...children)
{
this.children = children;
}
public boolean hasCapability(PumpCapability capability) {
public boolean hasCapability(PumpCapability capability)
{
// we can only check presense of simple capabilities
if (capability.children != null)
return false;
@ -51,15 +54,19 @@ public enum PumpCapability {
if (this == capability)
return true;
if (this.children != null) {
if (this.children!=null)
{
for (PumpCapability child : children) {
if (child == capability)
return true;
}
return false;
} else
}
else
return false;
}
}

View file

@ -9,9 +9,10 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.pump.common.data.DoseSettings;
/**
* Created by andy on 02/05/2018.
* <p>
*
* Most of this defintions is intended for VirtualPump only, but they can be used by other plugins.
*/
@ -100,7 +101,7 @@ public enum PumpType {
new DoseSettings(0.05d, 30, 8*60, 0.05d), //
PumpTempBasalType.Absolute, //
new DoseSettings(0.05d, 30, 24*60, 0d, 35d), PumpCapability.BasalRate_Duration30minAllowed, //
0.05d, 0.05d, null, PumpCapability.MedtronicCapabilities), // TODO
0.05d, 0.05d, null, PumpCapability.MedtronicCapabilities), //
Medtronic_515_715("Medtronic 515/715", Medtronic_512_712),
Medtronic_522_722("Medtronic 522/722", Medtronic_512_712),
@ -147,7 +148,8 @@ public enum PumpType {
private PumpType parent;
private static Map<String,PumpType> mapByDescription;
static {
static
{
mapByDescription = new HashMap<>();
for (PumpType pumpType : values()) {
@ -156,13 +158,14 @@ public enum PumpType {
}
PumpType(String description, PumpType parent) {
PumpType(String description, PumpType parent)
{
this.description = description;
this.parent = parent;
}
PumpType(String description, PumpType parent, PumpCapability pumpCapability) {
PumpType(String description, PumpType parent, PumpCapability pumpCapability)
{
this.description = description;
this.parent = parent;
this.pumpCapability = pumpCapability;
@ -171,16 +174,16 @@ public enum PumpType {
PumpType(String description, double bolusSize, DoseStepSize specialBolusSize, //
DoseSettings extendedBolusSettings, //
PumpTempBasalType pumpTempBasalType, DoseSettings tbrSettings, PumpCapability specialBasalDurations, //
double baseBasalMinValue, double baseBasalStep, DoseStepSize baseBasalSpecialSteps, PumpCapability pumpCapability) {
double baseBasalMinValue, double baseBasalStep, DoseStepSize baseBasalSpecialSteps, PumpCapability pumpCapability)
{
this(description, bolusSize, specialBolusSize, extendedBolusSettings, pumpTempBasalType, tbrSettings, specialBasalDurations, baseBasalMinValue, null, baseBasalStep, baseBasalSpecialSteps, pumpCapability);
}
PumpType(String description, double bolusSize, DoseStepSize specialBolusSize, //
DoseSettings extendedBolusSettings, //
PumpTempBasalType pumpTempBasalType, DoseSettings tbrSettings, PumpCapability specialBasalDurations, //
double baseBasalMinValue, Double baseBasalMaxValue, double baseBasalStep, DoseStepSize baseBasalSpecialSteps, PumpCapability pumpCapability) {
double baseBasalMinValue, Double baseBasalMaxValue, double baseBasalStep, DoseStepSize baseBasalSpecialSteps, PumpCapability pumpCapability)
{
this.description = description;
this.bolusSize = bolusSize;
this.specialBolusSize = specialBolusSize;
@ -197,7 +200,6 @@ public enum PumpType {
public String getDescription() {
return description;
}
@ -210,76 +212,69 @@ public enum PumpType {
}
public double getBolusSize() {
return isParentSet() ? parent.bolusSize : bolusSize;
}
public DoseStepSize getSpecialBolusSize() {
return isParentSet() ? parent.specialBolusSize : specialBolusSize;
}
public DoseSettings getExtendedBolusSettings() {
return isParentSet() ? parent.extendedBolusSettings : extendedBolusSettings;
}
public PumpTempBasalType getPumpTempBasalType() {
return isParentSet() ? parent.pumpTempBasalType : pumpTempBasalType;
}
public DoseSettings getTbrSettings() {
return isParentSet() ? parent.tbrSettings : tbrSettings;
}
public double getBaseBasalMinValue() {
return isParentSet() ? parent.baseBasalMinValue : baseBasalMinValue;
}
public Double getBaseBasalMaxValue() {
return isParentSet() ? parent.baseBasalMaxValue : baseBasalMaxValue;
}
public double getBaseBasalStep() {
return isParentSet() ? parent.baseBasalStep : baseBasalStep;
}
public DoseStepSize getBaseBasalSpecialSteps() {
return isParentSet() ? parent.baseBasalSpecialSteps : baseBasalSpecialSteps;
}
public PumpType getParent() {
return parent;
}
private boolean isParentSet() {
private boolean isParentSet()
{
return this.parent!=null;
}
public static PumpType getByDescription(String desc) {
if (mapByDescription.containsKey(desc)) {
public static PumpType getByDescription(String desc)
{
if (mapByDescription.containsKey(desc))
{
return mapByDescription.get(desc);
} else {
}
else
{
return PumpType.GenericAAPS;
}
}
@ -303,16 +298,16 @@ public enum PumpType {
}
private String getBaseBasalRange() {
private String getBaseBasalRange()
{
Double maxValue = getBaseBasalMaxValue();
return maxValue==null ? "" + getBaseBasalMinValue() : getBaseBasalMinValue() + "-" + maxValue;
}
private String getStep(String step, DoseStepSize stepSize) {
private String getStep(String step, DoseStepSize stepSize)
{
if (stepSize!=null)
return step + " [" + stepSize.getDescription() + "] *";
else
@ -321,23 +316,24 @@ public enum PumpType {
public boolean hasExtendedBasals() {
return ((getBaseBasalSpecialSteps() !=null) || (getSpecialBolusSize() != null));
}
public PumpCapability getSpecialBasalDurations() {
if (isParentSet()) {
if (isParentSet())
{
return parent.getSpecialBasalDurations();
} else {
}
else
{
return specialBasalDurations == null ? //
PumpCapability.BasalRate_Duration15and30minNotAllowed : specialBasalDurations;
}
}
public double determineCorrectBolusSize(double bolusAmount) {
if (bolusAmount == 0.0d) {
return bolusAmount;
}
@ -357,7 +353,6 @@ public enum PumpType {
public double determineCorrectExtendedBolusSize(double bolusAmount) {
if (bolusAmount == 0.0d) {
return bolusAmount;
}
@ -381,7 +376,6 @@ public enum PumpType {
public double determineCorrectBasalSize(double basalAmount) {
if (basalAmount == 0.0d) {
return basalAmount;
}

View file

@ -25,7 +25,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;

View file

@ -25,7 +25,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;

View file

@ -26,8 +26,8 @@ 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.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;

View file

@ -26,8 +26,8 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;

View file

@ -21,9 +21,11 @@ import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import com.crashlytics.android.answers.CustomEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
@ -40,7 +42,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.MessageHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.MessageHelperActivity;
import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
@ -69,6 +71,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtro
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
/**
@ -552,6 +555,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
pumpState = PumpDriverState.Initialized;
}
// FIXME andy!!!
// MainApp.getFirebaseAnalytics().logCustomEvent(FirebaseAnalytics.Event.SELECT_CONTENT, event);
//
// FabricPrivacy.getInstance().logCustom( //

View file

@ -22,7 +22,6 @@ import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
@ -655,20 +654,20 @@ public class MedtronicHistoryData {
boolean old = false;
if (old) {
treatment.insulin = bolusDTO.getDeliveredAmount();
treatment.pumpId = bolus.getPumpId();
treatment.source = Source.PUMP;
bolus.setLinkedObject(treatment);
TreatmentsPlugin.getPlugin().getService().createOrUpdate(treatment);
LOG.debug("editBolus - [date={},pumpId={}, insulin={}]", treatment.date, treatment.pumpId,
treatment.insulin);
MainApp.bus().post(new EventTreatmentChange(treatment));
} else {
// if (old) {
// treatment.insulin = bolusDTO.getDeliveredAmount();
// treatment.pumpId = bolus.getPumpId();
// treatment.source = Source.PUMP;
//
// bolus.setLinkedObject(treatment);
//
// TreatmentsPlugin.getPlugin().getService().createOrUpdate(treatment);
//
// LOG.debug("editBolus - [date={},pumpId={}, insulin={}]", treatment.date, treatment.pumpId,
// treatment.insulin);
//
// MainApp.bus().post(new EventTreatmentChange(treatment));
// } else {
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(treatment.date);
if (detailedBolusInfo == null) {
@ -687,7 +686,7 @@ public class MedtronicHistoryData {
if (L.isEnabled(L.PUMPCOMM))
LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
}
// }
}
}

View file

@ -1,15 +1,15 @@
package info.nightscout.androidaps.plugins.pump.virtual;
import java.util.List;
import android.os.SystemClock;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.os.SystemClock;
import com.squareup.otto.Subscribe;
import java.util.List;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
@ -41,11 +41,11 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 05.08.2016.
*/
public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
private Logger log = LoggerFactory.getLogger(L.PUMP);
Integer batteryPercent = 50;
@ -56,12 +56,16 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
private long lastDataTime = 0;
private PumpDescription pumpDescription = new PumpDescription();
public VirtualPumpPlugin() {
super(new PluginDescription().mainType(PluginType.PUMP).fragmentClass(VirtualPumpFragment.class.getName())
.pluginName(R.string.virtualpump).shortName(R.string.virtualpump_shortname)
.preferencesId(R.xml.pref_virtualpump).neverVisible(Config.NSCLIENT)
.description(R.string.description_pump_virtual));
super(new PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(VirtualPumpFragment.class.getName())
.pluginName(R.string.virtualpump)
.shortName(R.string.virtualpump_shortname)
.preferencesId(R.xml.pref_virtualpump)
.neverVisible(Config.NSCLIENT)
.description(R.string.description_pump_virtual)
);
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.1d;
@ -81,6 +85,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
pumpDescription.tempDurationStep30mAllowed = true;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = true;
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.01d;
@ -91,7 +96,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
pumpDescription.is30minBasalRatesCapable = true;
}
public static VirtualPumpPlugin getPlugin() {
if (plugin == null)
plugin = new VirtualPumpPlugin();
@ -99,23 +103,19 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return plugin;
}
private void loadFakingStatus() {
fromNSAreCommingFakedExtendedBoluses = SP.getBoolean(R.string.key_fromNSAreCommingFakedExtendedBoluses, false);
}
public boolean getFakingStatus() {
return fromNSAreCommingFakedExtendedBoluses;
}
public void setFakingStatus(boolean newStatus) {
fromNSAreCommingFakedExtendedBoluses = newStatus;
SP.putBoolean(R.string.key_fromNSAreCommingFakedExtendedBoluses, fromNSAreCommingFakedExtendedBoluses);
}
@Override
protected void onStart() {
super.onStart();
@ -123,86 +123,72 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
refreshConfiguration();
}
@Override
protected void onStop() {
MainApp.bus().unregister(this);
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange s) {
if (s.isChanged(R.string.key_virtualpump_type))
refreshConfiguration();
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return (Config.NSCLIENT) && fromNSAreCommingFakedExtendedBoluses;
}
@Override
public PumpEnactResult loadTDDs() {
//no result, could read DB in the future?
return new PumpEnactResult();
}
@Override
public List<CustomAction> getCustomActions() {
return null;
}
@Override
public void executeCustomAction(CustomActionType customActionType) {
}
@Override
public boolean isInitialized() {
return true;
}
@Override
public boolean isSuspended() {
return false;
}
@Override
public boolean isBusy() {
return false;
}
@Override
public boolean isConnected() {
return true;
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override
public void connect(String reason) {
if (!Config.NSCLIENT)
@ -210,48 +196,40 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
lastDataTime = System.currentTimeMillis();
}
@Override
public void disconnect(String reason) {
}
@Override
public void stopConnecting() {
}
@Override
public void getPumpStatus() {
lastDataTime = System.currentTimeMillis();
}
@Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
lastDataTime = System.currentTimeMillis();
// Do nothing here. we are using ConfigBuilderPlugin.getPlugin().getActiveProfile().getProfile();
PumpEnactResult result = new PumpEnactResult();
result.success = true;
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok),
Notification.INFO, 60);
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
return result;
}
@Override
public boolean isThisProfileSet(Profile profile) {
return true;
}
@Override
public long lastDataTime() {
return lastDataTime;
}
@Override
public double getBaseBasalRate() {
Profile profile = ProfileFunctions.getInstance().getProfile();
@ -263,16 +241,10 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
@Override
public double getReservoirLevel() {
return reservoirInUnits;
}
public double getReservoirLevel() { return reservoirInUnits; }
@Override
public int getBatteryLevel() {
return batteryPercent;
}
public int getBatteryLevel() { return batteryPercent; }
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
@ -301,26 +273,25 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
MainApp.bus().post(bolusingEvent);
SystemClock.sleep(1000);
if (L.isEnabled(L.PUMPCOMM))
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: "
+ detailedBolusInfo.carbs + "g " + result);
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = System.currentTimeMillis();
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
return result;
}
@Override
public void stopBolusDelivering() {
}
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile,
boolean enforceNew) {
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
TemporaryBasal tempBasal = new TemporaryBasal().date(System.currentTimeMillis()).absolute(absoluteRate)
.duration(durationInMinutes).source(Source.USER);
TemporaryBasal tempBasal = new TemporaryBasal()
.date(System.currentTimeMillis())
.absolute(absoluteRate)
.duration(durationInMinutes)
.source(Source.USER);
PumpEnactResult result = new PumpEnactResult();
result.success = true;
result.enacted = true;
@ -336,12 +307,13 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile,
boolean enforceNew) {
TemporaryBasal tempBasal = new TemporaryBasal().date(System.currentTimeMillis()).percent(percent)
.duration(durationInMinutes).source(Source.USER);
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
TemporaryBasal tempBasal = new TemporaryBasal()
.date(System.currentTimeMillis())
.percent(percent)
.duration(durationInMinutes)
.source(Source.USER);
PumpEnactResult result = new PumpEnactResult();
result.success = true;
result.enacted = true;
@ -358,15 +330,17 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
PumpEnactResult result = cancelExtendedBolus();
if (!result.success)
return result;
ExtendedBolus extendedBolus = new ExtendedBolus().date(System.currentTimeMillis()).insulin(insulin)
.durationInMinutes(durationInMinutes).source(Source.USER);
ExtendedBolus extendedBolus = new ExtendedBolus()
.date(System.currentTimeMillis())
.insulin(insulin)
.durationInMinutes(durationInMinutes)
.source(Source.USER);
result.success = true;
result.enacted = true;
result.bolusDelivered = insulin;
@ -381,7 +355,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult();
@ -401,7 +374,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult();
@ -421,7 +393,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis();
@ -465,30 +436,25 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return pump;
}
@Override
public String deviceID() {
return "VirtualPump";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return "Virtual Pump";
}
public PumpType getPumpType() {
return pumpType;
}
@Override
public boolean canHandleDST() {
return true;

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.T;

View file

@ -1,17 +1,17 @@
package info.nightscout.androidaps.plugins.treatments;
import java.util.Date;
import java.util.Objects;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Color;
import android.support.annotation.Nullable;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import java.util.Objects;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -28,7 +28,6 @@ import info.nightscout.androidaps.utils.JsonHelper;
@DatabaseTable(tableName = Treatment.TABLE_TREATMENTS)
public class Treatment implements DataPointWithLabelInterface {
public static final String TABLE_TREATMENTS = "Treatments";
@DatabaseField(id = true)
@ -61,11 +60,9 @@ public class Treatment implements DataPointWithLabelInterface {
@DatabaseField
public String boluscalc;
public Treatment() {
}
public static Treatment createFromJson(JSONObject json) throws JSONException {
Treatment treatment = new Treatment();
treatment.source = Source.NIGHTSCOUT;
@ -93,14 +90,21 @@ public class Treatment implements DataPointWithLabelInterface {
return treatment;
}
public String toString() {
return "Treatment{" + "date= " + date + ", date= " + new Date(date).toLocaleString() + ", isValid= " + isValid
+ ", isSMB= " + isSMB + ", _id= " + _id + ", pumpId= " + pumpId + ", insulin= " + insulin + ", carbs= "
+ carbs + ", mealBolus= " + mealBolus + "}";
return "Treatment{" +
"date= " + date +
", date= " + new Date(date).toLocaleString() +
", isValid= " + isValid +
", isSMB= " + isSMB +
", _id= " + _id +
", pumpId= " + pumpId +
", insulin= " + insulin +
", carbs= " + carbs +
", mealBolus= " + mealBolus +
", source= " + source +
"}";
}
public boolean isDataChanging(Treatment other) {
if (date != other.date)
return true;
@ -111,7 +115,6 @@ public class Treatment implements DataPointWithLabelInterface {
return false;
}
public boolean isEqual(Treatment other) {
if (date != other.date)
return false;
@ -130,6 +133,22 @@ public class Treatment implements DataPointWithLabelInterface {
return true;
}
public boolean isEqualWithoutPumpId(Treatment other) {
if (date != other.date)
return false;
if (insulin != other.insulin)
return false;
if (carbs != other.carbs)
return false;
if (mealBolus != other.mealBolus)
return false;
if (isSMB != other.isSMB)
return false;
if (!Objects.equals(_id, other._id))
return false;
return true;
}
@Nullable
public JSONObject getBoluscalc() {
@ -141,7 +160,6 @@ public class Treatment implements DataPointWithLabelInterface {
return null;
}
/*
* mealBolus, _id and isSMB cannot be known coming from pump. Only compare rest
* TODO: remove debug toasts
@ -159,7 +177,6 @@ public class Treatment implements DataPointWithLabelInterface {
return true;
}
public void copyFrom(Treatment t) {
date = t.date;
_id = t._id;
@ -170,7 +187,6 @@ public class Treatment implements DataPointWithLabelInterface {
isSMB = t.isSMB;
}
public void copyBasics(Treatment t) {
date = t.date;
insulin = t.insulin;
@ -179,7 +195,6 @@ public class Treatment implements DataPointWithLabelInterface {
source = t.source;
}
// ----------------- DataPointInterface --------------------
@Override
public double getX() {
@ -189,30 +204,25 @@ public class Treatment implements DataPointWithLabelInterface {
// default when no sgv around available
private double yValue = 0;
@Override
public double getY() {
return isSMB ? OverviewPlugin.getPlugin().determineLowLine() : yValue;
}
@Override
public String getLabel() {
String label = "";
if (insulin > 0)
label += DecimalFormatter.toPumpSupportedBolus(insulin) + "U";
if (insulin > 0) label += DecimalFormatter.toPumpSupportedBolus(insulin) + "U";
if (carbs > 0)
label += "~" + DecimalFormatter.to0Decimal(carbs) + "g";
return label;
}
@Override
public long getDuration() {
return 0;
}
@Override
public PointsWithLabelGraphSeries.Shape getShape() {
if (isSMB)
@ -221,13 +231,11 @@ public class Treatment implements DataPointWithLabelInterface {
return PointsWithLabelGraphSeries.Shape.BOLUS;
}
@Override
public float getSize() {
return 2;
}
@Override
public int getColor() {
if (isSMB)
@ -238,13 +246,11 @@ public class Treatment implements DataPointWithLabelInterface {
return MainApp.instance().getResources().getColor(android.R.color.holo_red_light);
}
@Override
public void setY(double y) {
yValue = y;
}
// ----------------- DataPointInterface end --------------------
public Iob iobCalc(long time, double dia) {

View file

@ -242,7 +242,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
try {
Treatment treatment = Treatment.createFromJson(json);
if (treatment != null)
createOrUpdate(treatment);
createOrUpdate(treatment, true);
else
log.error("Date is null: " + treatment.toString());
} catch (JSONException e) {
@ -251,7 +251,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
}
// return true if new record is created
public UpdateReturn createOrUpdate(Treatment treatment) {
public UpdateReturn createOrUpdate(Treatment treatment, boolean fromNightScout) {
try {
Treatment old;
treatment.date = DatabaseHelper.roundDateToSec(treatment.date);
@ -315,11 +315,11 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
if (treatment.source == Source.NIGHTSCOUT) {
old = getDao().queryForId(treatment.date);
if (old != null) {
if (!old.isEqual(treatment)) {
if (!old.isEqualWithoutPumpId(treatment)) {
boolean historyChange = old.isDataChanging(treatment);
long oldDate = old.date;
getDao().delete(old); // need to delete/create because date may change too
old.copyFrom(treatment);
treatmentCopy(old, treatment, fromNightScout);
getDao().create(old);
if (L.isEnabled(L.DATATREATMENTS))
log.debug("Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString());
@ -338,11 +338,11 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
if (treatment._id != null) {
old = findByNSId(treatment._id);
if (old != null) {
if (!old.isEqual(treatment)) {
if (!old.isEqualWithoutPumpId(treatment)) {
boolean historyChange = old.isDataChanging(treatment);
long oldDate = old.date;
getDao().delete(old); // need to delete/create because date may change too
old.copyFrom(treatment);
treatmentCopy(old, treatment, fromNightScout);
getDao().create(old);
if (L.isEnabled(L.DATATREATMENTS))
log.debug("Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
@ -379,6 +379,30 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
return new UpdateReturn(false, false);
}
private void treatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) {
log.debug("treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString());
if (fromNightScout) {
long pumpId_old = oldTreatment.pumpId;
oldTreatment.copyFrom(newTreatment);
if (pumpId_old != 0) {
oldTreatment.pumpId = pumpId_old;
}
if (oldTreatment.pumpId != 0 && oldTreatment.source != Source.PUMP) {
oldTreatment.source = Source.PUMP;
}
} else {
oldTreatment.copyFrom(newTreatment);
}
log.debug("treatmentCopy [newAfterChange={}]", oldTreatment.toString());
}
/**
* Returns the record for the given id, null if none, throws RuntimeException
* if multiple records with the same pump id exist.

View file

@ -43,7 +43,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
@ -563,7 +563,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
treatment.source = detailedBolusInfo.source;
treatment.mealBolus = treatment.carbs > 0;
treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null;
TreatmentService.UpdateReturn creatOrUpdateResult = getService().createOrUpdate(treatment);
TreatmentService.UpdateReturn creatOrUpdateResult = getService().createOrUpdate(treatment, false);
boolean newRecordCreated = creatOrUpdateResult.newRecord;
// log.debug("Adding new Treatment record" + treatment.toString());
if (detailedBolusInfo.carbTime != 0) {
@ -577,7 +577,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
// records
carbsTreatment.carbs = detailedBolusInfo.carbs;
carbsTreatment.source = detailedBolusInfo.source;
getService().createOrUpdate(carbsTreatment);
getService().createOrUpdate(carbsTreatment, false);
// log.debug("Adding new Treatment record" + carbsTreatment);
}
if (newRecordCreated && detailedBolusInfo.isValid)

View file

@ -23,8 +23,8 @@ 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.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;

View file

@ -8,7 +8,7 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DecimalFormatter;

View file

@ -74,7 +74,8 @@ public class FabricPrivacy {
}
public static boolean fabricEnabled() {
return SP.getBoolean("enable_fabric", true);
//return SP.getBoolean("enable_fabric", true);
return true;
}
// Analytics logCustom

View file

@ -53,8 +53,7 @@ public class MedtronicHistoryDataUTest {
RawHistoryPage historyPage = new RawHistoryPage();
historyPage.appendData(historyPageData);
List<PumpHistoryEntry> pumpHistoryEntries = decoder.processPageAndCreateRecords(historyPage,
PumpHistoryEntry.class);
List<PumpHistoryEntry> pumpHistoryEntries = decoder.processPageAndCreateRecords(historyPage);
System.out.println("PumpHistoryEntries: " + pumpHistoryEntries.size());

View file

@ -7,7 +7,6 @@ buildscript {
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
classpath 'com.google.gms:google-services:4.2.0'

View file

@ -1,102 +0,0 @@
apply plugin: 'com.android.application'
ext {
wearableVersion = "2.0.1"
playServicesWearable = "16.0.1"
}
def generateGitBuild = { ->
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('"')
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--always'
standardOutput = stdout
}
String commitObject = stdout.toString().trim()
stringBuilder.append(commitObject)
} catch (ignored) {
stringBuilder.append('NoGitSystemAvailable')
}
stringBuilder.append('-')
stringBuilder.append((new Date()).format('yyyy.MM.dd'))
stringBuilder.append('"')
return stringBuilder.toString()
}
android {
compileSdkVersion 27
defaultConfig {
applicationId "info.nightscout.androidaps"
minSdkVersion 23
targetSdkVersion 23
versionCode 1
versionName "1.0.2"
buildConfigField "String", "BUILDVERSION", generateGitBuild()
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
abortOnError false
}
productFlavors {
flavorDimensions "standard"
full {
applicationId "info.nightscout.androidaps"
dimension "standard"
versionName version
}
pumpcontrol {
applicationId "info.nightscout.aapspumpcontrol"
dimension "standard"
versionName version + "-pumpcontrol"
}
nsclient {
applicationId "info.nightscout.nsclient"
dimension "standard"
versionName version + "-nsclient"
}
nsclient2 {
applicationId "info.nightscout.nsclient2"
dimension "standard"
versionName version + "-nsclient"
}
}
}
allprojects {
repositories {
jcenter()
flatDir {
dirs 'libs'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation files("libs/hellocharts-library-1.5.5.jar")
//compile "com.ustwo.android:clockwise-wearable:1.0.2"
compileOnly "com.google.android.wearable:wearable:${wearableVersion}"
implementation "com.google.android.support:wearable:${wearableVersion}"
implementation "com.google.android.gms:play-services-wearable:${playServicesWearable}"
implementation(name:"ustwo-clockwise-debug", ext:"aar")
implementation "com.android.support:support-v4:27.0.1"
implementation 'com.android.support:wear:27.0.1'
implementation "me.denley.wearpreferenceactivity:wearpreferenceactivity:0.5.0"
}

1
wear/build.gradle Symbolic link
View file

@ -0,0 +1 @@
/home/andy/Dropbox/workspaces/aaps/andy_AndroidAPS_Medtronic_Shared/wear/build.gradle

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.interaction.utils;
import java.time.LocalDateTime;
import java.util.Date;
/**
@ -9,11 +8,9 @@ import java.util.Date;
public class WearUtil {
public static String dateTimeText(long timeInMs) {
Date d = new Date(timeInMs);
return "" + d.getDay() + "." + d.getMonth() + "." + d.getYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
}