diff --git a/app/build.gradle b/app/build.gradle index 8220158fae..e611da5da3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -6,7 +6,7 @@ buildscript { dependencies { classpath 'io.fabric.tools:gradle:1.+' - classpath 'com.dicedmelon.gradle:jacoco-android:0.1.2' + classpath 'com.dicedmelon.gradle:jacoco-android:0.1.3' } } apply plugin: "com.android.application" @@ -15,7 +15,7 @@ apply plugin: "jacoco-android" apply plugin: 'com.jakewharton.butterknife' ext { - supportLibraryVersion = "27.1.0" + supportLibraryVersion = "27.1.1" ormLiteVersion = "4.46" powermockVersion = "1.7.3" dexmakerVersion = "1.2" @@ -63,14 +63,14 @@ android { targetSdkVersion 25 multiDexEnabled true versionCode 1500 - // dev_version: 2.1 + // dev_version: 2.2.1-dev version "medtronic-0.8.2-SNAPSHOT" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"' - buildConfigField "String", "DEV_VERSION", '"2.1"' - buildConfigField "String", "DEV_DATE", '"2.3.2019"' - buildConfigField "String", "DEV_CHECKIN", '"f28d763ada9e6a8d7621b972e03edd980767e076"' + buildConfigField "String", "DEV_VERSION", '"2.2.1"' + buildConfigField "String", "DEV_DATE", '"30.3.2019"' + buildConfigField "String", "DEV_CHECKIN", '"361ffa91c8c66d3901b1e8ae92b8b54bf0e2a4ce"' testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" // if you change minSdkVersion to less than 11, you need to change executeTask for wear @@ -82,7 +82,7 @@ android { // 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 + 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 @@ -104,9 +104,9 @@ android { applicationId "info.nightscout.androidaps" dimension "standard" resValue "string", "app_name", "AndroidAPS" - versionName version + versionName version + "-pumpcontrol" manifestPlaceholders = [ - appIcon : "@mipmap/ic_launcher", + appIcon: "@mipmap/ic_launcher", appIconRound: "@mipmap/ic_launcher_round" ] } @@ -116,7 +116,7 @@ android { resValue "string", "app_name", "Pumpcontrol" versionName version manifestPlaceholders = [ - appIcon : "@mipmap/ic_pumpcontrol", + appIcon: "@mipmap/ic_pumpcontrol", appIconRound: "@null" ] } @@ -126,7 +126,7 @@ android { resValue "string", "app_name", "NSClient" versionName version + "-nsclient" manifestPlaceholders = [ - appIcon : "@mipmap/yellowowl", + appIcon: "@mipmap/ic_yellowowl", appIconRound: "@null" ] } @@ -136,7 +136,7 @@ android { resValue "string", "app_name", "NSClient2" versionName version + "-nsclient" manifestPlaceholders = [ - appIcon : "@mipmap/yellowowl", + appIcon: "@mipmap/ic_yellowowl", appIconRound: "@null" ] } @@ -151,7 +151,7 @@ android { unitTests.includeAndroidResources = true } - useLibrary "org.apache.http.legacy" + useLibrary "org.apache.http.legacy" } allprojects { @@ -199,7 +199,7 @@ dependencies { implementation "org.slf4j:slf4j-api:1.7.12" implementation "com.jjoe64:graphview:4.0.1" implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.1.1" - implementation 'com.google.android.gms:play-services-wearable:10.2.1' + implementation "com.google.android.gms:play-services-wearable:7.5.0" implementation(name: "android-edittext-validator-v1.3.4-mod", ext: "aar") implementation(name: "sightparser-release", ext: "aar") implementation 'com.madgag.spongycastle:core:1.58.0.0' @@ -233,8 +233,6 @@ dependencies { 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.7.22" androidTestImplementation "com.google.dexmaker:dexmaker:${dexmakerVersion}" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 61d3f6c1b3..b850a998f7 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -298,4 +298,4 @@ - \ No newline at end of file + diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java index 183975b984..2ecabfe965 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -68,4 +68,7 @@ public class Constants { //SMS Communicator public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); + //Storage [MB] + public static final long MINIMUM_FREE_SPACE = 200; + } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 7fe586b59d..cb767f0c43 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -1,25 +1,12 @@ package info.nightscout.androidaps; -import java.io.File; -import java.util.ArrayList; - -import net.danlew.android.joda.JodaTimeAndroid; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.app.Application; -import android.bluetooth.BluetoothAdapter; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.annotation.PluralsRes; import android.support.v4.content.LocalBroadcastManager; -import android.util.Log; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; @@ -28,6 +15,14 @@ import com.squareup.otto.Bus; import com.squareup.otto.LoggingBus; import com.squareup.otto.ThreadEnforcer; +import net.danlew.android.joda.JodaTimeAndroid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.ArrayList; + import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.interfaces.PluginBase; @@ -42,6 +37,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; +import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintPlugin; import info.nightscout.androidaps.plugins.general.actions.ActionsFragment; import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.general.food.FoodPlugin; @@ -97,8 +93,8 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import io.fabric.sdk.android.Fabric; -public class MainApp extends Application { +public class MainApp extends Application { private static Logger log = LoggerFactory.getLogger(L.CORE); private static KeepAliveReceiver keepAliveReceiver; @@ -116,12 +112,10 @@ public class MainApp extends Application { private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver(); private static DBAccessReceiver dbAccessReciever = new DBAccessReceiver(); private LocalBroadcastManager lbm; - private BroadcastReceiver btReceiver; // used for RileyLink (Medtronic and Omnipod) public static boolean devBranch; public static boolean engineeringMode; - @Override public void onCreate() { super.onCreate(); @@ -156,15 +150,12 @@ public class MainApp extends Application { registerLocalBroadcastReceiver(); - setBTReceiver(); - if (pluginsList == null) { pluginsList = new ArrayList<>(); // Register all tabs in app here pluginsList.add(OverviewPlugin.getPlugin()); pluginsList.add(IobCobCalculatorPlugin.getPlugin()); - if (Config.ACTION) - pluginsList.add(ActionsFragment.getPlugin()); + if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin()); pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin()); @@ -172,43 +163,29 @@ public class MainApp extends Application { pluginsList.add(SensitivityAAPSPlugin.getPlugin()); pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin()); pluginsList.add(SensitivityOref1Plugin.getPlugin()); - if (Config.PUMPDRIVERS) - pluginsList.add(DanaRPlugin.getPlugin()); - if (Config.PUMPDRIVERS) - pluginsList.add(DanaRKoreanPlugin.getPlugin()); - if (Config.PUMPDRIVERS) - pluginsList.add(DanaRv2Plugin.getPlugin()); - if (Config.PUMPDRIVERS) - pluginsList.add(DanaRSPlugin.getPlugin()); - if (Config.PUMPDRIVERS) - pluginsList.add(LocalInsightPlugin.getPlugin()); - pluginsList.add(CareportalPlugin.getPlugin()); - if (Config.PUMPDRIVERS) - pluginsList.add(ComboPlugin.getPlugin()); - if (Config.MDI) - pluginsList.add(MDIPlugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(DanaRPlugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin()); if (Config.PUMPDRIVERS && engineeringMode) { pluginsList.add(MedtronicPumpPlugin.getPlugin()); } + pluginsList.add(CareportalPlugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin()); + if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin()); pluginsList.add(VirtualPumpPlugin.getPlugin()); - if (Config.APS) - pluginsList.add(LoopPlugin.getPlugin()); - if (Config.APS) - pluginsList.add(OpenAPSMAPlugin.getPlugin()); - if (Config.APS) - pluginsList.add(OpenAPSAMAPlugin.getPlugin()); - if (Config.APS) - pluginsList.add(OpenAPSSMBPlugin.getPlugin()); + if (Config.APS) pluginsList.add(LoopPlugin.getPlugin()); + if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin()); + if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin()); + if (Config.APS) pluginsList.add(OpenAPSSMBPlugin.getPlugin()); pluginsList.add(NSProfilePlugin.getPlugin()); - if (Config.OTHERPROFILES) - pluginsList.add(SimpleProfilePlugin.getPlugin()); - if (Config.OTHERPROFILES) - pluginsList.add(LocalProfilePlugin.getPlugin()); + if (Config.OTHERPROFILES) pluginsList.add(SimpleProfilePlugin.getPlugin()); + if (Config.OTHERPROFILES) pluginsList.add(LocalProfilePlugin.getPlugin()); pluginsList.add(TreatmentsPlugin.getPlugin()); - if (Config.SAFETY) - pluginsList.add(SafetyPlugin.getPlugin()); - if (Config.APS) - pluginsList.add(ObjectivesPlugin.getPlugin()); + if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin()); + if (Config.SAFETY) pluginsList.add(StorageConstraintPlugin.getPlugin()); + if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin()); pluginsList.add(SourceXdripPlugin.getPlugin()); pluginsList.add(SourceNSClientPlugin.getPlugin()); pluginsList.add(SourceMM640gPlugin.getPlugin()); @@ -218,8 +195,7 @@ public class MainApp extends Application { pluginsList.add(SourcePoctechPlugin.getPlugin()); pluginsList.add(SourceTomatoPlugin.getPlugin()); pluginsList.add(SourceEversensePlugin.getPlugin()); - if (Config.SMSCOMMUNICATORENABLED) - pluginsList.add(SmsCommunicatorPlugin.getPlugin()); + if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(WearPlugin.initPlugin(this)); @@ -247,7 +223,6 @@ public class MainApp extends Application { } } - private void registerLocalBroadcastReceiver() { lbm = LocalBroadcastManager.getInstance(this); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT)); @@ -263,58 +238,19 @@ public class MainApp extends Application { lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_DEVICESTATUS)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_CAL)); - // register alarms + //register alarms lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ALARM)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ANNOUNCEMENT)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_CLEAR_ALARM)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_URGENT_ALARM)); - // register ack alarm + //register ack alarm lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM)); - // register dbaccess + //register dbaccess lbm.registerReceiver(dbAccessReciever, new IntentFilter(Intents.ACTION_DATABASE)); } - - private void setBTReceiver() { - - // SP.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, null); - SP.remove(MedtronicConst.Statistics.LastPumpHistoryEntry); // FIXME remove - - // SP.putString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)"); - - // RileyLink framework needs to know, when BT was reconnected, so that we can reconnect to RL device - btReceiver = new BroadcastReceiver() { - - @Override - public void onReceive(Context context, Intent intent) { - final String action = intent.getAction(); - - if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { - final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); - switch (state) { - case BluetoothAdapter.STATE_OFF: - case BluetoothAdapter.STATE_TURNING_OFF: - case BluetoothAdapter.STATE_TURNING_ON: - break; - - case BluetoothAdapter.STATE_ON: - Log.v("MainApp", "Bluetooth on"); - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected); - break; - } - } - } - }; - - // Register for broadcasts on BluetoothAdapter state change - IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); - registerReceiver(btReceiver, filter); - - } - - private void startKeepAliveService() { if (keepAliveReceiver == null) { keepAliveReceiver = new KeepAliveReceiver(); @@ -322,13 +258,11 @@ public class MainApp extends Application { } } - public void stopKeepAliveService() { if (keepAliveReceiver != null) KeepAliveReceiver.cancelAlarm(this); } - public static void subscribe(Object subscriber) { try { bus().register(subscriber); @@ -337,7 +271,6 @@ public class MainApp extends Application { } } - public static void unsubscribe(Object subscriber) { try { bus().unregister(subscriber); @@ -346,42 +279,34 @@ public class MainApp extends Application { } } - public static Bus bus() { return sBus; } - public static String gs(int id) { return sResources.getString(id); } - public static String gs(int id, Object... args) { return sResources.getString(id, args); } - public static String gq(@PluralsRes int id, int quantity, Object... args) { return sResources.getQuantityString(id, quantity, args); } - public static int gc(int id) { return sResources.getColor(id); } - public static MainApp instance() { return sInstance; } - public static DatabaseHelper getDbHelper() { return sDatabaseHelper; } - public static void closeDbHelper() { if (sDatabaseHelper != null) { sDatabaseHelper.close(); @@ -389,17 +314,14 @@ public class MainApp extends Application { } } - public static ConstraintChecker getConstraintChecker() { return sConstraintsChecker; } - public static ArrayList getPluginsList() { return pluginsList; } - public static ArrayList getSpecificPluginsList(PluginType type) { ArrayList newList = new ArrayList<>(); @@ -414,7 +336,6 @@ public class MainApp extends Application { return newList; } - public static ArrayList getSpecificPluginsVisibleInList(PluginType type) { ArrayList newList = new ArrayList<>(); @@ -430,7 +351,6 @@ public class MainApp extends Application { return newList; } - public static ArrayList getSpecificPluginsListByInterface(Class interfaceClass) { ArrayList newList = new ArrayList<>(); @@ -445,7 +365,6 @@ public class MainApp extends Application { return newList; } - public static ArrayList getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type) { ArrayList newList = new ArrayList<>(); @@ -461,13 +380,12 @@ public class MainApp extends Application { return newList; } - @Nullable public static T getSpecificPlugin(Class pluginClass) { if (pluginsList != null) { for (PluginBase p : pluginsList) { if (pluginClass.isAssignableFrom(p.getClass())) - return (T)p; + return (T) p; } } else { log.error("pluginsList=null"); @@ -475,26 +393,16 @@ public class MainApp extends Application { return null; } - - public static boolean isEngineeringMode() { - if (!Config.APS) - return true; - return engineeringMode; - } - - public static boolean isEngineeringModeOrRelease() { if (!Config.APS) return true; return engineeringMode || !devBranch; } - public static boolean isDev() { return devBranch; } - public static int getIcon() { if (Config.NSCLIENT) return R.mipmap.ic_yellowowl; @@ -504,7 +412,6 @@ public class MainApp extends Application { return R.mipmap.ic_launcher; } - public static int getNotificationIcon() { if (Config.NSCLIENT) return R.drawable.ic_notif_nsclient; @@ -514,7 +421,6 @@ public class MainApp extends Application { return R.drawable.ic_notif_aaps; } - @Override public void onTerminate() { if (L.isEnabled(L.CORE)) @@ -524,9 +430,5 @@ public class MainApp extends Application { sDatabaseHelper.close(); sDatabaseHelper = null; } - - if (btReceiver != null) { - unregisterReceiver(btReceiver); - } } } diff --git a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java index ceb85c6967..68664033d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java +++ b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java @@ -50,6 +50,10 @@ public class ConstraintChecker implements ConstraintsInterface { return isAdvancedFilteringEnabled(new Constraint<>(true)); } + public Constraint isSuperBolusEnabled() { + return isSuperBolusEnabled(new Constraint<>(true)); + } + public Constraint getMaxBasalAllowed(Profile profile) { return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile); } @@ -157,6 +161,17 @@ public class ConstraintChecker implements ConstraintsInterface { return value; } + @Override + public Constraint isSuperBolusEnabled(Constraint value) { + ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); + for (PluginBase p : constraintsPlugins) { + ConstraintsInterface constraint = (ConstraintsInterface) p; + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; + constraint.isSuperBolusEnabled(value); + } + return value; + } + @Override public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 7799c5b27f..d99c38a0f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -503,7 +503,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } catch (SQLException e) { log.error("Unhandled exception", e); } - return new ArrayList(); + return new ArrayList<>(); } @@ -521,7 +521,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } catch (SQLException e) { log.error("Unhandled exception", e); } - return new ArrayList(); + return new ArrayList<>(); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java index 5ac8cc83f7..f1c79dd5cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java @@ -35,6 +35,10 @@ public interface ConstraintsInterface { return value; } + default Constraint isSuperBolusEnabled(Constraint value) { + return value; + } + default Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { return absoluteRate; } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java index b92b8a8f87..01be296539 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java @@ -93,6 +93,8 @@ public abstract class PluginBase { return state == State.ENABLED && specialEnableCondition(); if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP)) return true; + if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.APS && isEnabled(PluginType.APS)) + return true; if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) return isProfileInterfaceEnabled; return false; diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java index 4c00268352..3690312cf8 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java @@ -1,9 +1,9 @@ package info.nightscout.androidaps.interfaces; -import java.util.List; - import org.json.JSONObject; +import java.util.List; + import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; @@ -16,105 +16,59 @@ import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; public interface PumpInterface { boolean isInitialized(); // true if pump status has been read and is ready to accept commands - - - boolean isSuspended(); // true if suspended (not delivering insulin) - - - boolean isBusy(); // if true pump is not ready to accept commands right now - - - boolean isConnected(); // true if BT connection is established - - - boolean isConnecting(); // true if BT connection is in progress - - + boolean isSuspended(); // true if suspended (not delivering insulin) + boolean isBusy(); // if true pump is not ready to accept commands right now + boolean isConnected(); // true if BT connection is established + boolean isConnecting(); // true if BT connection is in progress boolean isHandshakeInProgress(); // true if BT is connected but initial handshake is still in progress - - void finishHandshaking(); // set initial handshake completed - void connect(String reason); - - void disconnect(String reason); - - void stopConnecting(); - void getPumpStatus(); - // Upload to pump new basal profile PumpEnactResult setNewBasalProfile(Profile profile); - - boolean isThisProfileSet(Profile profile); - long lastDataTime(); - double getBaseBasalRate(); // base basal rate, not temp basal - double getReservoirLevel(); - - int getBatteryLevel(); // in percent as integer - + int getBatteryLevel(); // in percent as integer PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo); - - void stopBolusDelivering(); - - - PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, - boolean enforceNew); - - + PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew); PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew); - - PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes); - - - // some pumps might set a very short temp close to 100% as cancelling a temp can be noisy - // when the cancel request is requested by the user (forced), the pump should always do a real cancel + //some pumps might set a very short temp close to 100% as cancelling a temp can be noisy + //when the cancel request is requested by the user (forced), the pump should always do a real cancel PumpEnactResult cancelTempBasal(boolean enforceNew); - - PumpEnactResult cancelExtendedBolus(); - // Status to be passed to NS JSONObject getJSONStatus(Profile profile, String profileName); - - String deviceID(); - // Pump capabilities PumpDescription getPumpDescription(); - // Short info for SMS, Wear etc String shortStatus(boolean veryShort); - boolean isFakingTempsByExtendedBoluses(); - PumpEnactResult loadTDDs(); + public boolean canHandleDST(); List getCustomActions(); - - PumpEnactResult executeCustomAction(CustomActionType customActionType); + void executeCustomAction(CustomActionType customActionType); } diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.java b/app/src/main/java/info/nightscout/androidaps/logging/L.java index 2c9201bd79..583969c739 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/L.java +++ b/app/src/main/java/info/nightscout/androidaps/logging/L.java @@ -95,6 +95,7 @@ public class L { public static final String PROFILE = "PROFILE"; public static final String CONFIGBUILDER = "CONFIGBUILDER"; public static final String UI = "UI"; + public static final String SMS = "SMS"; private static void initialize() { logElements = new ArrayList<>(); @@ -117,6 +118,7 @@ public class L { logElements.add(new LogElement(PUMPBTCOMM, false)); logElements.add(new LogElement(PUMPCOMM, true)); logElements.add(new LogElement(PUMPQUEUE, true)); + logElements.add(new LogElement(SMS, true)); logElements.add(new LogElement(UI, true)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 7ee7cf0348..91bbccc515 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -34,6 +34,7 @@ import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventNewBG; +import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginBase; @@ -175,6 +176,14 @@ public class LoopPlugin extends PluginBase { return loopSuspendedTill; } + @Subscribe + public void onStatusEvent(final EventTempTargetChange ev) { + new Thread(() -> invoke("EventTempTargetChange", true)).start(); + FabricPrivacy.getInstance().logCustom(new CustomEvent("TT_Loop_Run")); + } + + + public void suspendTo(long endTime) { loopSuspendedTill = endTime; isSuperBolus = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index f1232e39c3..73914662d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -13,6 +13,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.Constraint; +import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; @@ -38,7 +39,7 @@ import info.nightscout.androidaps.utils.ToastUtils; /** * Created by mike on 05.08.2016. */ -public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { +public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { private static Logger log = LoggerFactory.getLogger(L.APS); private static OpenAPSSMBPlugin openAPSSMBPlugin; @@ -147,7 +148,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { if (L.isEnabled(L.APS)) Profiler.log(log, "getMealData()", startPart); - double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + Constraint maxIOBAllowedConstraint = MainApp.getConstraintChecker().getMaxIOBAllowed(); + inputConstraints.copyReasons(maxIOBAllowedConstraint); + double maxIob = maxIOBAllowedConstraint.value(); minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); @@ -266,4 +269,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { return newvalue; } + public Constraint isSuperBolusEnabled(Constraint value) { + value.set(false); + return value; + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.java index c456a626e7..b374c78413 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.java @@ -42,6 +42,7 @@ import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; + import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.utils.FabricPrivacy; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java index c87432a9ab..6b9b353979 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -16,6 +16,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.interfaces.ProfileInterface; @@ -139,4 +140,44 @@ public class ProfileFunctions { return null; } + public static ProfileSwitch prepareProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, long date) { + ProfileSwitch profileSwitch = new ProfileSwitch(); + profileSwitch.date = date; + profileSwitch.source = Source.USER; + profileSwitch.profileName = profileName; + profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); + profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); + profileSwitch.durationInMinutes = duration; + profileSwitch.isCPP = percentage != 100 || timeshift != 0; + profileSwitch.timeshift = timeshift; + profileSwitch.percentage = percentage; + return profileSwitch; + } + + public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) { + ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeshift, System.currentTimeMillis()); + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); + FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch")); + } + + public static void doProfileSwitch(final int duration, final int percentage, final int timeshift) { + ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); + if (profileSwitch != null) { + profileSwitch = new ProfileSwitch(); + profileSwitch.date = System.currentTimeMillis(); + profileSwitch.source = Source.USER; + profileSwitch.profileName = getInstance().getProfileName(System.currentTimeMillis(), false); + profileSwitch.profileJson = getInstance().getProfile().getData().toString(); + profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); + profileSwitch.durationInMinutes = duration; + profileSwitch.isCPP = percentage != 100 || timeshift != 0; + profileSwitch.timeshift = timeshift; + profileSwitch.percentage = percentage; + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); + FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch")); + } else { + log.error("No profile switch existing"); + } + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java index 2862cc3d7a..ec3ef44881 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java @@ -12,18 +12,17 @@ import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.utils.T; -/** - * Created by Rumen on 31.10.2018. - */ public class DstHelperPlugin extends PluginBase implements ConstraintsInterface { + public static final int DISABLE_TIMEFRAME_HOURS = -3; + public static final int WARN_PRIOR_TIMEFRAME_HOURS = 24; private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS); - private int minutesToChange = 0; static DstHelperPlugin plugin = null; @@ -43,83 +42,53 @@ public class DstHelperPlugin extends PluginBase implements ConstraintsInterface ); } - public int dstTest(Calendar c) throws Exception { -// c = Calendar.getInstance(TimeZone.getDefault()); -// c = Calendar.getInstance(TimeZone.getTimeZone("Australia/Lord_Howe")); -// c.setTimeInMillis(DateUtil.fromISODateString("2018-10-07T01:00:00Z").getTime()); - long zoneOffset = c.get(Calendar.ZONE_OFFSET); - long d1 = c.getTimeInMillis() - zoneOffset; - c.setTimeInMillis(d1); - int offset1 = c.get(Calendar.DST_OFFSET); - - c.add(Calendar.DATE, 1); - long d2 = c.getTimeInMillis(); - - int diffInHours = (int) ((d1 - d2) / -T.hours(1).msecs()); - long offsetDetectedTime = 0; - // comparing millis because change can be < 1 hour -// log.debug("Starting from: "+startTimeString + " to "+endTimeString); -// log.debug("start "+offset1+" end "+c.get(Calendar.DST_OFFSET)); - if (offset1 != c.get(Calendar.DST_OFFSET)) { - //we have a time change in next 24 hours, but when exactly -// log.debug("Daylight saving time detected between " + startTimeString + " and " + endTimeString); -// log.debug("Diff in hours is: "+diffInHours); - c.setTimeInMillis(d1 - zoneOffset); - offset1 = c.get(Calendar.DST_OFFSET); - for (int i = 0; i <= diffInHours * 4; i++) { - - if (offset1 != c.get(Calendar.DST_OFFSET)) { - log.debug("Detected offset in " + ((i / 4) - zoneOffset / T.hours(1).msecs()) + " hours value is " + (offset1 - c.get(Calendar.DST_OFFSET)) / T.mins(1).msecs() + " minutes"); - offsetDetectedTime = c.getTimeInMillis() - d1; - break; - } - c.add(Calendar.MINUTE, 15); - - } - } - int minutesLeft = (int) ((offsetDetectedTime / T.mins(1).msecs())); - /*log.debug("zoneoffset(minutes):"+zoneOffset/T.mins(1).msecs()); - log.debug("Start offset: "+offset1/T.mins(1).msecs()); - log.debug("End offset :" + c.get(Calendar.DST_OFFSET)/T.mins(1).msecs()); - log.debug("Now is:"+startTimeString); - log.debug("Detected in(min): "+(offsetDetectedTime/T.mins(1).msecs())); - log.debug("Returning value of: " + minutesLeft); */ - minutesToChange = minutesLeft; - return minutesLeft; - + public static boolean wasDST(Calendar now) { + Calendar ago = (Calendar) now.clone(); + ago.add(Calendar.HOUR, DISABLE_TIMEFRAME_HOURS); + return now.get(Calendar.DST_OFFSET) != ago.get(Calendar.DST_OFFSET); } - //Return false if time to DST change is less than 91 and positive + public static boolean willBeDST(Calendar now) { + Calendar ago = (Calendar) now.clone(); + ago.add(Calendar.HOUR, WARN_PRIOR_TIMEFRAME_HOURS); + return now.get(Calendar.DST_OFFSET) != ago.get(Calendar.DST_OFFSET); + } + + //Return false if time to DST change happened in the last 3 hours. @Override public Constraint isLoopInvocationAllowed(Constraint value) { - try { - this.dstTest(Calendar.getInstance()); - } catch (Exception e) { - e.printStackTrace(); - } - if (this.minutesToChange <= 90 && minutesToChange > 0 && value.value()) { - try { - LoopPlugin loopPlugin = LoopPlugin.getPlugin(); - if (loopPlugin.suspendedTo() == 0L) { -// loopPlugin.suspendTo(System.currentTimeMillis() + minutesToChange * T.mins(1).msecs()); - warnUser(Notification.DST_LOOP_DISABLED, MainApp.gs(R.string.dst_loop_disabled_warning)); - } else - log.debug("Loop already suspended"); - } catch (Exception e) { - e.printStackTrace(); - } - value.set(false, "DST in 90 minutes or less", this); - } else if (minutesToChange <= 24 * T.hours(1).mins() && minutesToChange > 0) { + PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + if (pump == null || pump.canHandleDST()) { + log.debug("Pump can handle DST"); + return value; + } + + Calendar cal = Calendar.getInstance(); + + if (willBeDST(cal)) { warnUser(Notification.DST_IN_24H, MainApp.gs(R.string.dst_in_24h_warning)); } + + if (!value.value()) { + log.debug("Already not allowed - don't check further"); + return value; + } + + if (wasDST(cal)) { + LoopPlugin loopPlugin = LoopPlugin.getPlugin(); + if (!loopPlugin.isSuspended()) { + warnUser(Notification.DST_LOOP_DISABLED, MainApp.gs(R.string.dst_loop_disabled_warning)); + } else { + log.debug("Loop already suspended"); + } + value.set(false, "DST in last 3 hours.", this); + } return value; } - // display warning - void warnUser(int id, String warningText) { + private void warnUser(int id, String warningText) { Notification notification = new Notification(id, warningText, Notification.LOW); MainApp.bus().post(new EventNewNotification(notification)); } - } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.java index 9f1ac748d5..b943571089 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.java @@ -120,6 +120,7 @@ public class ObjectivesFragment extends SubscriberFragment { public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(position); holder.title.setText(MainApp.gs(R.string.nth_objective, position + 1)); + holder.revert.setVisibility(View.INVISIBLE); if (objective.getObjective() != 0) { holder.objective.setVisibility(View.VISIBLE); holder.objective.setText(MainApp.gs(objective.getObjective())); @@ -145,6 +146,9 @@ public class ObjectivesFragment extends SubscriberFragment { holder.verify.setVisibility(View.VISIBLE); holder.verify.setEnabled(objective.isCompleted() || enableFake.isChecked()); holder.start.setVisibility(View.GONE); + if(objective.isRevertable()) { + holder.revert.setVisibility(View.VISIBLE); + } holder.progress.setVisibility(View.VISIBLE); holder.progress.removeAllViews(); for (Objective.Task task : objective.getTasks()) { @@ -169,8 +173,20 @@ public class ObjectivesFragment extends SubscriberFragment { scrollToCurrentObjective(); startUpdateTimer(); }); + holder.revert.setOnClickListener((view) -> { + objective.setAccomplishedOn(null); + objective.setStartedOn(null); + if (position > 0) { + Objective prevObj = ObjectivesPlugin.getPlugin().getObjectives().get(position - 1); + prevObj.setAccomplishedOn(null); + } + notifyDataSetChanged(); + scrollToCurrentObjective(); + }); } + + @Override public int getItemCount() { return ObjectivesPlugin.getPlugin().getObjectives().size(); @@ -185,6 +201,7 @@ public class ObjectivesFragment extends SubscriberFragment { public LinearLayout progress; public Button verify; public Button start; + public Button revert; public ViewHolder(View itemView) { super(itemView); @@ -195,6 +212,7 @@ public class ObjectivesFragment extends SubscriberFragment { progress = itemView.findViewById(R.id.objective_progress); verify = itemView.findViewById(R.id.objective_verify); start = itemView.findViewById(R.id.objective_start); + revert = itemView.findViewById(R.id.objective_back); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java index a1935c2ec6..83abe15688 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java @@ -42,6 +42,10 @@ public abstract class Objective { return true; } + public boolean isRevertable() { + return false; + } + public boolean isAccomplished() { return accomplishedOn != null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective4.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective4.java index 5708565ebe..1bbb4ef7c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective4.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective4.java @@ -25,4 +25,9 @@ public class Objective4 extends Objective { } }); } + + @Override + public boolean isRevertable() { + return true; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java new file mode 100644 index 0000000000..197fd5c17a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.java @@ -0,0 +1,76 @@ +package info.nightscout.androidaps.plugins.constraints.storage; + +import android.os.Environment; +import android.os.StatFs; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; + +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.interfaces.Constraint; +import info.nightscout.androidaps.interfaces.ConstraintsInterface; +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.general.overview.events.EventDismissNotification; +import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; + +/** + * Created by Rumen on 06.03.2019. + */ +public class StorageConstraintPlugin extends PluginBase implements ConstraintsInterface { + private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS); + static StorageConstraintPlugin plugin = null; + + public static StorageConstraintPlugin getPlugin() { + if (plugin == null) + plugin = new StorageConstraintPlugin(); + return plugin; + } + + public StorageConstraintPlugin() { + super(new PluginDescription() + .mainType(PluginType.CONSTRAINTS) + .neverVisible(true) + .alwaysEnabled(true) + .showInList(false) + .pluginName(R.string.storage) + ); + } + + /** + * Constraints interface + **/ + + @Override + public Constraint isClosedLoopAllowed(Constraint value) { + long diskfree = getAvailableInternalMemorySize(); + if (L.isEnabled(L.CONSTRAINTS)) + log.debug("Internal storage free (Mb):" + diskfree); + if (diskfree < Constants.MINIMUM_FREE_SPACE) { + value.set(false, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), this); + Notification notification = new Notification(Notification.DISKFULL, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL); + MainApp.bus().post(new EventNewNotification(notification)); + } else { + MainApp.bus().post(new EventDismissNotification(Notification.DISKFULL)); + } + + return value; + } + + public static long getAvailableInternalMemorySize() { + File path = Environment.getDataDirectory(); + StatFs stat = new StatFs(path.getPath()); + long blockSize = stat.getBlockSizeLong(); + long blocksAvailable = stat.getAvailableBlocksLong(); + int size = 1048576; // blocksize of 1 Mb + return ((blocksAvailable * blockSize) / size); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java index 958e22b1f3..02ff6e6b5c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java @@ -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; @@ -19,14 +15,18 @@ import android.widget.LinearLayout; import com.crashlytics.android.answers.CustomEvent; import com.squareup.otto.Subscribe; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.activities.TDDStatsActivity; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.events.EventCustomActionsChanged; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; @@ -35,17 +35,19 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; 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; + /** * A simple {@link Fragment} subclass. */ @@ -53,7 +55,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL static ActionsPlugin actionsPlugin = new ActionsPlugin(); - static public ActionsPlugin getPlugin() { return actionsPlugin; } @@ -69,6 +70,8 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL SingleClickButton tddStats; SingleClickButton history; + private Map pumpCustomActions = new HashMap<>(); + private List pumpCustomButtons = new ArrayList<>(); public ActionsFragment() { super(); @@ -76,17 +79,18 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL @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); - profileSwitch = (SingleClickButton)view.findViewById(R.id.actions_profileswitch); - tempTarget = (SingleClickButton)view.findViewById(R.id.actions_temptarget); - extendedBolus = (SingleClickButton)view.findViewById(R.id.actions_extendedbolus); - extendedBolusCancel = (SingleClickButton)view.findViewById(R.id.actions_extendedbolus_cancel); - tempBasal = (SingleClickButton)view.findViewById(R.id.actions_settempbasal); - tempBasalCancel = (SingleClickButton)view.findViewById(R.id.actions_canceltempbasal); - fill = (SingleClickButton)view.findViewById(R.id.actions_fill); + profileSwitch = (SingleClickButton) view.findViewById(R.id.actions_profileswitch); + tempTarget = (SingleClickButton) view.findViewById(R.id.actions_temptarget); + extendedBolus = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus); + extendedBolusCancel = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus_cancel); + tempBasal = (SingleClickButton) view.findViewById(R.id.actions_settempbasal); + tempBasalCancel = (SingleClickButton) view.findViewById(R.id.actions_canceltempbasal); + fill = (SingleClickButton) view.findViewById(R.id.actions_fill); tddStats = view.findViewById(R.id.actions_tddstats); history = view.findViewById(R.id.actions_historybrowser); @@ -111,47 +115,34 @@ 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); @@ -169,37 +160,34 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease() - && pump.getPumpDescription().isSetBasalProfileCapable; + && pump.getPumpDescription().isSetBasalProfileCapable; if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended()) profileSwitch.setVisibility(View.GONE); 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); @@ -220,70 +208,64 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL else tempTarget.setVisibility(View.VISIBLE); - if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().supportsTDDs) + if (!pump.getPumpDescription().supportsTDDs) tddStats.setVisibility(View.GONE); else tddStats.setVisibility(View.VISIBLE); - checkCustomActions(); + checkPumpCustomActions(); + } }); } - private String activePumpName; - private Map currentCustomActions = new HashMap<>(); - private List customButtons = new ArrayList<>(); - View.OnClickListener customActionsListener = v -> { + View.OnClickListener pumpCustomActionsListener = v -> { SingleClickButton btn = (SingleClickButton)v; - CustomAction customAction = this.currentCustomActions.get(btn.getText().toString()); + CustomAction customAction = this.pumpCustomActions.get(btn.getText().toString()); ConfigBuilderPlugin.getPlugin().getActivePump().executeCustomAction(customAction.getCustomActionType()); }; - private void checkCustomActions() { + private void checkPumpCustomActions() { PumpInterface activePump = ConfigBuilderPlugin.getPlugin().getActivePump(); - removeCustomActions(); + removePumpCustomActions(); if (activePump == null) { return; } - // add new actions List customActions = activePump.getCustomActions(); - if (customActions != null) { + if (customActions != null && customActions.size()>0) { LinearLayout ll = actionsFragmentView.findViewById(R.id.action_buttons_layout); for (CustomAction customAction : customActions) { - if (!customAction.isEnabled()) - continue; - SingleClickButton btn = new SingleClickButton(getContext(), null, android.R.attr.buttonStyle); btn.setText(MainApp.gs(customAction.getName())); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f); + LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f); layoutParams.setMargins(20, 8, 20, 8); // 10,3,10,3 btn.setLayoutParams(layoutParams); - btn.setOnClickListener(customActionsListener); + btn.setOnClickListener(pumpCustomActionsListener); - Drawable top = getResources().getDrawable(R.drawable.icon_actions_profileswitch); + Drawable top = getResources().getDrawable(customAction.getIconResourceId()); btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null); ll.addView(btn); - this.currentCustomActions.put(MainApp.gs(customAction.getName()), customAction); - this.customButtons.add(btn); + this.pumpCustomActions.put(MainApp.gs(customAction.getName()), customAction); + this.pumpCustomButtons.add(btn); } } @@ -291,19 +273,19 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL } - private void removeCustomActions() { + private void removePumpCustomActions() { - if (currentCustomActions.size() == 0) + if (pumpCustomActions.size()==0) return; LinearLayout ll = actionsFragmentView.findViewById(R.id.action_buttons_layout); - for (SingleClickButton customButton : customButtons) { + for (SingleClickButton customButton : pumpCustomButtons) { ll.removeView(customButton); } - customButtons.clear(); - currentCustomActions.clear(); + pumpCustomButtons.clear(); + pumpCustomActions.clear(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/defs/CustomAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/defs/CustomAction.java index 8e0bf1d81b..e5e119baad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/defs/CustomAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/defs/CustomAction.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.general.actions.defs; +import info.nightscout.androidaps.R; + /** * Created by andy on 9/20/18. */ @@ -9,18 +11,19 @@ public class CustomAction { private int name; private String iconName; private CustomActionType customActionType; - private boolean enabled = true; + private int iconResourceId; public CustomAction(int nameResourceId, CustomActionType actionType) { - this(nameResourceId, actionType, true); - } - - - public CustomAction(int nameResourceId, CustomActionType actionType, boolean enabled) { this.name = nameResourceId; this.customActionType = actionType; - this.enabled = enabled; + this.iconResourceId = R.drawable.icon_actions_profileswitch; + } + + public CustomAction(int nameResourceId, CustomActionType actionType, int iconResourceId) { + this.name = nameResourceId; + this.customActionType = actionType; + this.iconResourceId = iconResourceId; } @@ -30,16 +33,6 @@ public class CustomAction { } - public String getIconName() { - - return iconName; - } - - - public void setIconName(String iconName) { - - this.iconName = iconName; - } public CustomActionType getCustomActionType() { @@ -48,18 +41,7 @@ public class CustomAction { } - public void setCustomActionType(CustomActionType customActionType) { - - this.customActionType = customActionType; - } - - - public boolean isEnabled() { - return enabled; - } - - - public void setEnabled(boolean enabled) { - this.enabled = enabled; + public int getIconResourceId() { + return iconResourceId; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java index 058c31b0b5..991fc962ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java @@ -229,8 +229,8 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli double sageWarn = nsSettings.getExtendedWarnValue("sage", "warn", 164); handleAge(sage, CareportalEvent.SENSORCHANGE, sageWarn, sageUrgent); - double pbageUrgent = nsSettings.getExtendedWarnValue("pgage", "urgent", 360); - double pbageWarn = nsSettings.getExtendedWarnValue("pgage", "warn", 240); + double pbageUrgent = nsSettings.getExtendedWarnValue("bage", "urgent", 360); + double pbageWarn = nsSettings.getExtendedWarnValue("bage", "warn", 240); handleAge(pbage, CareportalEvent.PUMPBATTERYCHANGE, pbageWarn, pbageUrgent); } ); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java index 1e38a0131a..e4eccd18d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java @@ -722,7 +722,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick public void createNSTreatment(JSONObject data) { if (options.executeProfileSwitch) { if (data.has("profile")) { - doProfileSwitch(profileStore, JsonHelper.safeGetString(data, "profile"), JsonHelper.safeGetInt(data, "duration"), JsonHelper.safeGetInt(data, "percentage"), JsonHelper.safeGetInt(data, "timeshift")); + ProfileFunctions.doProfileSwitch(profileStore, JsonHelper.safeGetString(data, "profile"), JsonHelper.safeGetInt(data, "duration"), JsonHelper.safeGetInt(data, "percentage"), JsonHelper.safeGetInt(data, "timeshift")); } } else if (options.executeTempTarget) { final int duration = JsonHelper.safeGetInt(data, "duration"); @@ -746,7 +746,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } } else { if (JsonHelper.safeGetString(data, "eventType").equals(CareportalEvent.PROFILESWITCH)) { - ProfileSwitch profileSwitch = prepareProfileSwitch( + ProfileSwitch profileSwitch = ProfileFunctions.prepareProfileSwitch( profileStore, JsonHelper.safeGetString(data, "profile"), JsonHelper.safeGetInt(data, "duration"), @@ -762,46 +762,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } } - public static ProfileSwitch prepareProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, long date) { - ProfileSwitch profileSwitch = new ProfileSwitch(); - profileSwitch.date = date; - profileSwitch.source = Source.USER; - profileSwitch.profileName = profileName; - profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); - profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); - profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeshift != 0; - profileSwitch.timeshift = timeshift; - profileSwitch.percentage = percentage; - return profileSwitch; - } - - public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) { - ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeshift, System.currentTimeMillis()); - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); - FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch")); - } - - public static void doProfileSwitch(final int duration, final int percentage, final int timeshift) { - ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); - if (profileSwitch != null) { - profileSwitch = new ProfileSwitch(); - profileSwitch.date = System.currentTimeMillis(); - profileSwitch.source = Source.USER; - profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), false); - profileSwitch.profileJson = ProfileFunctions.getInstance().getProfile().getData().toString(); - profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); - profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeshift != 0; - profileSwitch.timeshift = timeshift; - profileSwitch.percentage = percentage; - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); - FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch")); - } else { - log.error("No profile switch existing"); - } - } - @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putString("notesEdit", notesEdit.getText().toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java index 07d76d90fe..8eeee8c43c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java @@ -48,9 +48,7 @@ class NsClientReceiverDelegate { bus.post(event); context.registerReceiver(chargingStateReceiver, - new IntentFilter(Intent.ACTION_POWER_CONNECTED)); - context.registerReceiver(chargingStateReceiver, - new IntentFilter(Intent.ACTION_POWER_DISCONNECTED)); + new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); EventChargingState eventChargingState = chargingStateReceiver.grabChargingState(context); if (eventChargingState != null) @@ -97,7 +95,7 @@ class NsClientReceiverDelegate { } void processStateChange() { - boolean newAllowedState = allowedChargingState && allowedNetworkState; + boolean newAllowedState = allowedChargingState && allowedNetworkState; if (newAllowedState != allowed) { allowed = newAllowedState; bus.post(new EventPreferenceChange(R.string.key_nsclientinternal_paused)); @@ -109,7 +107,9 @@ class NsClientReceiverDelegate { boolean newAllowedState = true; - if (!ev.isCharging && chargingOnly) newAllowedState = false; + if (!ev.isCharging && chargingOnly) { + newAllowedState = false; + } return newAllowedState; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/Dialogs/WizardDialog.java index d357bf9f06..33b3019668 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/Dialogs/WizardDialog.java @@ -51,17 +51,16 @@ import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventFeatureRunning; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.BolusWizard; @@ -165,18 +164,6 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com } - @Subscribe - public void onStatusEvent(final EventNewBG e) { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - calculateInsulin(); - } - }); - } - @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished e) { Activity activity = getActivity(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.java index 5477963240..3b6bcf615d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.java @@ -73,6 +73,7 @@ public class Notification { public static final int INSIGHT_TIMEOUT_DURING_HANDSHAKE = 48; public static final int DST_LOOP_DISABLED = 49; public static final int DST_IN_24H = 50; + public static final int DISKFULL = 51; public int id; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java index 04d5e9ffbe..0287c21260 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java @@ -27,7 +27,6 @@ import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventInitializationChanged; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshOverview; @@ -39,6 +38,7 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -283,7 +283,7 @@ public class PersistentNotificationPlugin extends PluginBase { } @Subscribe - public void onStatusEvent(final EventNewBG ev) { + public void onStatusEvent(final EventAutosensCalculationFinished ev) { triggerNotificationUpdate(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.java new file mode 100644 index 0000000000..4b05072eb1 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.java @@ -0,0 +1,59 @@ +package info.nightscout.androidaps.plugins.general.smsCommunicator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.utils.DateUtil; + +class AuthRequest { + private static Logger log = LoggerFactory.getLogger(L.SMS); + + Sms requester; + String confirmCode; + private Runnable action; + + private long date; + + private boolean processed; + private SmsCommunicatorPlugin plugin; + + AuthRequest(SmsCommunicatorPlugin plugin, Sms requester, String requestText, String confirmCode, SmsAction action) { + this.requester = requester; + this.confirmCode = confirmCode; + this.action = action; + this.plugin = plugin; + + this.date = DateUtil.now(); + + plugin.sendSMS(new Sms(requester.phoneNumber, requestText)); + } + + void action(String codeReceived) { + if (processed) { + if (L.isEnabled(L.SMS)) + log.debug("Already processed"); + return; + } + if (!confirmCode.equals(codeReceived)) { + processed = true; + if (L.isEnabled(L.SMS)) + log.debug("Wrong code"); + plugin.sendSMS(new Sms(requester.phoneNumber, R.string.sms_wrongcode)); + return; + } + if (DateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) { + processed = true; + if (L.isEnabled(L.SMS)) + log.debug("Processing confirmed SMS: " + requester.text); + if (action != null) + action.run(); + return; + } + if (L.isEnabled(L.SMS)) + log.debug("Timed out SMS: " + requester.text); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.java new file mode 100644 index 0000000000..2eedfa0a51 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.java @@ -0,0 +1,42 @@ +package info.nightscout.androidaps.plugins.general.smsCommunicator; + +import android.telephony.SmsMessage; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.utils.DateUtil; + +class Sms { + String phoneNumber; + String text; + long date; + boolean received = false; + boolean sent = false; + boolean processed = false; + boolean ignored = false; + + Sms(SmsMessage message) { + phoneNumber = message.getOriginatingAddress(); + text = message.getMessageBody(); + date = message.getTimestampMillis(); + received = true; + } + + Sms(String phoneNumber, String text) { + this.phoneNumber = phoneNumber; + this.text = text; + this.date = DateUtil.now(); + sent = true; + } + + Sms(String phoneNumber, int textId) { + this.phoneNumber = phoneNumber; + this.text = MainApp.gs(textId); + this.date = DateUtil.now(); + sent = true; + } + + public String toString() { + return "SMS from " + phoneNumber + ": " + text; + } +} + diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.java new file mode 100644 index 0000000000..6b5d5b8747 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.java @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.plugins.general.smsCommunicator; + +abstract class SmsAction implements Runnable { + Double aDouble; + Integer anInteger; + Integer secondInteger; + String aString; + + SmsAction() {} + + SmsAction(Double aDouble) { + this.aDouble = aDouble; + } + + SmsAction(Double aDouble, Integer secondInteger) { + this.aDouble = aDouble; + this.secondInteger = secondInteger; + } + + SmsAction(String aString, Integer secondInteger) { + this.aString = aString; + this.secondInteger = secondInteger; + } + + SmsAction(Integer anInteger) { + this.anInteger = anInteger; + } + + SmsAction(Integer anInteger, Integer secondInteger) { + this.anInteger = anInteger; + this.secondInteger = secondInteger; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java index 8e46159bd9..d1c4adf5fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator; import android.app.Activity; import android.os.Bundle; -import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; @@ -12,9 +11,6 @@ import android.widget.TextView; import com.squareup.otto.Subscribe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Collections; import java.util.Comparator; @@ -22,14 +18,8 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.FabricPrivacy; -/** - * A simple {@link Fragment} subclass. - */ public class SmsCommunicatorFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(SmsCommunicatorFragment.class); - TextView logView; public SmsCommunicatorFragment() { @@ -39,18 +29,11 @@ public class SmsCommunicatorFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false); + View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false); - logView = (TextView) view.findViewById(R.id.smscommunicator_log); + logView = (TextView) view.findViewById(R.id.smscommunicator_log); - updateGUI(); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } - - return null; + return view; } @Subscribe @@ -58,35 +41,33 @@ public class SmsCommunicatorFragment extends SubscriberFragment { updateGUI(); } - @Override protected void updateGUI() { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - class CustomComparator implements Comparator { - public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) { - return (int) (object1.date - object2.date); - } + activity.runOnUiThread(() -> { + class CustomComparator implements Comparator { + public int compare(Sms object1, Sms object2) { + return (int) (object1.date - object2.date); } - Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator()); - int messagesToShow = 40; - - int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow); - - String logText = ""; - for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) { - SmsCommunicatorPlugin.Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x); - if (sms.received) { - logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; - } else if (sms.sent) { - logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; - } - } - logView.setText(Html.fromHtml(logText)); } + Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator()); + int messagesToShow = 40; + + int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow); + + String logText = ""; + for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) { + Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x); + if (sms.ignored) { + logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + "
"; + } else if (sms.received) { + logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; + } else if (sms.sent) { + logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; + } + } + logView.setText(Html.fromHtml(logText)); }); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java index 95ceccab3d..e4ec65df11 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java @@ -3,30 +3,27 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator; import android.content.Intent; import android.content.pm.ResolveInfo; import android.os.Bundle; -import android.os.SystemClock; import android.telephony.SmsManager; import android.telephony.SmsMessage; -import com.crashlytics.android.answers.CustomEvent; import com.squareup.otto.Subscribe; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.Normalizer; import java.util.ArrayList; -import java.util.Date; import java.util.List; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; @@ -36,27 +33,32 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +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.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; +import info.nightscout.androidaps.services.Intents; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; -import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.XdripCalibrations; /** * Created by mike on 05.08.2016. */ public class SmsCommunicatorPlugin extends PluginBase { - private static Logger log = LoggerFactory.getLogger(SmsCommunicatorPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.SMS); private static SmsCommunicatorPlugin smsCommunicatorPlugin; @@ -68,59 +70,15 @@ public class SmsCommunicatorPlugin extends PluginBase { return smsCommunicatorPlugin; } - private List allowedNumbers = new ArrayList<>(); + List allowedNumbers = new ArrayList<>(); - class Sms { - String phoneNumber; - String text; - long date; - boolean received = false; - boolean sent = false; - boolean processed = false; + AuthRequest messageToConfirm = null; - String confirmCode; - double bolusRequested = 0d; - double tempBasal = 0d; - double calibrationRequested = 0d; - int duration = 0; - - Sms(SmsMessage message) { - phoneNumber = message.getOriginatingAddress(); - text = message.getMessageBody(); - date = message.getTimestampMillis(); - received = true; - } - - Sms(String phoneNumber, String text, long date) { - this.phoneNumber = phoneNumber; - this.text = text; - this.date = date; - sent = true; - } - - Sms(String phoneNumber, String text, long date, String confirmCode) { - this.phoneNumber = phoneNumber; - this.text = text; - this.date = date; - this.confirmCode = confirmCode; - sent = true; - } - - public String toString() { - return "SMS from " + phoneNumber + ": " + text; - } - } - - private Sms cancelTempBasalWaitingForConfirmation = null; - private Sms tempBasalWaitingForConfirmation = null; - private Sms bolusWaitingForConfirmation = null; - private Sms calibrationWaitingForConfirmation = null; - private Sms suspendWaitingForConfirmation = null; - private Date lastRemoteBolusTime = new Date(0); + long lastRemoteBolusTime = 0; ArrayList messages = new ArrayList<>(); - private SmsCommunicatorPlugin() { + SmsCommunicatorPlugin() { super(new PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(SmsCommunicatorFragment.class.getName()) @@ -159,7 +117,26 @@ public class SmsCommunicatorPlugin extends PluginBase { } } - private boolean isAllowedNumber(String number) { + boolean isCommand(String command, String number) { + switch(command.toUpperCase()) { + case "BG": + case "LOOP": + case "TREATMENTS": + case "NSCLIENT": + case "PUMP": + case "BASAL": + case "BOLUS": + case "EXTENDED": + case "CAL": + case "PROFILE": + return true; + } + if (messageToConfirm != null && messageToConfirm.requester.phoneNumber.equals(number)) + return true; + return false; + } + + boolean isAllowedNumber(String number) { for (String num : allowedNumbers) { if (num.equals(number)) return true; } @@ -180,367 +157,103 @@ public class SmsCommunicatorPlugin extends PluginBase { } } - private void processSms(final Sms receivedSms) { + void processSms(final Sms receivedSms) { if (!isEnabled(PluginType.GENERAL)) { log.debug("Ignoring SMS. Plugin disabled."); return; } if (!isAllowedNumber(receivedSms.phoneNumber)) { log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed"); + receivedSms.ignored = true; + messages.add(receivedSms); + MainApp.bus().post(new EventSmsCommunicatorUpdateGui()); return; } - String reply = ""; - messages.add(receivedSms); log.debug(receivedSms.toString()); - String[] splited = receivedSms.text.split("\\s+"); - Double amount; - Double tempBasal; - int duration = 0; - String passCode; + String[] splitted = receivedSms.text.split("\\s+"); boolean remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false); - if (splited.length > 0) { - switch (splited[0].toUpperCase()) { + if (splitted.length > 0 && isCommand(splitted[0].toUpperCase(), receivedSms.phoneNumber)) { + switch (splitted[0].toUpperCase()) { case "BG": - BgReading actualBG = DatabaseHelper.actualBg(); - BgReading lastBG = DatabaseHelper.lastBg(); - - String units = ProfileFunctions.getInstance().getProfileUnits(); - - if (actualBG != null) { - reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", "; - } else if (lastBG != null) { - Long agoMsec = System.currentTimeMillis() - lastBG.date; - int agoMin = (int) (agoMsec / 60d / 1000d); - reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", "; - } - GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); - if (glucoseStatus != null) - reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", "; - - TreatmentsPlugin.getPlugin().updateTotalIOBTreatments(); - IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round(); - TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals(); - IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round(); - - reply += MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" - + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " - + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)"; - - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bg")); + processBG(splitted, receivedSms); break; case "LOOP": - if (splited.length > 1) - switch (splited[1].toUpperCase()) { - case "DISABLE": - case "STOP": - LoopPlugin loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); - if (loopPlugin != null && loopPlugin.isEnabled(PluginType.LOOP)) { - loopPlugin.setPluginEnabled(PluginType.LOOP, false); - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { - @Override - public void run() { - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP")); - String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " + - MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - }); - } - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Stop")); - break; - case "ENABLE": - case "START": - loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); - if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) { - loopPlugin.setPluginEnabled(PluginType.LOOP, true); - reply = MainApp.gs(R.string.smscommunicator_loophasbeenenabled); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START")); - } - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Start")); - break; - case "STATUS": - loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); - if (loopPlugin != null) { - if (loopPlugin.isEnabled(PluginType.LOOP)) { - if (loopPlugin.isSuspended()) - reply = String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()); - else - reply = MainApp.gs(R.string.smscommunicator_loopisenabled); - } else { - reply = MainApp.gs(R.string.smscommunicator_loopisdisabled); - } - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Status")); - break; - case "RESUME": - LoopPlugin.getPlugin().suspendTo(0); - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME")); - NSUpload.uploadOpenAPSOffline(0); - reply = MainApp.gs(R.string.smscommunicator_loopresumed); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Resume")); - break; - case "SUSPEND": - if (splited.length >= 3) - duration = SafeParse.stringToInt(splited[2]); - duration = Math.max(0, duration); - duration = Math.min(180, duration); - if (duration == 0) { - reply = MainApp.gs(R.string.smscommunicator_wrongduration); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else if (remoteCommandsAllowed) { - passCode = generatePasscode(); - reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode); - receivedSms.processed = true; - resetWaitingMessages(); - sendSMS(suspendWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode)); - suspendWaitingForConfirmation.duration = duration; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Suspend")); - } else { - reply = MainApp.gs(R.string.smscommunicator_remotecommandnotallowed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - break; - } + if (!remoteCommandsAllowed) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)); + else if (splitted.length == 2 || splitted.length == 3) + processLOOP(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; case "TREATMENTS": - if (splited.length > 1) - switch (splited[1].toUpperCase()) { - case "REFRESH": - Intent restartNSClient = new Intent(Intents.ACTION_RESTART); - TreatmentsPlugin.getPlugin().getService().resetTreatments(); - MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); - List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); - reply = "TERATMENTS REFRESH " + q.size() + " receivers"; - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Treatments_Refresh")); - break; - } + if (splitted.length == 2) + processTREATMENTS(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; case "NSCLIENT": - if (splited.length > 1) - switch (splited[1].toUpperCase()) { - case "RESTART": - Intent restartNSClient = new Intent(Intents.ACTION_RESTART); - MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); - List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); - reply = "NSCLIENT RESTART " + q.size() + " receivers"; - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Nsclient_Restart")); - break; - } + if (splitted.length == 2) + processNSCLIENT(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; case "PUMP": - case "DANAR": - ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() { - @Override - public void run() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (result.success) { - if (pump != null) { - String reply = pump.shortStatus(true); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } else { - String reply = MainApp.gs(R.string.readstatusfailed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } - }); - receivedSms.processed = true; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Pump")); + processPUMP(splitted, receivedSms); + break; + case "PROFILE": + if (!remoteCommandsAllowed) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)); + else if (splitted.length == 2 || splitted.length == 3) + processPROFILE(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; case "BASAL": - if (splited.length > 1) { - if (splited[1].toUpperCase().equals("CANCEL") || splited[1].toUpperCase().equals("STOP")) { - if (remoteCommandsAllowed) { - passCode = generatePasscode(); - reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode); - receivedSms.processed = true; - resetWaitingMessages(); - sendSMS(cancelTempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode)); - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal")); - } else { - reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } else { - tempBasal = SafeParse.stringToDouble(splited[1]); - Profile profile = ProfileFunctions.getInstance().getProfile(); - if (profile == null) { - reply = MainApp.gs(R.string.noprofile); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else { - tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value(); - if (remoteCommandsAllowed) { - passCode = generatePasscode(); - reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, passCode); - receivedSms.processed = true; - resetWaitingMessages(); - sendSMS(tempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode)); - tempBasalWaitingForConfirmation.tempBasal = tempBasal; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal")); - } else { - reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } - } - } + if (!remoteCommandsAllowed) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)); + else if (splitted.length == 2 || splitted.length == 3) + processBASAL(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + break; + case "EXTENDED": + if (!remoteCommandsAllowed) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)); + else if (splitted.length == 2 || splitted.length == 3) + processEXTENDED(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; case "BOLUS": - if (System.currentTimeMillis() - lastRemoteBolusTime.getTime() < Constants.remoteBolusMinDistance) { - reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended()) { - reply = MainApp.gs(R.string.pumpsuspended); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else if (splited.length > 1) { - amount = SafeParse.stringToDouble(splited[1]); - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); - if (amount > 0d && remoteCommandsAllowed) { - passCode = generatePasscode(); - reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), amount, passCode); - receivedSms.processed = true; - resetWaitingMessages(); - sendSMS(bolusWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode)); - bolusWaitingForConfirmation.bolusRequested = amount; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bolus")); - } else { - reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } + if (!remoteCommandsAllowed) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)); + else if (splitted.length == 2 && DateUtil.now() - lastRemoteBolusTime < Constants.remoteBolusMinDistance) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotebolusnotallowed)); + else if (splitted.length == 2 && ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended()) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.pumpsuspended)); + else if (splitted.length == 2) + processBOLUS(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; case "CAL": - if (splited.length > 1) { - amount = SafeParse.stringToDouble(splited[1]); - if (amount > 0d && remoteCommandsAllowed) { - passCode = generatePasscode(); - reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), amount, passCode); - receivedSms.processed = true; - resetWaitingMessages(); - sendSMS(calibrationWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode)); - calibrationWaitingForConfirmation.calibrationRequested = amount; - FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Cal")); - } else { - reply = MainApp.gs(R.string.smscommunicator_remotecalibrationnotallowed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } + if (!remoteCommandsAllowed) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)); + else if (splitted.length == 2) + processCAL(splitted, receivedSms); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); break; default: // expect passCode here - if (bolusWaitingForConfirmation != null && !bolusWaitingForConfirmation.processed && - bolusWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - bolusWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) { - bolusWaitingForConfirmation.processed = true; - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.insulin = bolusWaitingForConfirmation.bolusRequested; - detailedBolusInfo.source = Source.USER; - ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() { - @Override - public void run() { - PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - if (result.success) { - SystemClock.sleep(T.secs(15).msecs()); // wait some time to get history - String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), result.bolusDelivered); - if (pump != null) - reply += "\n" + pump.shortStatus(true); - lastRemoteBolusTime = new Date(); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else { - SystemClock.sleep(T.secs(60).msecs()); // wait some time to get history - String reply = MainApp.gs(R.string.smscommunicator_bolusfailed); - if (pump != null) - reply += "\n" + pump.shortStatus(true); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } - }); - } else if (tempBasalWaitingForConfirmation != null && !tempBasalWaitingForConfirmation.processed && - tempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - tempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) { - tempBasalWaitingForConfirmation.processed = true; - Profile profile = ProfileFunctions.getInstance().getProfile(); - if (profile != null) - ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(tempBasalWaitingForConfirmation.tempBasal, 30, true, profile, new Callback() { - @Override - public void run() { - if (result.success) { - String reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration); - reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else { - String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed); - reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } - }); - } else if (cancelTempBasalWaitingForConfirmation != null && !cancelTempBasalWaitingForConfirmation.processed && - cancelTempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - cancelTempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) { - cancelTempBasalWaitingForConfirmation.processed = true; - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { - @Override - public void run() { - if (result.success) { - String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled); - reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else { - String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed); - reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } - }); - } else if (calibrationWaitingForConfirmation != null && !calibrationWaitingForConfirmation.processed && - calibrationWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - calibrationWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) { - calibrationWaitingForConfirmation.processed = true; - boolean result = XdripCalibrations.sendIntent(calibrationWaitingForConfirmation.calibrationRequested); - if (result) { - reply = MainApp.gs(R.string.smscommunicator_calibrationsent); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else { - reply = MainApp.gs(R.string.smscommunicator_calibrationfailed); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } else if (suspendWaitingForConfirmation != null && !suspendWaitingForConfirmation.processed && - suspendWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - suspendWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) { - suspendWaitingForConfirmation.processed = true; - final int dur = suspendWaitingForConfirmation.duration; - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { - @Override - public void run() { - if (result.success) { - LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + dur * 60L * 1000); - NSUpload.uploadOpenAPSOffline(dur * 60); - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED")); - String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " + - MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); - sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } else { - String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed); - reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); - sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis())); - } - } - }); - } else { - sendSMS(new Sms(receivedSms.phoneNumber, MainApp.gs(R.string.smscommunicator_unknowncommand), System.currentTimeMillis())); - } - resetWaitingMessages(); + if (messageToConfirm != null && messageToConfirm.requester.phoneNumber.equals(receivedSms.phoneNumber)) { + messageToConfirm.action(splitted[0]); + messageToConfirm = null; + } else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_unknowncommand)); break; } } @@ -548,9 +261,491 @@ public class SmsCommunicatorPlugin extends PluginBase { MainApp.bus().post(new EventSmsCommunicatorUpdateGui()); } + @SuppressWarnings("unused") + private void processBG(String[] splitted, Sms receivedSms) { + BgReading actualBG = DatabaseHelper.actualBg(); + BgReading lastBG = DatabaseHelper.lastBg(); + + String reply = ""; + + String units = ProfileFunctions.getInstance().getProfileUnits(); + + if (actualBG != null) { + reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", "; + } else if (lastBG != null) { + Long agoMsec = System.currentTimeMillis() - lastBG.date; + int agoMin = (int) (agoMsec / 60d / 1000d); + reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", "; + } + GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); + if (glucoseStatus != null) + reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", "; + + TreatmentsPlugin.getPlugin().updateTotalIOBTreatments(); + IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round(); + TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals(); + IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round(); + + String cobText = MainApp.gs(R.string.value_unavailable_short); + CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB"); + + reply += MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" + + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " + + MainApp.gs(R.string.cob) + ": " + cobInfo.generateCOBString(); + + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + receivedSms.processed = true; + } + + private void processLOOP(String[] splitted, Sms receivedSms) { + String reply; + switch (splitted[1].toUpperCase()) { + case "DISABLE": + case "STOP": + LoopPlugin loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); + if (loopPlugin != null && loopPlugin.isEnabled(PluginType.LOOP)) { + loopPlugin.setPluginEnabled(PluginType.LOOP, false); + ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { + @Override + public void run() { + MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP")); + String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " + + MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + }); + } else { + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisdisabled)); + } + receivedSms.processed = true; + break; + case "ENABLE": + case "START": + loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); + if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) { + loopPlugin.setPluginEnabled(PluginType.LOOP, true); + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loophasbeenenabled)); + MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START")); + } else { + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisenabled)); + } + receivedSms.processed = true; + break; + case "STATUS": + loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); + if (loopPlugin != null) { + if (loopPlugin.isEnabled(PluginType.LOOP)) { + if (loopPlugin.isSuspended()) + reply = String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()); + else + reply = MainApp.gs(R.string.smscommunicator_loopisenabled); + } else { + reply = MainApp.gs(R.string.smscommunicator_loopisdisabled); + } + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + receivedSms.processed = true; + break; + case "RESUME": + LoopPlugin.getPlugin().suspendTo(0); + MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME")); + NSUpload.uploadOpenAPSOffline(0); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopresumed)); + break; + case "SUSPEND": + int duration = 0; + if (splitted.length == 3) + duration = SafeParse.stringToInt(splitted[2]); + duration = Math.max(0, duration); + duration = Math.min(180, duration); + if (duration == 0) { + receivedSms.processed = true; + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_wrongduration)); + return; + } else { + String passCode = generatePasscode(); + reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(duration) { + @Override + public void run() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { + @Override + public void run() { + if (result.success) { + LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + anInteger * 60L * 1000); + NSUpload.uploadOpenAPSOffline(anInteger * 60); + MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED")); + String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " + + MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + + } + }); + } + break; + default: + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + break; + } + } + + private void processTREATMENTS(String[] splitted, Sms receivedSms) { + if (splitted[1].toUpperCase().equals("REFRESH")) { + Intent restartNSClient = new Intent(Intents.ACTION_RESTART); + TreatmentsPlugin.getPlugin().getService().resetTreatments(); + MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); + List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); + String reply = "TREATMENTS REFRESH " + q.size() + " receivers"; + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + receivedSms.processed = true; + } else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + } + + private void processNSCLIENT(String[] splitted, Sms receivedSms) { + if (splitted[1].toUpperCase().equals("RESTART")) { + Intent restartNSClient = new Intent(Intents.ACTION_RESTART); + MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); + List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); + String reply = "NSCLIENT RESTART " + q.size() + " receivers"; + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + receivedSms.processed = true; + } else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + } + + @SuppressWarnings("unused") + private void processPUMP(String[] splitted, Sms receivedSms) { + ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() { + @Override + public void run() { + PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + if (result.success) { + if (pump != null) { + String reply = pump.shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } else { + String reply = MainApp.gs(R.string.readstatusfailed); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + receivedSms.processed = true; + } + + private void processPROFILE(String[] splitted, Sms receivedSms) { + // load profiles + ProfileInterface anInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); + if (anInterface == null) { + sendSMS(new Sms(receivedSms.phoneNumber, R.string.notconfigured)); + receivedSms.processed = true; + return; + } + ProfileStore store = anInterface.getProfile(); + if (store == null) { + sendSMS(new Sms(receivedSms.phoneNumber, R.string.notconfigured)); + receivedSms.processed = true; + return; + } + final ArrayList list = store.getProfileList(); + + if (splitted[1].toUpperCase().equals("STATUS")) { + sendSMS(new Sms(receivedSms.phoneNumber, ProfileFunctions.getInstance().getProfileName())); + } else if (splitted[1].toUpperCase().equals("LIST")) { + if (list.isEmpty()) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.invalidprofile)); + else { + String reply = ""; + for (int i = 0; i < list.size(); i++) { + if (i > 0) + reply += "\n"; + reply += (i + 1) + ". "; + reply += list.get(i); + } + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } else { + + int pindex = SafeParse.stringToInt(splitted[1]); + int percentage = 100; + if (splitted.length > 2) + percentage = SafeParse.stringToInt(splitted[2]); + + if (pindex > list.size()) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else if (percentage == 0) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else if (pindex == 0) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else { + final Profile profile = store.getSpecificProfile((String) list.get(pindex - 1)); + if (profile == null) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.noprofile)); + else { + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_profilereplywithcode), list.get(pindex - 1), percentage, passCode); + receivedSms.processed = true; + int finalPercentage = percentage; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction((String) list.get(pindex - 1), finalPercentage) { + @Override + public void run() { + ProfileFunctions.doProfileSwitch(store, (String) list.get(pindex - 1), 0, finalPercentage, 0); + sendSMS(new Sms(receivedSms.phoneNumber, R.string.profileswitchcreated)); + } + }); + } + } + } + receivedSms.processed = true; + } + + private void processBASAL(String[] splitted, Sms receivedSms) { + if (splitted[1].toUpperCase().equals("CANCEL") || splitted[1].toUpperCase().equals("STOP")) { + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction() { + @Override + public void run() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { + @Override + public void run() { + if (result.success) { + String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + } + }); + } else if (splitted[1].endsWith("%")) { + int tempBasalPct = SafeParse.stringToInt(StringUtils.removeEnd(splitted[1], "%")); + int duration = 30; + if (splitted.length > 2) + duration = SafeParse.stringToInt(splitted[2]); + final Profile profile = ProfileFunctions.getInstance().getProfile(); + + if (profile == null) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.noprofile)); + else if (tempBasalPct == 0 && !splitted[1].equals("0%")) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else if (duration == 0) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else { + tempBasalPct = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(tempBasalPct), profile).value(); + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(tempBasalPct, duration) { + @Override + public void run() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(anInteger, secondInteger, true, profile, new Callback() { + @Override + public void run() { + if (result.success) { + String reply; + if (result.isPercent) + reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration); + else + reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + } + }); + } + } else { + Double tempBasal = SafeParse.stringToDouble(splitted[1]); + int duration = 30; + if (splitted.length > 2) + duration = SafeParse.stringToInt(splitted[2]); + final Profile profile = ProfileFunctions.getInstance().getProfile(); + if (profile == null) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.noprofile)); + else if (tempBasal == 0 && !splitted[1].equals("0")) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else if (duration == 0) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else { + tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value(); + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(tempBasal, duration) { + @Override + public void run() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(aDouble, secondInteger, true, profile, new Callback() { + @Override + public void run() { + if (result.success) { + String reply; + if (result.isPercent) + reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration); + else + reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + } + }); + } + } + } + + private void processEXTENDED(String[] splitted, Sms receivedSms) { + if (splitted[1].toUpperCase().equals("CANCEL") || splitted[1].toUpperCase().equals("STOP")) { + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction() { + @Override + public void run() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(new Callback() { + @Override + public void run() { + if (result.success) { + String reply = MainApp.gs(R.string.smscommunicator_extendedcanceled); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_extendedcancelfailed); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + } + }); + } else if (splitted.length != 3) { + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + } else { + Double extended = SafeParse.stringToDouble(splitted[1]); + int duration = SafeParse.stringToInt(splitted[2]); + extended = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(extended)).value(); + if (extended == 0 || duration == 0) + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + else { + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(extended, duration) { + @Override + public void run() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().extendedBolus(aDouble, secondInteger, new Callback() { + @Override + public void run() { + if (result.success) { + String reply = String.format(MainApp.gs(R.string.smscommunicator_extendedset), aDouble, duration); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_extendedfailed); + reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + } + }); + } + } + } + + + private void processBOLUS(String[] splitted, Sms receivedSms) { + Double bolus = SafeParse.stringToDouble(splitted[1]); + bolus = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(bolus)).value(); + if (bolus > 0d) { + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(bolus) { + @Override + public void run() { + DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); + detailedBolusInfo.insulin = aDouble; + detailedBolusInfo.source = Source.USER; + ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() { + @Override + public void run() { + final boolean resultSuccess = result.success; + final double resultBolusDelivered = result.bolusDelivered; + ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() { + @Override + public void run() { + PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + if (resultSuccess) { + String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered); + if (pump != null) + reply += "\n" + pump.shortStatus(true); + lastRemoteBolusTime = DateUtil.now(); + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); + } else { + String reply = MainApp.gs(R.string.smscommunicator_bolusfailed); + if (pump != null) + reply += "\n" + pump.shortStatus(true); + sendSMS(new Sms(receivedSms.phoneNumber, reply)); + } + } + }); + } + }); + } + }); + } else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + } + + private void processCAL(String[] splitted, Sms receivedSms) { + Double cal = SafeParse.stringToDouble(splitted[1]); + if (cal > 0d) { + String passCode = generatePasscode(); + String reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode); + receivedSms.processed = true; + messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction() { + @Override + public void run() { + boolean result = XdripCalibrations.sendIntent(aDouble); + if (result) + sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_calibrationsent)); + else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_calibrationfailed)); + } + }); + } else + sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat)); + } + public void sendNotificationToAllNumbers(String text) { for (int i = 0; i < allowedNumbers.size(); i++) { - Sms sms = new Sms(allowedNumbers.get(i), text, System.currentTimeMillis()); + Sms sms = new Sms(allowedNumbers.get(i), text); sendSMS(sms); } } @@ -562,12 +757,13 @@ public class SmsCommunicatorPlugin extends PluginBase { } } - private void sendSMS(Sms sms) { + void sendSMS(Sms sms) { SmsManager smsManager = SmsManager.getDefault(); sms.text = stripAccents(sms.text); if (sms.text.length() > 140) sms.text = sms.text.substring(0, 139); try { - log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text); + if (L.isEnabled(L.SMS)) + log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text); smsManager.sendTextMessage(sms.phoneNumber, null, sms.text, null, null); messages.add(sms); } catch (IllegalArgumentException e) { @@ -577,6 +773,7 @@ public class SmsCommunicatorPlugin extends PluginBase { Notification notification = new Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); } + MainApp.bus().post(new EventSmsCommunicatorUpdateGui()); } private String generatePasscode() { @@ -586,17 +783,10 @@ public class SmsCommunicatorPlugin extends PluginBase { passCode += Character.toString((char) (startChar2 + Math.random() * ('z' - 'a' + 1))); int startChar3 = Math.random() > 0.5 ? 'a' : 'A'; passCode += Character.toString((char) (startChar3 + Math.random() * ('z' - 'a' + 1))); + passCode.replace('l', 'k').replace('I', 'J'); return passCode; } - private void resetWaitingMessages() { - tempBasalWaitingForConfirmation = null; - cancelTempBasalWaitingForConfirmation = null; - bolusWaitingForConfirmation = null; - calibrationWaitingForConfirmation = null; - suspendWaitingForConfirmation = null; - } - private static String stripAccents(String s) { s = Normalizer.normalize(s, Normalizer.Form.NFD); s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", ""); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java index aef742b49b..b92410d67f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java @@ -693,7 +693,7 @@ public class ActionStringHandler { //send profile to pumpe new NewNSTreatmentDialog(); //init - NewNSTreatmentDialog.doProfileSwitch(0, percentage, timeshift); + ProfileFunctions.doProfileSwitch(0, percentage, timeshift); } private static void generateTempTarget(int duration, double low, double high) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java index a401edbfa3..df5f2a5ed5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java @@ -10,7 +10,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventBolusRequested; import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshOverview; @@ -24,6 +23,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.utils.SP; /** @@ -157,7 +157,7 @@ public class WearPlugin extends PluginBase { @Subscribe - public void onStatusEvent(final EventNewBG ev) { + public void onStatusEvent(final EventAutosensCalculationFinished ev) { sendDataToWatch(true, true, true); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java index e94aa286e5..aa6498563d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.general.wear.wearintegration; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; - import android.os.AsyncTask; import android.util.Log; @@ -15,11 +12,13 @@ import com.google.android.gms.wearable.PutDataMapRequest; import com.google.android.gms.wearable.PutDataRequest; import com.google.android.gms.wearable.Wearable; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + /** * Created by emmablack on 12/26/14. */ -class SendToDataLayerThread extends AsyncTask { - +class SendToDataLayerThread extends AsyncTask { private GoogleApiClient googleApiClient; private static final String TAG = "SendToDataLayerThread"; private String path; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index 42ab57eedd..52dbeed75c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -32,6 +32,12 @@ import com.google.android.gms.wearable.PutDataRequest; import com.google.android.gms.wearable.Wearable; import com.google.android.gms.wearable.WearableListenerService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -42,6 +48,9 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; +import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; @@ -49,6 +58,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; @@ -61,23 +71,16 @@ import info.nightscout.androidaps.utils.ToastUtils; public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { - private static final Logger log = LoggerFactory.getLogger(WatchUpdaterService.class); - private static final String TAG = "WatchUpdaterService"; - - // ACTIONS public static final String ACTION_RESEND = WatchUpdaterService.class.getName().concat(".Resend"); public static final String ACTION_OPEN_SETTINGS = WatchUpdaterService.class.getName().concat(".OpenSettings"); public static final String ACTION_SEND_STATUS = WatchUpdaterService.class.getName().concat(".SendStatus"); public static final String ACTION_SEND_BASALS = WatchUpdaterService.class.getName().concat(".SendBasals"); public static final String ACTION_SEND_BOLUSPROGRESS = WatchUpdaterService.class.getName().concat(".BolusProgress"); - public static final String ACTION_SEND_ACTIONCONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat( - ".ActionConfirmationRequest"); - public static final String ACTION_SEND_CHANGECONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat( - ".ChangeConfirmationRequest"); - public static final String ACTION_CANCEL_NOTIFICATION = WatchUpdaterService.class.getName().concat( - ".CancelNotification"); + public static final String ACTION_SEND_ACTIONCONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat(".ActionConfirmationRequest"); + public static final String ACTION_SEND_CHANGECONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat(".ChangeConfirmationRequest"); + public static final String ACTION_CANCEL_NOTIFICATION = WatchUpdaterService.class.getName().concat(".CancelNotification"); - // PATHS + private GoogleApiClient googleApiClient; public static final String WEARABLE_DATA_PATH = "/nightscout_watch_data"; public static final String WEARABLE_RESEND_PATH = "/nightscout_watch_data_resend"; private static final String WEARABLE_CANCELBOLUS_PATH = "/nightscout_watch_cancel_bolus"; @@ -92,20 +95,22 @@ public class WatchUpdaterService extends WearableListenerService implements Goog public static final String ACTION_CONFIRMATION_REQUEST_PATH = "/nightscout_watch_actionconfirmationrequest"; public static final String ACTION_CHANGECONFIRMATION_REQUEST_PATH = "/nightscout_watch_changeconfirmationrequest"; public static final String ACTION_CANCELNOTIFICATION_REQUEST_PATH = "/nightscout_watch_cancelnotificationrequest"; - // Phone - Capabilites - private static final String CAPABILITY_PHONE_APP = "phone_app_sync_bgs"; - private static final String MESSAGE_PATH_PHONE = "/phone_message_path"; - // Wear - Capabilites - private static final String CAPABILITY_WEAR_APP = "wear_app_sync_bgs"; - private static final String MESSAGE_PATH_WEAR = "/wear_message_path"; - private GoogleApiClient googleApiClient; + boolean wear_integration = false; SharedPreferences mPrefs; private static boolean lastLoopStatus; + private static Logger log = LoggerFactory.getLogger(WatchUpdaterService.class); + private Handler handler; + // Phone + private static final String CAPABILITY_PHONE_APP = "phone_app_sync_bgs"; + private static final String MESSAGE_PATH_PHONE = "/phone_message_path"; + // Wear + private static final String CAPABILITY_WEAR_APP = "wear_app_sync_bgs"; + private static final String MESSAGE_PATH_WEAR = "/wear_message_path"; private String mWearNodeId = null; private String localnode = null; private String logPrefix = ""; // "WR: " @@ -126,12 +131,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - public void listenForChangeInSettings() { WearPlugin.registerWatchUpdaterService(this); } - public void setSettings() { wear_integration = WearPlugin.getPlugin().isEnabled(PluginType.GENERAL); // Log.d(TAG, "WR: wear_integration=" + wear_integration); @@ -149,14 +152,13 @@ public class WatchUpdaterService extends WearableListenerService implements Goog .addOnConnectionFailedListener(this).addApi(Wearable.API).build(); Wearable.MessageApi.addListener(googleApiClient, this); if (googleApiClient.isConnected()) { - Log.d(TAG, logPrefix + "API client is connected"); + log.debug(logPrefix + "API client is connected"); } else { // Log.d("WatchUpdater", logPrefix + "API client is not connected and is trying to connect"); googleApiClient.connect(); } } - @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : null; @@ -175,8 +177,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } else if (ACTION_SEND_BASALS.equals(action)) { sendBasals(); } else if (ACTION_SEND_BOLUSPROGRESS.equals(action)) { - sendBolusProgress(intent.getIntExtra("progresspercent", 0), - intent.hasExtra("progressstatus") ? intent.getStringExtra("progressstatus") : ""); + sendBolusProgress(intent.getIntExtra("progresspercent", 0), intent.hasExtra("progressstatus") ? intent.getStringExtra("progressstatus") : ""); } else if (ACTION_SEND_ACTIONCONFIRMATIONREQUEST.equals(action)) { String title = intent.getStringExtra("title"); String message = intent.getStringExtra("message"); @@ -283,12 +284,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void cancelBolus() { ConfigBuilderPlugin.getPlugin().getActivePump().stopBolusDelivering(); } - private void sendData() { BgReading lastBG = DatabaseHelper.lastBg(); @@ -351,10 +350,8 @@ public class WatchUpdaterService extends WearableListenerService implements Goog dataMap.putString("avgDelta", "--"); } else { dataMap.putString("slopeArrow", slopeArrow(glucoseStatus.delta)); - dataMap.putString("delta", - deltastring(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)); - dataMap.putString("avgDelta", - deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units)); + dataMap.putString("delta", deltastring(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)); + dataMap.putString("avgDelta", deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units)); } dataMap.putLong("sgvLevel", sgvLevel); dataMap.putDouble("sgvDouble", lastBG.value); @@ -363,7 +360,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return dataMap; } - private String deltastring(double deltaMGDL, double deltaMMOL, String units) { String deltastring = ""; if (deltaMGDL >= 0) { @@ -389,7 +385,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return deltastring; } - private String slopeArrow(double delta) { if (delta <= (-3.5 * 5)) { return "\u21ca"; @@ -413,11 +408,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { googleApiConnect(); } - long startTime = System.currentTimeMillis() - (long)(60000 * 60 * 5.5); + long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5); BgReading last_bg = DatabaseHelper.lastBg(); - if (last_bg == null) - return; + if (last_bg == null) return; List graph_bgs = MainApp.getDbHelper().getBgreadingsDataFromTime(startTime, true); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(true); @@ -437,28 +431,27 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } entries.putDataMapArrayList("entries", dataMaps); executeTask(new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient), entries); - - // Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); } - sendPreferences(); // DMR + sendPreferences(); sendBasals(); - sendStatus(); // DMR + sendStatus(); } - private void sendBasals() { if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { googleApiConnect(); } long now = System.currentTimeMillis(); - final long startTimeWindow = now - (long)(60000 * 60 * 5.5); + final long startTimeWindow = now - (long) (60000 * 60 * 5.5); + ArrayList basals = new ArrayList<>(); ArrayList temps = new ArrayList<>(); ArrayList boluses = new ArrayList<>(); ArrayList predictions = new ArrayList<>(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { @@ -486,32 +479,33 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } + for (; runningTime < now; runningTime += 5 * 60 * 1000) { Profile profileTB = ProfileFunctions.getInstance().getProfile(runningTime); - // basal rate + //basal rate endBasalValue = profile.getBasal(runningTime); if (endBasalValue != beginBasalValue) { - // push the segment we recently left + //push the segment we recently left basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue)); - // begin new Basal segment + //begin new Basal segment beginBasalSegmentTime = runningTime; beginBasalValue = endBasalValue; } - // temps + //temps tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(runningTime); if (tb1 == null && tb2 == null) { - // no temp stays no temp + //no temp stays no temp } else if (tb1 != null && tb2 == null) { - // temp is over -> push it + //temp is over -> push it temps.add(tempDatamap(tb_start, tb_before, runningTime, endBasalValue, tb_amount)); tb1 = null; } else if (tb1 == null && tb2 != null) { - // temp begins + //temp begins tb1 = tb2; tb_start = runningTime; tb_before = endBasalValue; @@ -529,16 +523,16 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } if (beginBasalSegmentTime != runningTime) { - // push the remaining segment + //push the remaining segment basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue)); } if (tb1 != null) { - tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); // use "now" to express current situation + tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); //use "now" to express current situation if (tb2 == null) { - // express the cancelled temp by painting it down one minute early + //express the cancelled temp by painting it down one minute early temps.add(tempDatamap(tb_start, tb_before, now - 1 * 60 * 1000, endBasalValue, tb_amount)); } else { - // express currently running temp by painting it a bit into the future + //express currently running temp by painting it a bit into the future Profile profileNow = ProfileFunctions.getInstance().getProfile(now); double currentAmount = tb2.tempBasalConvertedToAbsolute(now, profileNow); if (currentAmount != tb_amount) { @@ -549,39 +543,36 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } } else { - tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); // use "now" to express current situation + tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); //use "now" to express current situation if (tb2 != null) { - // onset at the end + //onset at the end Profile profileTB = ProfileFunctions.getInstance().getProfile(runningTime); double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime, profileTB); - temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, - currentAmount)); + temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)); } } List treatments = TreatmentsPlugin.getPlugin().getTreatmentsFromHistory(); for (Treatment treatment : treatments) { if (treatment.date > startTimeWindow) { - boluses.add(treatmentMap(treatment.date, treatment.insulin, treatment.carbs, treatment.isSMB, - treatment.isValid)); + boluses.add(treatmentMap(treatment.date, treatment.insulin, treatment.carbs, treatment.isSMB, treatment.isValid)); } } final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun; - if (SP.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.request.hasPredictions - && finalLastRun.constraintsProcessed != null) { + if (SP.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.request.hasPredictions && finalLastRun.constraintsProcessed != null) { List predArray = finalLastRun.constraintsProcessed.getPredictions(); if (!predArray.isEmpty()) { for (BgReading bg : predArray) { - if (bg.value < 40) - continue; + if (bg.value < 40) continue; predictions.add(predictionMap(bg.date, bg.value, bg.getPredectionColor())); } } } + DataMap dm = new DataMap(); dm.putDataMapArrayList("basals", basals); dm.putDataMapArrayList("temps", temps); @@ -591,7 +582,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog executeTask(new SendToDataLayerThread(BASAL_DATA_PATH, googleApiClient), dm); } - private DataMap tempDatamap(long startTime, double startBasal, long to, double toBasal, double amount) { DataMap dm = new DataMap(); dm.putLong("starttime", startTime); @@ -602,7 +592,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return dm; } - private DataMap basalMap(long startTime, long endTime, double amount) { DataMap dm = new DataMap(); dm.putLong("starttime", startTime); @@ -611,7 +600,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return dm; } - private DataMap treatmentMap(long date, double bolus, double carbs, boolean isSMB, boolean isValid) { DataMap dm = new DataMap(); dm.putLong("date", date); @@ -622,7 +610,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return dm; } - private DataMap predictionMap(long timestamp, double sgv, int color) { DataMap dm = new DataMap(); dm.putLong("timestamp", timestamp); @@ -635,7 +622,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog private void sendNotification() { if (googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(OPEN_SETTINGS_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); dataMapRequest.getDataMap().putString("openSettings", "openSettings"); PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); @@ -646,11 +633,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void sendBolusProgress(int progresspercent, String status) { if (googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(BOLUS_PROGRESS_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); dataMapRequest.getDataMap().putString("bolusProgress", "bolusProgress"); dataMapRequest.getDataMap().putString("progressstatus", status); @@ -663,11 +649,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void sendActionConfirmationRequest(String title, String message, String actionstring) { if (googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CONFIRMATION_REQUEST_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); dataMapRequest.getDataMap().putString("actionConfirmationRequest", "actionConfirmationRequest"); dataMapRequest.getDataMap().putString("title", title); @@ -684,11 +669,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void sendChangeConfirmationRequest(String title, String message, String actionstring) { if (googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CHANGECONFIRMATION_REQUEST_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); dataMapRequest.getDataMap().putString("changeConfirmationRequest", "changeConfirmationRequest"); dataMapRequest.getDataMap().putString("title", title); @@ -705,11 +689,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void sendCancelNotificationRequest(String actionstring) { if (googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CANCELNOTIFICATION_REQUEST_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); dataMapRequest.getDataMap().putString("cancelNotificationRequest", "cancelNotificationRequest"); dataMapRequest.getDataMap().putString("actionstring", actionstring); @@ -724,7 +707,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void sendStatus() { if (googleApiClient.isConnected()) { @@ -740,13 +722,12 @@ public class WatchUpdaterService extends WearableListenerService implements Goog IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round(); iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob); - iobDetail = "(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" - + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")"; - cobString = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "WatcherUpdaterService") - .generateCOBString(); + iobDetail = "(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")"; + cobString = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "WatcherUpdaterService").generateCOBString(); currentBasal = generateBasalString(treatmentsInterface); - // bgi + //bgi + double bgi = -(bolusIob.activity + basalIob.activity) * 5 * profile.getIsf(); bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to1Decimal(bgi); @@ -754,23 +735,24 @@ public class WatchUpdaterService extends WearableListenerService implements Goog status = generateStatusString(profile, currentBasal, iobSum, iobDetail, bgiString); } - // batteries + + //batteries int phoneBattery = getBatteryLevel(getApplicationContext()); String rigBattery = NSDeviceStatus.getInstance().getUploaderStatus().trim(); + long openApsStatus = -1; - // OpenAPS status + //OpenAPS status if (Config.APS) { - // we are AndroidAPS - openApsStatus = LoopPlugin.lastRun != null && LoopPlugin.lastRun.lastEnact != null - && LoopPlugin.lastRun.lastEnact.getTime() != 0 ? LoopPlugin.lastRun.lastEnact.getTime() : -1; + //we are AndroidAPS + openApsStatus = LoopPlugin.lastRun != null && LoopPlugin.lastRun.lastEnact != null && LoopPlugin.lastRun.lastEnact.getTime() != 0 ? LoopPlugin.lastRun.lastEnact.getTime() : -1; } else { - // NSClient or remote + //NSClient or remote openApsStatus = NSDeviceStatus.getOpenApsTimestamp(); } PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_STATUS_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putString("externalStatusString", status); dataMapRequest.getDataMap().putString("iobSum", iobSum); dataMapRequest.getDataMap().putString("iobDetail", iobDetail); @@ -791,14 +773,13 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - private void sendPreferences() { if (googleApiClient.isConnected()) { boolean wearcontrol = SP.getBoolean("wearcontrol", false); PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_PREFERENCES_PATH); - // unique content + //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); dataMapRequest.getDataMap().putBoolean("wearcontrol", wearcontrol); PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); @@ -826,8 +807,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog @NonNull - private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, - String bgiString) { + private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, String bgiString) { String status = ""; @@ -854,7 +834,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog status += currentBasal + " " + iobString; - // add BGI if shown, otherwise return + //add BGI if shown, otherwise return if (mPrefs.getBoolean("wear_showbgi", false)) { status += " " + bgiString; } @@ -862,7 +842,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return status; } - @NonNull private String generateBasalString(TreatmentsInterface treatmentsInterface) { @@ -885,7 +864,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return basalStringResult; } - @Override public void onDestroy() { if (googleApiClient != null && googleApiClient.isConnected()) { @@ -894,22 +872,18 @@ public class WatchUpdaterService extends WearableListenerService implements Goog WearPlugin.unRegisterWatchUpdaterService(); } - @Override public void onConnectionSuspended(int cause) { } - @Override public void onConnectionFailed(ConnectionResult connectionResult) { } - public static boolean shouldReportLoopStatus(boolean enabled) { return (lastLoopStatus != enabled); } - public static int getBatteryLevel(Context context) { Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (batteryIntent != null) { @@ -918,7 +892,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog if (level == -1 || scale == -1) { return 50; } - return (int)(((float)level / (float)scale) * 100.0f); + return (int) (((float) level / (float) scale) * 100.0f); } return 50; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index d0794bf4d5..fe89cc8304 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -17,7 +17,6 @@ import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.events.EventTempBasalChange; @@ -26,10 +25,11 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -115,7 +115,7 @@ public class StatuslinePlugin extends PluginBase { if (ConfigBuilderPlugin.getPlugin().getActivePump() == null) return ""; - + LoopPlugin loopPlugin = LoopPlugin.getPlugin(); if (!loopPlugin.isEnabled(PluginType.LOOP)) { @@ -138,7 +138,7 @@ public class StatuslinePlugin extends PluginBase { IobTotal bolusIob = treatmentsInterface.getLastCalculationTreatments().round(); treatmentsInterface.updateTotalIOBTempBasals(); IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round(); - status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob)+"U"; + status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U"; if (mPrefs.getBoolean("xdripstatus_detailediob", true)) { @@ -182,7 +182,7 @@ public class StatuslinePlugin extends PluginBase { } @Subscribe - public void onStatusEvent(final EventNewBG ev) { + public void onStatusEvent(final EventAutosensCalculationFinished ev) { sendStatus(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index d08485dd1a..aac0985fba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -65,8 +65,6 @@ public class IobCobCalculatorPlugin extends PluginBase { private volatile List bgReadings = null; // newest at index 0 private volatile List bucketed_data = null; - private double dia = Constants.defaultDIA; - final Object dataLock = new Object(); boolean stopCalculationTrigger = false; @@ -118,11 +116,22 @@ public class IobCobCalculatorPlugin extends PluginBase { return rounded; } - void loadBgData(long now) { - long start = (long) (now - 60 * 60 * 1000L * (24 + dia)); - bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false); - if (L.isEnabled(L.AUTOSENS)) - log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now)); + void loadBgData(long to) { + Profile profile = ProfileFunctions.getInstance().getProfile(to); + double dia = Constants.defaultDIA; + 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) + // 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)); + } 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)); + } } public boolean isAbout5minData() { @@ -608,10 +617,6 @@ public class IobCobCalculatorPlugin extends PluginBase { } if (ConfigBuilderPlugin.getPlugin() == null) return; // app still initializing - Profile profile = ProfileFunctions.getInstance().getProfile(); - if (profile == null) - return; // app still initializing - dia = profile.getDia(); if (ev == null) { // on init no need of reset return; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java index 2a5f76c686..e27f27c26f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java @@ -41,6 +41,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.MidnightTime; import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.T; import static info.nightscout.androidaps.utils.DateUtil.now; import static java.util.Calendar.MINUTE; @@ -61,7 +62,7 @@ public class IobCobOref1Thread extends Thread { private PowerManager.WakeLock mWakeLock; - public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); this.iobCobCalculatorPlugin = plugin; @@ -72,13 +73,15 @@ public class IobCobOref1Thread extends Thread { this.end = end; PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); - mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); + if (powerManager != null) + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainApp.gs(R.string.app_name) + ":iobCobThread"); } @Override public final void run() { long start = DateUtil.now(); - mWakeLock.acquire(); + if (mWakeLock != null) + mWakeLock.acquire(T.mins(10).msecs()); try { if (L.isEnabled(L.AUTOSENS)) log.debug("AUTOSENSDATA thread started: " + from); @@ -173,7 +176,7 @@ public class IobCobOref1Thread extends Thread { double bgi = -iob.activity * sens * 5; double deviation = delta - bgi; - double avgDeviation = Math.round((avgDelta - bgi) * 1000) / 1000; + double avgDeviation = Math.round((avgDelta - bgi) * 1000) / 1000d; double slopeFromMaxDeviation = 0; double slopeFromMinDeviation = 999; @@ -394,7 +397,8 @@ public class IobCobOref1Thread extends Thread { MainApp.bus().post(new EventAutosensCalculationFinished(cause)); }).start(); } finally { - mWakeLock.release(); + if (mWakeLock != null) + mWakeLock.release(); MainApp.bus().post(new EventIobCalculationProgress("")); if (L.isEnabled(L.AUTOSENS)) { log.debug("AUTOSENSDATA thread ended: " + from); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java index 89bc0a6606..2970f07aca 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java @@ -41,6 +41,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.MidnightTime; import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.T; import static info.nightscout.androidaps.utils.DateUtil.now; @@ -60,7 +61,7 @@ public class IobCobThread extends Thread { private PowerManager.WakeLock mWakeLock; - public IobCobThread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + IobCobThread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); this.iobCobCalculatorPlugin = plugin; @@ -71,13 +72,15 @@ public class IobCobThread extends Thread { this.end = end; PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); - mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); + if (powerManager != null) + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainApp.gs(R.string.app_name) + ":iobCobThread"); } @Override public final void run() { long start = DateUtil.now(); - mWakeLock.acquire(); + if (mWakeLock != null) + mWakeLock.acquire(T.mins(10).msecs()); try { if (L.isEnabled(L.AUTOSENS)) log.debug("AUTOSENSDATA thread started: " + from); @@ -172,7 +175,7 @@ public class IobCobThread extends Thread { double bgi = -iob.activity * sens * 5; double deviation = delta - bgi; - double avgDeviation = Math.round((avgDelta - bgi) * 1000) / 1000; + double avgDeviation = Math.round((avgDelta - bgi) * 1000) / 1000d; double slopeFromMaxDeviation = 0; double slopeFromMinDeviation = 999; @@ -321,7 +324,8 @@ public class IobCobThread extends Thread { MainApp.bus().post(new EventAutosensCalculationFinished(cause)); }).start(); } finally { - mWakeLock.release(); + if (mWakeLock != null) + mWakeLock.release(); MainApp.bus().post(new EventIobCalculationProgress("")); if (L.isEnabled(L.AUTOSENS)) { log.debug("AUTOSENSDATA thread ended: " + from); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.java index 913f6a1d12..66b895839d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.java @@ -22,7 +22,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI; @@ -157,7 +156,7 @@ public class NSProfileFragment extends SubscriberFragment { Profile profile = store.getSpecificProfile(name); if (profile != null) { OKDialog.showConfirmation(getActivity(), MainApp.gs(R.string.activate_profile) + ": " + name + " ?", () -> - NewNSTreatmentDialog.doProfileSwitch(store, name, 0, 100, 0) + ProfileFunctions.doProfileSwitch(store, name, 0, 100, 0) ); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index fd53f3d8be..557ba42168 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -1,5 +1,16 @@ package info.nightscout.androidaps.plugins.pump.combo; +import android.content.DialogInterface; +import android.os.SystemClock; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.FragmentActivity; +import android.support.v7.app.AlertDialog; + +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; @@ -8,17 +19,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import android.content.DialogInterface; -import android.os.SystemClock; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.app.FragmentActivity; -import android.support.v7.app.AlertDialog; - import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -66,19 +66,16 @@ 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.SP; - /** * Created by mike on 05.08.2016. */ public class ComboPlugin extends PluginBase implements PumpInterface, ConstraintsInterface { - private static final Logger log = LoggerFactory.getLogger(L.PUMP); static final String COMBO_TBRS_SET = "combo_tbrs_set"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; private static ComboPlugin plugin = null; - public static ComboPlugin getPlugin() { if (plugin == null) plugin = new ComboPlugin(); @@ -98,8 +95,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ private volatile boolean scripterIsBolusing; /** - * This is set to true to request a bolus cancellation. {@link #deliverBolus(DetailedBolusInfo)} will reset this - * flag. + * This is set to true to request a bolus cancellation. {@link #deliverBolus(DetailedBolusInfo)} + * will reset this flag. */ private volatile boolean cancelBolus; @@ -108,7 +105,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint * indicates if new history records on the pump have been found. This effectively blocks * high temps ({@link #setTempBasalPercent(Integer, Integer)} and boluses * ({@link #deliverBolus(DetailedBolusInfo)} till the queue is empty and the connection - * is shut down. {@link #initializePump()} resets this since on startup the history is allowed to have + * is shut down. + * {@link #initializePump()} resets this since on startup the history is allowed to have * changed (and the user can't possible have already calculated anything with out of date IOB). * The next reconnect will then reset this flag. This might cause some grief when attempting * to bolus again within the 5s of idling it takes before the connecting is shut down. Or if @@ -121,34 +119,36 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint /** * Cache of the last <=2 boluses on the pump. Used to detect changes in pump history, * requiring reading more pump history. This is read/set in {@link #checkHistory()} when changed - * pump history was detected and was read, as well as in {@link #deliverBolus(DetailedBolusInfo)} after bolus - * delivery. Newest record is the first one. + * pump history was detected and was read, as well as in {@link #deliverBolus(DetailedBolusInfo)} + * after bolus delivery. Newest record is the first one. */ private volatile List recentBoluses = new ArrayList<>(0); - private static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_pump_unsupported_operation)); - + private static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult() + .success(false).enacted(false).comment(MainApp.gs(R.string.combo_pump_unsupported_operation)); private ComboPlugin() { - super(new PluginDescription().mainType(PluginType.PUMP).fragmentClass(ComboFragment.class.getName()) - .pluginName(R.string.combopump).shortName(R.string.combopump_shortname) - .description(R.string.description_pump_combo)); + super(new PluginDescription() + .mainType(PluginType.PUMP) + .fragmentClass(ComboFragment.class.getName()) + .pluginName(R.string.combopump) + .shortName(R.string.combopump_shortname) + .description(R.string.description_pump_combo) + ); ruffyScripter = new RuffyScripter(MainApp.instance().getApplicationContext()); pumpDescription.setPumpDescription(PumpType.AccuChekCombo); } - public ComboPump getPump() { return pump; } - String getStateSummary() { PumpState ps = pump.state; if (ps.activeAlert != null) { - return ps.activeAlert.errorCode != null ? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message - : "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message; + return ps.activeAlert.errorCode != null + ? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message + : "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message; } else if (ps.suspended && (ps.batteryState == PumpState.EMPTY || ps.insulinState == PumpState.EMPTY)) { return MainApp.gs(R.string.combo_pump_state_suspended_due_to_error); } else if (ps.suspended) { @@ -161,32 +161,29 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return MainApp.gs(R.string.combo_pump_state_running); } - @Override - public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, - FragmentActivity context) { + public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); if (allowHardwarePump || context == null) { pluginSwitcher.invoke(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(R.string.allow_hardware_pump_text) - .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int id) { - pluginSwitcher.invoke(); - SP.putBoolean("allow_hardware_pump", true); - if (L.isEnabled(L.PUMP)) - log.debug("First time HW pump allowed!"); - } - }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - - public void onClick(DialogInterface dialog, int id) { - pluginSwitcher.cancel(); - if (L.isEnabled(L.PUMP)) - log.debug("User does not allow switching to HW pump!"); - } - }); + .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + pluginSwitcher.invoke(); + SP.putBoolean("allow_hardware_pump", true); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); + } + }) + .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + pluginSwitcher.cancel(); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); + } + }); builder.create().show(); } } @@ -197,42 +194,35 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return pump.initialized; } - @Override public boolean isSuspended() { return pump.state.suspended; } - @Override public boolean isBusy() { return ruffyScripter.isPumpBusy(); } - @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) { // ruffyscripter establishes a connection as needed. @@ -245,7 +235,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // checks be called in ComboPlugin.connect(); ... and have that cause other issues } - @Override public void disconnect(String reason) { if (L.isEnabled(L.PUMP)) @@ -253,29 +242,25 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint ruffyScripter.disconnect(); } - @Override public void stopConnecting() { // we're not doing that } - @Override public synchronized PumpEnactResult setNewBasalProfile(Profile profile) { if (!isInitialized()) { // note that this should not happen anymore since the queue is present, which // issues a READSTATE when starting to issue commands which initializes the pump log.error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, - MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); + Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); - return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.pumpNotInitializedProfileNotSet)); + return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.pumpNotInitializedProfileNotSet)); } BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile); if (pump.basalProfile.equals(requestedBasalProfile)) { - // dismiss previously "FAILED" overview notifications + //dismiss previously "FAILED" overview notifications MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); return new PumpEnactResult().success(true).enacted(false); @@ -283,64 +268,56 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { - return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_force_disabled_notification)); + return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.combo_force_disabled_notification)); } CommandResult setResult = runCommand(MainApp.gs(R.string.combo_activity_setting_basal_profile), 2, - () -> ruffyScripter.setBasalProfile(requestedBasalProfile)); + () -> ruffyScripter.setBasalProfile(requestedBasalProfile)); if (!setResult.success) { - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, - MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); - return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.failedupdatebasalprofile)); + return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.failedupdatebasalprofile)); } pump.basalProfile = requestedBasalProfile; - // dismiss previously "FAILED" overview notifications + //dismiss previously "FAILED" overview notifications MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - // issue success notification - Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), - Notification.INFO, 60); + //issue success notification + 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 new PumpEnactResult().success(true).enacted(true); } - @Override public boolean isThisProfileSet(Profile profile) { if (!isInitialized()) { - /* - * This might be called too soon during boot. Return true to prevent a request - * to update the profile. KeepAlive is called every Constants.keepalivems - * and will detect the need for a profile update and apply it. - */ + /* This might be called too soon during boot. Return true to prevent a request + to update the profile. KeepAlive is called every Constants.keepalivems + and will detect the need for a profile update and apply it. + */ return true; } return pump.basalProfile.equals(convertProfileToComboProfile(profile)); } - @NonNull private BasalProfile convertProfileToComboProfile(Profile profile) { BasalProfile basalProfile = new BasalProfile(); for (int i = 0; i < 24; i++) { double rate = profile.getBasalTimeFromMidnight(i * 60 * 60); - /* - * The Combo pump does hava a different granularity for basal rate: + /*The Combo pump does hava a different granularity for basal rate: * 0.01 - if below 1U/h * 0.05 - if above 1U/h - */ + * */ if (rate < 1) { - // round to 0.01 granularity; + //round to 0.01 granularity; rate = Math.round(rate / 0.01) * 0.01; } else { - // round to 0.05 granularity; + //round to 0.05 granularity; rate = Math.round(rate / 0.05) * 0.05; } @@ -349,13 +326,11 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return basalProfile; } - @Override public long lastDataTime() { return pump.lastSuccessfulCmdTime; } - /** * Runs pump initialization if needed and reads the pump state from the main screen. */ @@ -371,7 +346,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } } - private synchronized void initializePump() { long maxWait = System.currentTimeMillis() + 15 * 1000; while (!ruffyScripter.isPumpAvailable()) { @@ -388,9 +362,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // trigger a connect, which will update state and check history CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); if (stateResult.invalidSetup) { - MainApp.bus().post( - new EventNewNotification(new Notification(Notification.COMBO_PUMP_ALARM, MainApp - .gs(R.string.combo_invalid_setup), Notification.URGENT))); + MainApp.bus().post(new EventNewNotification( + new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_invalid_setup), Notification.URGENT))); return; } if (!stateResult.success) { @@ -407,15 +380,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { Notification n = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_force_disabled_notification), Notification.URGENT); + MainApp.gs(R.string.combo_force_disabled_notification), + Notification.URGENT); n.soundId = R.raw.alarm; MainApp.bus().post(new EventNewNotification(n)); return; } // read basal profile into cache (KeepAlive will trigger a profile update if needed) - CommandResult readBasalResult = runCommand(MainApp.gs(R.string.combo_actvity_reading_basal_profile), 2, - ruffyScripter::readBasalProfile); + CommandResult readBasalResult = runCommand(MainApp.gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); if (!readBasalResult.success) { return; } @@ -431,8 +404,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint long lastBolusTimestamp = recentBoluses.get(0).timestamp; long now = System.currentTimeMillis(); if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_check_date), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_check_date), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } } @@ -442,7 +414,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint MainApp.bus().post(new EventComboPumpUpdateGUI()); } - /** * Updates local cache with state (reservoir level, last bolus ...) returned from the pump */ @@ -459,20 +430,17 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint MainApp.bus().post(new EventComboPumpUpdateGUI()); } - @Override public double getBaseBasalRate() { int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); return pump.basalProfile.hourlyRates[currentHour]; } - @Override public double getReservoirLevel() { return pump.reservoirLevel; } - @Override public int getBatteryLevel() { switch (pump.state.batteryState) { @@ -508,7 +476,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint MainApp.bus().post(event); }; - /** * Updates Treatment records with carbs and boluses and delivers a bolus if needed */ @@ -518,8 +485,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) { // neither carbs nor bolus requested log.error("deliverTreatment: Invalid input"); - return new PumpEnactResult().success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d) - .comment(MainApp.gs(R.string.danar_invalidinput)); + return new PumpEnactResult().success(false).enacted(false) + .bolusDelivered(0d).carbsDelivered(0d) + .comment(MainApp.gs(R.string.danar_invalidinput)); } else if (detailedBolusInfo.insulin > 0) { // bolus needed, ask pump to deliver it return deliverBolus(detailedBolusInfo); @@ -533,15 +501,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint bolusingEvent.percent = 100; MainApp.bus().post(bolusingEvent); - return new PumpEnactResult().success(true).enacted(true).bolusDelivered(0d) - .carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok)); + return new PumpEnactResult().success(true).enacted(true) + .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) + .comment(MainApp.gs(R.string.virtualpump_resultok)); } } finally { MainApp.bus().post(new EventComboPumpUpdateGUI()); } } - @NonNull private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) { try { @@ -552,29 +520,30 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1)); if (!stateResult.success) { return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); + .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); } if (stateResult.reservoirLevel != -1 && stateResult.reservoirLevel - 0.5 < detailedBolusInfo.insulin) { return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_reservoir_level_insufficient_for_bolus)); + .comment(MainApp.gs(R.string.combo_reservoir_level_insufficient_for_bolus)); } // the commands above ensured a connection was made, which updated this field if (pumpHistoryChanged) { return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_bolus_rejected_due_to_pump_history_change)); + .comment(MainApp.gs(R.string.combo_bolus_rejected_due_to_pump_history_change)); } - Bolus previousBolus = stateResult.history != null && !stateResult.history.bolusHistory.isEmpty() ? stateResult.history.bolusHistory - .get(0) : new Bolus(0, 0, false); + Bolus previousBolus = stateResult.history != null && !stateResult.history.bolusHistory.isEmpty() + ? stateResult.history.bolusHistory.get(0) + : new Bolus(0, 0, false); // reject a bolus if one with the exact same size was successfully delivered // within the last 1-2 minutes if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01 - && previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) { + && previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) { if (L.isEnabled(L.PUMP)) log.debug("Bolus request rejected, same bolus was successfully delivered very recently"); return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.bolus_frequency_exceeded)); + .comment(MainApp.gs(R.string.bolus_frequency_exceeded)); } // if the last bolus was given in the current minute, wait till the pump clock moves @@ -584,13 +553,13 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint long maxWaitTimeout = waitStartTime + 65 * 1000; int waitLoops = 0; while (previousBolus.timestamp == timeCheckResult.state.pumpTime - && maxWaitTimeout > System.currentTimeMillis()) { + && maxWaitTimeout > System.currentTimeMillis()) { if (cancelBolus) { return new PumpEnactResult().success(true).enacted(false); } if (!timeCheckResult.success) { return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); + .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); } if (L.isEnabled(L.PUMP)) log.debug("Waiting for pump clock to advance for the next unused bolus record timestamp"); @@ -614,7 +583,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // start bolus delivery scripterIsBolusing = true; - runCommand(null, 0, () -> ruffyScripter.deliverBolus(detailedBolusInfo.insulin, bolusProgressReporter)); + runCommand(null, 0, + () -> ruffyScripter.deliverBolus(detailedBolusInfo.insulin, bolusProgressReporter)); scripterIsBolusing = false; // Note that the result of the issued bolus command is not checked. If there was @@ -626,32 +596,33 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint CommandResult postBolusStateResult = runCommand(null, 3, () -> ruffyScripter.readQuickInfo(2)); if (!postBolusStateResult.success) { return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_error_bolus_verification_failed)); + .comment(MainApp.gs(R.string.combo_error_bolus_verification_failed)); } - Bolus lastPumpBolus = postBolusStateResult.history != null - && !postBolusStateResult.history.bolusHistory.isEmpty() ? postBolusStateResult.history.bolusHistory - .get(0) : null; + Bolus lastPumpBolus = postBolusStateResult.history != null && !postBolusStateResult.history.bolusHistory.isEmpty() + ? postBolusStateResult.history.bolusHistory.get(0) + : null; // no bolus delivered? if (lastPumpBolus == null || lastPumpBolus.equals(previousBolus)) { if (cancelBolus) { return new PumpEnactResult().success(true).enacted(false); } else { - return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_error_no_bolus_delivered)); + return new PumpEnactResult() + .success(false) + .enacted(false) + .comment(MainApp.gs(R.string.combo_error_no_bolus_delivered)); } } // at least some insulin delivered, so add it to treatments if (!addBolusToTreatments(detailedBolusInfo, lastPumpBolus)) return new PumpEnactResult().success(false).enacted(true) - .comment(MainApp.gs(R.string.combo_error_updating_treatment_record)); + .comment(MainApp.gs(R.string.combo_error_updating_treatment_record)); // check pump bolus record has a sane timestamp long now = System.currentTimeMillis(); if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_suspious_bolus_time), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_suspious_bolus_time), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } @@ -664,18 +635,18 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (cancelBolus) { return new PumpEnactResult().success(true).enacted(true); } - return new PumpEnactResult() - .success(false) - .enacted(true) - .comment( - MainApp.gs(R.string.combo_error_partial_bolus_delivered, lastPumpBolus.amount, - detailedBolusInfo.insulin)); + return new PumpEnactResult().success(false).enacted(true) + .comment(MainApp.gs(R.string.combo_error_partial_bolus_delivered, + lastPumpBolus.amount, detailedBolusInfo.insulin)); } // full bolus was delivered successfully incrementBolusCount(); - return new PumpEnactResult().success(true).enacted(lastPumpBolus.amount > 0) - .bolusDelivered(lastPumpBolus.amount).carbsDelivered(detailedBolusInfo.carbs); + return new PumpEnactResult() + .success(true) + .enacted(lastPumpBolus.amount > 0) + .bolusDelivered(lastPumpBolus.amount) + .carbsDelivered(detailedBolusInfo.carbs); } finally { pump.activity = null; MainApp.bus().post(new EventComboPumpUpdateGUI()); @@ -684,7 +655,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } } - private void incrementTbrCount() { try { SP.putLong(COMBO_TBRS_SET, SP.getLong(COMBO_TBRS_SET, 0L) + 1); @@ -693,7 +663,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } } - private void incrementBolusCount() { try { SP.putLong(COMBO_BOLUSES_DELIVERED, SP.getLong(COMBO_BOLUSES_DELIVERED, 0L) + 1); @@ -702,7 +671,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } } - /** Creates a treatment record based on the request in DetailBolusInfo and the delivered bolus. */ private boolean addBolusToTreatments(DetailedBolusInfo detailedBolusInfo, Bolus lastPumpBolus) { DetailedBolusInfo dbi = detailedBolusInfo.copy(); @@ -715,8 +683,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } catch (Exception e) { log.error("Adding treatment record failed", e); if (dbi.isSMB) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } return false; @@ -724,7 +691,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return true; } - @Override public void stopBolusDelivering() { if (scripterIsBolusing) { @@ -733,24 +699,21 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint cancelBolus = true; } - /** * Note: AAPS calls this solely to enact OpenAPS suggestions * * @param force the force parameter isn't used currently since we always set the tbr - - * there might be room for optimization to first test the currently running tbr - * and only change it if it differs (as the DanaR plugin does). This approach - * might have other issues though (what happens if the tbr which wasn't re-set to - * the new value (and thus still has the old duration of e.g. 1 min) expires?) + * there might be room for optimization to first test the currently running tbr + * and only change it if it differs (as the DanaR plugin does). This approach + * might have other issues though (what happens if the tbr which wasn't re-set to + * the new value (and thus still has the old duration of e.g. 1 min) expires?) */ @Override - public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, - boolean force) { + public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean force) { if (L.isEnabled(L.PUMP)) - log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes - + " min."); + log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min."); int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); - int roundedPercentage = (int)(Math.round(absoluteRate / getBaseBasalRate() * 10) * 10); + int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10); if (unroundedPercentage != roundedPercentage) { if (L.isEnabled(L.PUMP)) log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%"); @@ -759,35 +722,31 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return setTempBasalPercent(roundedPercentage, durationInMinutes); } - /** * Note: AAPS calls this directly only for setting a temp basal issued by the user * * @param forceNew Driver always applies the requested TBR and simply overrides whatever TBR - * is or isn't running at the moment + * is or isn't running at the moment */ @Override - public PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes, Profile profile, - boolean forceNew) { + public PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes, Profile profile, boolean forceNew) { return setTempBasalPercent(percent, durationInMinutes); } - private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) { if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min"); if (pumpHistoryChanged && percent > 110) { return new PumpEnactResult().success(false).enacted(false) - .comment(MainApp.gs(R.string.combo_high_temp_rejected_due_to_pump_history_changes)); + .comment(MainApp.gs(R.string.combo_high_temp_rejected_due_to_pump_history_changes)); } int adjustedPercent = percent; if (adjustedPercent > pumpDescription.maxTempPercent) { if (L.isEnabled(L.PUMP)) - log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " - + pumpDescription.maxTempPercent); + log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent); adjustedPercent = pumpDescription.maxTempPercent; } @@ -804,35 +763,35 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } int finalAdjustedPercent = adjustedPercent; - CommandResult commandResult = runCommand( - MainApp.gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes), 3, - () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes)); + CommandResult commandResult = runCommand(MainApp.gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes), + 3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes)); if (!commandResult.success) { return new PumpEnactResult().success(false).enacted(false); } PumpState state = commandResult.state; if (state.tbrActive && state.tbrPercent == adjustedPercent - && (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) { - TemporaryBasal tempStart = new TemporaryBasal().date(state.timestamp).duration(state.tbrRemainingDuration) - .percent(state.tbrPercent).source(Source.USER); + && (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) { + TemporaryBasal tempStart = new TemporaryBasal() + .date(state.timestamp) + .duration(state.tbrRemainingDuration) + .percent(state.tbrPercent) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStart); MainApp.bus().post(new EventComboPumpUpdateGUI()); } incrementTbrCount(); - return new PumpEnactResult().success(true).enacted(true).isPercent(true).percent(state.tbrPercent) - .duration(state.tbrRemainingDuration); + return new PumpEnactResult().success(true).enacted(true).isPercent(true) + .percent(state.tbrPercent).duration(state.tbrRemainingDuration); } - @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { return OPERATION_NOT_SUPPORTED; } - /** * Cancel an active Temp Basal. Mostly sets a fake Temp Basal to avoid a TBR CANCELLED * alert. This relies on TemporaryBasal objects to properly reflect the pumps state, @@ -845,11 +804,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint public PumpEnactResult cancelTempBasal(boolean enforceNew) { if (L.isEnabled(L.PUMP)) log.debug("cancelTempBasal called"); - final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory( - System.currentTimeMillis()); + final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); if (enforceNew) { - CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, - ruffyScripter::readPumpState); + CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); if (!stateResult.success) { return new PumpEnactResult().success(false).enacted(false); } @@ -858,14 +815,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } if (L.isEnabled(L.PUMP)) log.debug("cancelTempBasal: hard-cancelling TBR since force requested"); - CommandResult cancelResult = runCommand(MainApp.gs(R.string.combo_pump_action_cancelling_tbr), 2, - ruffyScripter::cancelTbr); + CommandResult cancelResult = runCommand(MainApp.gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr); if (!cancelResult.success) { return new PumpEnactResult().success(false).enacted(false); } if (!cancelResult.state.tbrActive) { - TemporaryBasal tempBasal = new TemporaryBasal().date(cancelResult.state.timestamp).duration(0) - .source(Source.USER); + TemporaryBasal tempBasal = new TemporaryBasal() + .date(cancelResult.state.timestamp) + .duration(0) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); return new PumpEnactResult().isTempCancel(true).success(true).enacted(true); } else { @@ -873,20 +831,16 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } } else if (activeTemp == null) { return new PumpEnactResult().success(true).enacted(false); - } else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) - && activeTemp.getPlannedRemainingMinutes() <= 15) { + } else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) && activeTemp.getPlannedRemainingMinutes() <= 15) { // Let fake neutral temp keep run (see below) // Note that since this runs on the queue a connection is opened regardless, but this // case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR). if (L.isEnabled(L.PUMP)) - log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate - + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); - return new PumpEnactResult() - .success(true) - .enacted(true) - .comment( - "cancelTempBasal skipping changing tbr since it already is at " + activeTemp.percentRate - + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); + log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); + return new PumpEnactResult().success(true).enacted(true) + .comment("cancelTempBasal skipping changing tbr since it already is at " + + activeTemp.percentRate + "% and running for another " + + activeTemp.getPlannedRemainingMinutes() + " mins."); } else { // Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on // on whether the TBR we're cancelling is above or below 100%. @@ -898,11 +852,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } private interface CommandExecution { - CommandResult execute(); } - /** * Runs a command, sets an activity if provided, retries if requested and updates fields * concerned with last connection. @@ -945,11 +897,11 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (commandResult.success) { pump.lastSuccessfulCmdTime = System.currentTimeMillis(); - if (validBasalRateProfileSelectedOnPump - && commandResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { + if (validBasalRateProfileSelectedOnPump && commandResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { setValidBasalRateProfileSelectedOnPump(false); Notification n = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_force_disabled_notification), Notification.URGENT); + MainApp.gs(R.string.combo_force_disabled_notification), + Notification.URGENT); n.soundId = R.raw.alarm; MainApp.bus().post(new EventNewNotification(n)); ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null); @@ -966,12 +918,10 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return commandResult; } - public void setValidBasalRateProfileSelectedOnPump(boolean value) { validBasalRateProfileSelectedOnPump = value; } - /** * Returns the command result of running ReadPumpState if it wasn't successful, indicating * an error condition. Returns null otherwise. @@ -987,8 +937,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // due to empty cartridge alert, which might also trigger TBR cancelled alert if (activeAlert != null) { if (activeAlert.warningCode != null - && (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW - || activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW || activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED)) { + && (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW || + activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW || + activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED)) { // turn benign warnings into notifications notifyAboutPumpWarning(activeAlert); ruffyScripter.confirmAlert(activeAlert.warningCode); @@ -997,8 +948,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint notification.date = new Date(); notification.id = Notification.COMBO_PUMP_ALARM; notification.level = Notification.URGENT; - notification.text = MainApp.gs(R.string.combo_is_in_error_state, activeAlert.errorCode, - activeAlert.message); + notification.text = MainApp.gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message); MainApp.bus().post(new EventNewNotification(notification)); return preCheckResult.success(false); } @@ -1019,8 +969,11 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (aapsTbr == null || aapsTbr.percentRate != 0) { if (L.isEnabled(L.PUMP)) log.debug("Creating 15m zero temp since pump is suspended"); - TemporaryBasal newTempBasal = new TemporaryBasal().date(now).percent(0).duration(15) - .source(Source.USER); + TemporaryBasal newTempBasal = new TemporaryBasal() + .date(now) + .percent(0) + .duration(15) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); } } @@ -1044,8 +997,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // can't infer base basal rate if TBR is 0 return; } - double pumpBasalRate = state.tbrActive ? Math.round(state.basalRate * 100 / state.tbrPercent * 100) / 100d - : state.basalRate; + double pumpBasalRate = state.tbrActive + ? Math.round(state.basalRate * 100 / state.tbrPercent * 100) / 100d + : state.basalRate; int pumpHour = new Date(state.pumpTime).getHours(); int phoneHour = new Date().getHours(); if (pumpHour != phoneHour) { @@ -1054,22 +1008,18 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } if (Math.abs(pumpBasalRate - getBaseBasalRate()) > 0.001) { - CommandResult readBasalResult = runCommand(MainApp.gs(R.string.combo_actvity_reading_basal_profile), 2, - ruffyScripter::readBasalProfile); + CommandResult readBasalResult = runCommand(MainApp.gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); if (readBasalResult.success) { pump.basalProfile = readBasalResult.basalProfile; - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); } else { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } } } - /** * Check pump time (on the main menu) and raise notification if time is off. * (setting clock is not supported by ruffy) @@ -1079,27 +1029,22 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // time couldn't be read (e.g. a warning is displayed on the menu , hiding the time field) } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) { if (L.isEnabled(L.PUMP)) - log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) - + ")"); - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_notification_check_time_date), Notification.URGENT); + log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) { if (L.isEnabled(L.PUMP)) - log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) - + ")"); - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_notification_check_time_date), Notification.NORMAL); + log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); } } - private void notifyAboutPumpWarning(WarningOrErrorCode activeAlert) { - if (activeAlert.warningCode == null - || (!activeAlert.warningCode.equals(PumpWarningCodes.CARTRIDGE_LOW) - && !activeAlert.warningCode.equals(PumpWarningCodes.BATTERY_LOW) && !activeAlert.warningCode - .equals(PumpWarningCodes.TBR_CANCELLED))) { + if (activeAlert.warningCode == null || + (!activeAlert.warningCode.equals(PumpWarningCodes.CARTRIDGE_LOW) + && !activeAlert.warningCode.equals(PumpWarningCodes.BATTERY_LOW) + && !activeAlert.warningCode.equals(PumpWarningCodes.TBR_CANCELLED))) { throw new IllegalArgumentException(activeAlert.toString()); } Notification notification = new Notification(); @@ -1116,10 +1061,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint MainApp.bus().post(new EventNewNotification(notification)); } - private void checkForUnsafeUsage(CommandResult commandResult) { - if (commandResult == null) - return; + if (commandResult == null) return; long lastViolation = 0; if (commandResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BOLUS_TYPE) { @@ -1133,10 +1076,10 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } if (lastViolation > 0) { lowSuspendOnlyLoopEnforcedUntil = lastViolation + 6 * 60 * 60 * 1000; - if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis() - && violationWarningRaisedForBolusAt != lowSuspendOnlyLoopEnforcedUntil) { + if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis() && violationWarningRaisedForBolusAt != lowSuspendOnlyLoopEnforcedUntil) { Notification n = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_low_suspend_forced_notification), Notification.URGENT); + MainApp.gs(R.string.combo_low_suspend_forced_notification), + Notification.URGENT); n.soundId = R.raw.alarm; MainApp.bus().post(new EventNewNotification(n)); violationWarningRaisedForBolusAt = lowSuspendOnlyLoopEnforcedUntil; @@ -1145,7 +1088,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } } - /** * Checks the main screen to determine if TBR on pump matches app state. */ @@ -1156,36 +1098,45 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) { if (L.isEnabled(L.PUMP)) log.debug("Creating temp basal from pump TBR"); - TemporaryBasal newTempBasal = new TemporaryBasal().date(now).percent(state.tbrPercent) - .duration(state.tbrRemainingDuration).source(Source.USER); + TemporaryBasal newTempBasal = new TemporaryBasal() + .date(now) + .percent(state.tbrPercent) + .duration(state.tbrRemainingDuration) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); } else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) { if (L.isEnabled(L.PUMP)) log.debug("Ending AAPS-TBR since pump has no TBR active"); - TemporaryBasal tempStop = new TemporaryBasal().date(now).duration(0).source(Source.USER); + TemporaryBasal tempStop = new TemporaryBasal() + .date(now) + .duration(0) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); - } else if (aapsTbr != null - && state.tbrActive - && (aapsTbr.percentRate != state.tbrPercent || Math.abs(aapsTbr.getPlannedRemainingMinutes() - - state.tbrRemainingDuration) > 2)) { + } else if (aapsTbr != null && state.tbrActive + && (aapsTbr.percentRate != state.tbrPercent || + Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) { if (L.isEnabled(L.PUMP)) log.debug("AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR"); - TemporaryBasal tempStop = new TemporaryBasal().date(now - 1000).duration(0).source(Source.USER); + TemporaryBasal tempStop = new TemporaryBasal() + .date(now - 1000) + .duration(0) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); - TemporaryBasal newTempBasal = new TemporaryBasal().date(now).percent(state.tbrPercent) - .duration(state.tbrRemainingDuration).source(Source.USER); + TemporaryBasal newTempBasal = new TemporaryBasal() + .date(now) + .percent(state.tbrPercent) + .duration(state.tbrRemainingDuration) + .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); } } - /** * Reads the pump's history and updates the DB accordingly. */ private boolean readHistory(@Nullable PumpHistoryRequest request) { - CommandResult historyResult = runCommand(MainApp.gs(R.string.combo_activity_reading_pump_history), 3, - () -> ruffyScripter.readHistory(request)); + CommandResult historyResult = runCommand(MainApp.gs(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request)); PumpHistory history = historyResult.history; if (!historyResult.success || history == null) { return false; @@ -1204,7 +1155,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return historyResult.success; } - /** Return value indicates whether a new record was created. */ private boolean updateDbFromPumpHistory(@NonNull PumpHistory history) { boolean updated = false; @@ -1222,7 +1172,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return updated; } - /** * Adds the bolus to the timestamp to be able to differentiate multiple boluses in the same * minute. Best effort, since this covers only boluses up to 6.0 U and relies on other code @@ -1232,11 +1181,10 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ long calculateFakeBolusDate(Bolus pumpBolus) { double bolus = pumpBolus.amount - 0.1; - int secondsFromBolus = (int)(bolus * 10 * 1000); + int secondsFromBolus = (int) (bolus * 10 * 1000); return pumpBolus.timestamp + Math.min(secondsFromBolus, 59 * 1000); } - /** * Reads QuickInfo to update reservoir level and determine if new boluses exist on the pump * and if so, queries the history for all new records. @@ -1245,7 +1193,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ private CommandResult checkHistory() { CommandResult quickInfoResult = runCommand(MainApp.gs(R.string.combo_activity_checking_for_history_changes), 3, - () -> ruffyScripter.readQuickInfo(2)); + () -> ruffyScripter.readQuickInfo(2)); // no history, nothing to check or complain about if (quickInfoResult.history == null || quickInfoResult.history.bolusHistory.isEmpty()) { @@ -1258,14 +1206,14 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // compare recent records List initialPumpBolusHistory = quickInfoResult.history.bolusHistory; if (recentBoluses.size() == 1 && initialPumpBolusHistory.size() >= 1 - && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))) { + && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))) { if (L.isEnabled(L.PUMP)) log.debug("Setting 'pumpHistoryChanged' false"); pumpHistoryChanged = false; return null; } else if (recentBoluses.size() == 2 && initialPumpBolusHistory.size() >= 2 - && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0)) - && recentBoluses.get(1).equals(quickInfoResult.history.bolusHistory.get(1))) { + && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0)) + && recentBoluses.get(1).equals(quickInfoResult.history.bolusHistory.get(1))) { if (L.isEnabled(L.PUMP)) log.debug("Setting 'pumpHistoryChanged' false"); pumpHistoryChanged = false; @@ -1274,8 +1222,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // fetch new records long lastKnownPumpRecordTimestamp = recentBoluses.isEmpty() ? 0 : recentBoluses.get(0).timestamp; - CommandResult historyResult = runCommand(MainApp.gs(R.string.combo_activity_reading_pump_history), 3, - () -> ruffyScripter.readHistory(new PumpHistoryRequest().bolusHistory(lastKnownPumpRecordTimestamp))); + CommandResult historyResult = runCommand(MainApp.gs(R.string.combo_activity_reading_pump_history), 3, () -> + ruffyScripter.readHistory(new PumpHistoryRequest().bolusHistory(lastKnownPumpRecordTimestamp))); if (!historyResult.success) { pumpHistoryChanged = true; return historyResult; @@ -1289,8 +1237,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (bolusSet.size() != historyResult.history.bolusHistory.size()) { if (L.isEnabled(L.PUMP)) log.debug("Bolus with same amount within the same minute imported. Only one will make it to the DB."); - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, - MainApp.gs(R.string.combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string. + combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } @@ -1307,13 +1255,11 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return null; } - @Override public PumpEnactResult cancelExtendedBolus() { return OPERATION_NOT_SUPPORTED; } - @Override public JSONObject getJSONStatus(Profile profile, String profileName) { if (!pump.initialized) { @@ -1325,14 +1271,10 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint pumpJson.put("clock", DateUtil.toISOString(pump.lastSuccessfulCmdTime)); int level; - if (pump.reservoirLevel != -1) - level = pump.reservoirLevel; - else if (pump.state.insulinState == PumpState.LOW) - level = 8; - else if (pump.state.insulinState == PumpState.EMPTY) - level = 0; - else - level = 150; + if (pump.reservoirLevel != -1) level = pump.reservoirLevel; + else if (pump.state.insulinState == PumpState.LOW) level = 8; + else if (pump.state.insulinState == PumpState.EMPTY) level = 0; + else level = 150; pumpJson.put("reservoir", level); JSONObject statusJson = new JSONObject(); @@ -1356,10 +1298,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint JSONObject batteryJson = new JSONObject(); int battery = 100; - if (ps.batteryState == PumpState.LOW) - battery = 25; - else if (ps.batteryState == PumpState.EMPTY) - battery = 0; + if (ps.batteryState == PumpState.LOW) battery = 25; + else if (ps.batteryState == PumpState.EMPTY) battery = 0; batteryJson.put("percent", battery); pumpJson.put("battery", batteryJson); @@ -1371,31 +1311,26 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return null; } - @Override public String deviceID() { return "Combo"; } - @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override public String shortStatus(boolean veryShort) { return getStateSummary(); } - @Override public boolean isFakingTempsByExtendedBoluses() { return false; } - @Override public PumpEnactResult loadTDDs() { PumpEnactResult result = new PumpEnactResult(); @@ -1407,9 +1342,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint for (int i = 0; i < tdds.size(); i++) { Tdd currTdd = tdds.get(i); if (currTdd.total < 1) - continue; // cases where dummy days are introduced (e.g. Battery change with date loss) + continue; //cases where dummy days are introduced (e.g. Battery change with date loss) if (map.containsKey(currTdd.timestamp)) { - // duplicate days on time changes + //duplicate days on time changes TDD existing = map.get(currTdd.timestamp); existing.total += currTdd.total; } else { @@ -1427,24 +1362,11 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return result; } - - @Override - public List getCustomActions() { - return null; - } - - - @Override - public PumpEnactResult executeCustomAction(CustomActionType customActionType) { - return null; - } - // Constraints interface private long lowSuspendOnlyLoopEnforcedUntil = 0; private long violationWarningRaisedForBolusAt = 0; private boolean validBasalRateProfileSelectedOnPump = true; - @Override public Constraint isLoopInvocationAllowed(Constraint value) { if (!validBasalRateProfileSelectedOnPump) @@ -1452,12 +1374,26 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return value; } - @Override public Constraint applyMaxIOBConstraints(Constraint maxIob) { if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis()) - maxIob.setIfSmaller(0d, - String.format(MainApp.gs(R.string.limitingmaxiob), 0d, MainApp.gs(R.string.unsafeusage)), this); + maxIob.setIfSmaller(0d, String.format(MainApp.gs(R.string.limitingmaxiob), 0d, MainApp.gs(R.string.unsafeusage)), this); return maxIob; } -} + + @Override + public List getCustomActions() { + return null; + } + + @Override + public void executeCustomAction(CustomActionType customActionType) { + + } + + @Override + public boolean canHandleDST() { + return false; + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index 51ef539689..749307e1a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.pump.danaR; -import java.util.Date; -import java.util.List; +import android.support.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.support.annotation.Nullable; +import java.util.Date; +import java.util.List; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; @@ -47,7 +47,6 @@ import info.nightscout.androidaps.utils.SP; */ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface { - protected Logger log = LoggerFactory.getLogger(L.PUMP); protected AbstractDanaRExecutionService sExecutionService; @@ -56,14 +55,17 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte public PumpDescription pumpDescription = new PumpDescription(); - protected AbstractDanaRPlugin() { - super(new PluginDescription().mainType(PluginType.PUMP).fragmentClass(DanaRFragment.class.getName()) - .pluginName(R.string.danarspump).shortName(R.string.danarpump_shortname).preferencesId(R.xml.pref_danars) - .description(R.string.description_pump_dana_r)); + super(new PluginDescription() + .mainType(PluginType.PUMP) + .fragmentClass(DanaRFragment.class.getName()) + .pluginName(R.string.danarspump) + .shortName(R.string.danarpump_shortname) + .preferencesId(R.xml.pref_danars) + .description(R.string.description_pump_dana_r) + ); } - @Override public void onStateChange(PluginType type, State oldState, State newState) { // if pump profile was enabled need to switch to another too @@ -74,21 +76,17 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } } - @Override public boolean isSuspended() { return DanaRPump.getInstance().pumpSuspended; } - @Override public boolean isBusy() { - if (sExecutionService == null) - return false; + if (sExecutionService == null) return false; return sExecutionService.isConnected() || sExecutionService.isConnecting(); } - // Pump interface @Override public PumpEnactResult setNewBasalProfile(Profile profile) { @@ -101,8 +99,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } if (!isInitialized()) { log.error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, - MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); + Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet); return result; @@ -110,16 +107,14 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); } if (!sExecutionService.updateBasalsInPump(profile)) { - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, - MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = MainApp.gs(R.string.failedupdatebasalprofile); return result; } else { MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - 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)); result.success = true; result.enacted = true; @@ -128,7 +123,6 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } } - @Override public boolean isThisProfileSet(Profile profile) { if (!isInitialized()) @@ -141,8 +135,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte for (int h = 0; h < basalValues; h++) { Double pumpValue = pump.pumpProfiles[pump.activeProfile][h]; Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement); - if (profileValue == null) - return true; + if (profileValue == null) return true; if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { if (L.isEnabled(L.PUMP)) log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); @@ -152,30 +145,21 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return true; } - @Override public long lastDataTime() { return DanaRPump.getInstance().lastConnection; } - @Override public double getBaseBasalRate() { return DanaRPump.getInstance().currentBasal; } + @Override + public double getReservoirLevel() { return DanaRPump.getInstance().reservoirRemainingUnits; } @Override - public double getReservoirLevel() { - return DanaRPump.getInstance().reservoirRemainingUnits; - } - - - @Override - public int getBatteryLevel() { - return DanaRPump.getInstance().batteryRemaining; - } - + public int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; } @Override public void stopBolusDelivering() { @@ -186,14 +170,11 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte sExecutionService.bolusStop(); } - @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, - boolean enforceNew) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile) - .value(); + percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -239,7 +220,6 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return result; } - @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); @@ -259,13 +239,11 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte result.isPercent = false; result.isTempCancel = false; if (L.isEnabled(L.PUMP)) - log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount - + " Asked: " + insulin); + log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount + " Asked: " + insulin); return result; } boolean connectionOK = sExecutionService.extendedBolus(insulin, durationInHalfHours); - if (connectionOK && pump.isExtendedInProgress - && Math.abs(pump.extendedBolusAmount - insulin) < getPumpDescription().extendedBolusStep) { + if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAmount - insulin) < getPumpDescription().extendedBolusStep) { result.enacted = true; result.success = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); @@ -286,7 +264,6 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return result; } - @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); @@ -310,7 +287,6 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } } - @Override public void connect(String from) { if (sExecutionService != null) { @@ -320,33 +296,26 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } } - @Override public boolean isConnected() { return sExecutionService != null && sExecutionService.isConnected(); } - @Override public boolean isConnecting() { return sExecutionService != null && sExecutionService.isConnecting(); } - @Override public void disconnect(String from) { - if (sExecutionService != null) - sExecutionService.disconnect(from); + if (sExecutionService != null) sExecutionService.disconnect(from); } - @Override public void stopConnecting() { - if (sExecutionService != null) - sExecutionService.stopConnecting(); + if (sExecutionService != null) sExecutionService.stopConnecting(); } - @Override public void getPumpStatus() { if (sExecutionService != null) { @@ -356,7 +325,6 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte } } - @Override public JSONObject getJSONStatus(Profile profile, String profilename) { DanaRPump pump = DanaRPump.getInstance(); @@ -399,7 +367,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte pumpjson.put("battery", battery); pumpjson.put("status", status); pumpjson.put("extended", extended); - pumpjson.put("reservoir", (int)pump.reservoirRemainingUnits); + pumpjson.put("reservoir", (int) pump.reservoirRemainingUnits); pumpjson.put("clock", DateUtil.toISOString(new Date())); } catch (JSONException e) { log.error("Unhandled exception", e); @@ -407,19 +375,16 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return pumpjson; } - @Override public String deviceID() { return DanaRPump.getInstance().serialNumber; } - @Override public PumpDescription getPumpDescription() { return pumpDescription; } - /** * DanaR interface */ @@ -429,51 +394,35 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return sExecutionService.loadHistory(type); } - /** * Constraint interface */ @Override public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { - absoluteRate.setIfSmaller( - DanaRPump.getInstance().maxBasal, - String.format(MainApp.gs(R.string.limitingbasalratio), DanaRPump.getInstance().maxBasal, - MainApp.gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(DanaRPump.getInstance().maxBasal, String.format(MainApp.gs(R.string.limitingbasalratio), DanaRPump.getInstance().maxBasal, MainApp.gs(R.string.pumplimit)), this); return absoluteRate; } - @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - percentRate.setIfGreater(0, - String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), - this); - percentRate.setIfSmaller( - getPumpDescription().maxTempPercent, - String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, - MainApp.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); return percentRate; } - @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller( - DanaRPump.getInstance().maxBolus, - String.format(MainApp.gs(R.string.limitingbolus), DanaRPump.getInstance().maxBolus, - MainApp.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(DanaRPump.getInstance().maxBolus, String.format(MainApp.gs(R.string.limitingbolus), DanaRPump.getInstance().maxBolus, MainApp.gs(R.string.pumplimit)), this); return insulin; } - @Override public Constraint applyExtendedBolusConstraints(Constraint insulin) { return applyBolusConstraints(insulin); } - @Nullable @Override public ProfileStore getProfile() { @@ -482,61 +431,52 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte return DanaRPump.getInstance().createConvertedProfile(); } - @Override public String getUnits() { return DanaRPump.getInstance().getUnits(); } - @Override public String getProfileName() { return DanaRPump.getInstance().createConvertedProfileName(); } - @Override public PumpEnactResult loadTDDs() { return loadHistory(RecordTypes.RECORD_TYPE_DAILY); } - // Reply for sms communicator public String shortStatus(boolean veryShort) { DanaRPump pump = DanaRPump.getInstance(); String ret = ""; if (pump.lastConnection != 0) { Long agoMsec = System.currentTimeMillis() - pump.lastConnection; - int agoMin = (int)(agoMsec / 60d / 1000d); + int agoMin = (int) (agoMsec / 60d / 1000d); ret += "LastConn: " + agoMin + " minago\n"; } if (pump.lastBolusTime != 0) { - ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" - + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; + ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; } - TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin() - .getRealTempBasalFromHistory(System.currentTimeMillis()); + TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { ret += "Temp: " + activeTemp.toStringFull() + "\n"; } - ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory( - System.currentTimeMillis()); + ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); if (activeExtendedBolus != null) { ret += "Extended: " + activeExtendedBolus.toString() + "\n"; } if (!veryShort) { - ret += "TDD: " + DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits - + " U\n"; + ret += "TDD: " + DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits + " U\n"; } ret += "IOB: " + pump.iob + "U\n"; ret += "Reserv: " + DecimalFormatter.to0Decimal(pump.reservoirRemainingUnits) + "U\n"; ret += "Batt: " + pump.batteryRemaining + "\n"; return ret; } - - // TODO: daily total constraint + @Override public List getCustomActions() { return null; @@ -544,7 +484,16 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte @Override - public PumpEnactResult executeCustomAction(CustomActionType customActionType) { - return null; + public void executeCustomAction(CustomActionType customActionType) { + } + + @Override + public boolean canHandleDST() { + return false; + } + + + + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 7cc30ef571..ddbb8547ae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -1,12 +1,5 @@ package info.nightscout.androidaps.plugins.pump.danaRS; -import java.util.List; - -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.content.ComponentName; import android.content.Context; import android.content.Intent; @@ -18,6 +11,13 @@ import android.support.v7.app.AlertDialog; import com.squareup.otto.Subscribe; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -67,11 +67,9 @@ import info.nightscout.androidaps.utils.T; */ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface { - private Logger log = LoggerFactory.getLogger(L.PUMP); private static DanaRSPlugin plugin = null; - public static DanaRSPlugin getPlugin() { if (plugin == null) plugin = new DanaRSPlugin(); @@ -85,16 +83,19 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte public static PumpDescription pumpDescription = new PumpDescription(); - private DanaRSPlugin() { - super(new PluginDescription().mainType(PluginType.PUMP).fragmentClass(DanaRFragment.class.getName()) - .pluginName(R.string.danarspump).shortName(R.string.danarspump_shortname).preferencesId(R.xml.pref_danars) - .description(R.string.description_pump_dana_rs)); + super(new PluginDescription() + .mainType(PluginType.PUMP) + .fragmentClass(DanaRFragment.class.getName()) + .pluginName(R.string.danarspump) + .shortName(R.string.danarspump_shortname) + .preferencesId(R.xml.pref_danars) + .description(R.string.description_pump_dana_rs) + ); pumpDescription.setPumpDescription(PumpType.DanaRS); } - @Override public void onStateChange(PluginType type, State oldState, State newState) { // if pump profile was enabled need to switch to another too @@ -105,7 +106,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override protected void onStart() { Context context = MainApp.instance().getApplicationContext(); @@ -117,7 +117,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte super.onStart(); } - @Override protected void onStop() { Context context = MainApp.instance().getApplicationContext(); @@ -126,25 +125,25 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte MainApp.bus().unregister(this); } - @Override - public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, - FragmentActivity context) { + public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); if (allowHardwarePump || context == null) { pluginSwitcher.invoke(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(context); - builder.setMessage(R.string.allow_hardware_pump_text).setPositiveButton(R.string.yes, (dialog, id) -> { - pluginSwitcher.invoke(); - SP.putBoolean("allow_hardware_pump", true); - if (L.isEnabled(L.PUMP)) - log.debug("First time HW pump allowed!"); - }).setNegativeButton(R.string.cancel, (dialog, id) -> { - pluginSwitcher.cancel(); - if (L.isEnabled(L.PUMP)) - log.debug("User does not allow switching to HW pump!"); - }); + builder.setMessage(R.string.allow_hardware_pump_text) + .setPositiveButton(R.string.yes, (dialog, id) -> { + pluginSwitcher.invoke(); + SP.putBoolean("allow_hardware_pump", true); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); + }) + .setNegativeButton(R.string.cancel, (dialog, id) -> { + pluginSwitcher.cancel(); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); + }); builder.create().show(); } } @@ -157,30 +156,26 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte danaRSService = null; } - public void onServiceConnected(ComponentName name, IBinder service) { if (L.isEnabled(L.PUMP)) log.debug("Service is connected"); - DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder)service; + DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder) service; danaRSService = mLocalBinder.getServiceInstance(); } }; - @SuppressWarnings("UnusedParameters") @Subscribe public void onStatusEvent(final EventAppExit e) { MainApp.instance().getApplicationContext().unbindService(mConnection); } - @Subscribe public void onStatusEvent(final EventDanaRSDeviceChange e) { mDeviceAddress = SP.getString(R.string.key_danars_address, ""); mDeviceName = SP.getString(R.string.key_danars_name, ""); } - @Override public void connect(String from) { if (L.isEnabled(L.PUMP)) @@ -192,46 +187,37 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override public boolean isConnected() { return danaRSService != null && danaRSService.isConnected(); } - @Override public boolean isConnecting() { return danaRSService != null && danaRSService.isConnecting(); } - @Override public boolean isHandshakeInProgress() { return false; } - @Override public void finishHandshaking() { } - @Override public void disconnect(String from) { if (L.isEnabled(L.PUMP)) log.debug("RS disconnect from: " + from); - if (danaRSService != null) - danaRSService.disconnect(from); + if (danaRSService != null) danaRSService.disconnect(from); } - @Override public void stopConnecting() { - if (danaRSService != null) - danaRSService.stopConnecting(); + if (danaRSService != null) danaRSService.stopConnecting(); } - @Override public void getPumpStatus() { if (danaRSService != null) { @@ -241,7 +227,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - // DanaR interface @Override @@ -249,40 +234,28 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return danaRSService.loadHistory(type); } - @Override public PumpEnactResult loadEvents() { return danaRSService.loadEvents(); } - @Override public PumpEnactResult setUserOptions() { return danaRSService.setUserSettings(); } - // Constraints interface @Override public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { - absoluteRate.setIfSmaller( - DanaRPump.getInstance().maxBasal, - String.format(MainApp.gs(R.string.limitingbasalratio), DanaRPump.getInstance().maxBasal, - MainApp.gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(DanaRPump.getInstance().maxBasal, String.format(MainApp.gs(R.string.limitingbasalratio), DanaRPump.getInstance().maxBasal, MainApp.gs(R.string.pumplimit)), this); return absoluteRate; } - @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - percentRate.setIfGreater(0, - String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), - this); - percentRate.setIfSmaller( - getPumpDescription().maxTempPercent, - String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, - MainApp.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); return percentRate; } @@ -290,20 +263,15 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller( - DanaRPump.getInstance().maxBolus, - String.format(MainApp.gs(R.string.limitingbolus), DanaRPump.getInstance().maxBolus, - MainApp.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(DanaRPump.getInstance().maxBolus, String.format(MainApp.gs(R.string.limitingbolus), DanaRPump.getInstance().maxBolus, MainApp.gs(R.string.pumplimit)), this); return insulin; } - @Override public Constraint applyExtendedBolusConstraints(Constraint insulin) { return applyBolusConstraints(insulin); } - // Profile interface @Nullable @@ -314,19 +282,16 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return DanaRPump.getInstance().createConvertedProfile(); } - @Override public String getUnits() { return DanaRPump.getInstance().getUnits(); } - @Override public String getProfileName() { return DanaRPump.getInstance().createConvertedProfileName(); } - // Pump interface @Override @@ -334,21 +299,17 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return DanaRPump.getInstance().lastConnection > 0 && DanaRPump.getInstance().maxBasal > 0; } - @Override public boolean isSuspended() { return DanaRPump.getInstance().pumpSuspended; } - @Override public boolean isBusy() { - if (danaRSService == null) - return false; + if (danaRSService == null) return false; return danaRSService.isConnected() || danaRSService.isConnecting(); } - @Override public PumpEnactResult setNewBasalProfile(Profile profile) { PumpEnactResult result = new PumpEnactResult(); @@ -360,8 +321,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } if (!isInitialized()) { log.error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, - MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); + Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet); return result; @@ -369,16 +329,14 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); } if (!danaRSService.updateBasalsInPump(profile)) { - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, - MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = MainApp.gs(R.string.failedupdatebasalprofile); return result; } else { MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - 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)); result.success = true; result.enacted = true; @@ -387,7 +345,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override public boolean isThisProfileSet(Profile profile) { if (!isInitialized()) @@ -399,9 +356,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte int basalIncrement = pump.basal48Enable ? 30 * 60 : 60 * 60; for (int h = 0; h < basalValues; h++) { Double pumpValue = pump.pumpProfiles[pump.activeProfile][h]; - Double profileValue = profile.getBasalTimeFromMidnight((Integer)(h * basalIncrement)); - if (profileValue == null) - return true; + Double profileValue = profile.getBasalTimeFromMidnight((Integer) (h * basalIncrement)); + if (profileValue == null) return true; if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { if (L.isEnabled(L.PUMP)) log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); @@ -411,35 +367,25 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return true; } - @Override public long lastDataTime() { return DanaRPump.getInstance().lastConnection; } - @Override public double getBaseBasalRate() { return DanaRPump.getInstance().currentBasal; } + @Override + public double getReservoirLevel() { return DanaRPump.getInstance().reservoirRemainingUnits; } @Override - public double getReservoirLevel() { - return DanaRPump.getInstance().reservoirRemainingUnits; - } - - - @Override - public int getBatteryLevel() { - return DanaRPump.getInstance().batteryRemaining; - } - + public int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; } @Override public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker() - .applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); int speed = 12; @@ -456,14 +402,13 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } // RS stores end time for bolus, we need to adjust time // default delivery speed is 12 sec/U - detailedBolusInfo.date = DateUtil.now() + (long)(speed * detailedBolusInfo.insulin * 1000); + detailedBolusInfo.date = DateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000); // clean carbs to prevent counting them as twice because they will picked up as another record // I don't think it's necessary to copy DetailedBolusInfo right now for carbs records double carbs = detailedBolusInfo.carbs; detailedBolusInfo.carbs = 0; int carbTime = detailedBolusInfo.carbTime; - if (carbTime == 0) - carbTime--; // better set 1 min back to prevents clash with insulin + if (carbTime == 0) carbTime--; // better set 1 min back to prevents clash with insulin detailedBolusInfo.carbTime = 0; DetailedBolusInfoStorage.add(detailedBolusInfo); // will be picked up on reading history @@ -472,17 +417,15 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte t.isSMB = detailedBolusInfo.isSMB; boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || carbs > 0) - connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int)carbs, - DateUtil.now() + T.mins(carbTime).msecs(), t); + connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); PumpEnactResult result = new PumpEnactResult(); - result.success = connectionOK - && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; + result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; result.bolusDelivered = t.insulin; result.carbsDelivered = detailedBolusInfo.carbs; if (!result.success) { String error = "" + DanaRS_Packet_Bolus_Set_Step_Bolus_Start.errorCode; switch (DanaRS_Packet_Bolus_Set_Step_Bolus_Start.errorCode) { - // 4 reported as max bolus violation. Check later + // 4 reported as max bolus violation. Check later case 0x10: error = MainApp.gs(R.string.maxbolusviolation); break; @@ -496,13 +439,11 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte error = MainApp.gs(R.string.insulinlimitviolation); break; } - result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, - t.insulin, error); + result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, error); } else result.comment = MainApp.gs(R.string.virtualpump_resultok); if (L.isEnabled(L.PUMP)) - log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " - + result.bolusDelivered); + log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); return result; } else { PumpEnactResult result = new PumpEnactResult(); @@ -515,7 +456,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override public void stopBolusDelivering() { if (danaRSService == null) { @@ -525,22 +465,19 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte danaRSService.bolusStop(); } - // This is called from APS @Override - public synchronized PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, - Profile profile, boolean enforceNew) { + public synchronized PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { // Recheck pump status if older than 30 min - // This should not be needed while using queue because connection should be done before calling this - // if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) { - // connect("setTempBasalAbsolute old data"); - // } + //This should not be needed while using queue because connection should be done before calling this + //if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) { + // connect("setTempBasalAbsolute old data"); + //} PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile) - .value(); + absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -565,15 +502,12 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte if (doLowTemp || doHighTemp) { Integer percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); - if (percentRate < 100) - percentRate = Round.ceilTo((double)percentRate, 10d).intValue(); - else - percentRate = Round.floorTo((double)percentRate, 10d).intValue(); + if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); + else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); if (percentRate > 500) // Special high temp 500/15min percentRate = 500; // Check if some temp is already in progress - TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin() - .getTempBasalFromHistory(System.currentTimeMillis()); + TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: currently running: " + activeTemp.toString()); @@ -594,8 +528,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } // Convert duration from minutes to hours if (L.isEnabled(L.PUMP)) - log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes - + " mins (doLowTemp || doHighTemp)"); + log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); if (percentRate == 0 && durationInMinutes > 30) { result = setTempBasalPercent(percentRate, durationInMinutes, profile, false); } else { @@ -617,14 +550,11 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - @Override - public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, - Profile profile, boolean enforceNew) { + public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile) - .value(); + percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -675,7 +605,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - private synchronized PumpEnactResult setHighTempBasalPercent(Integer percent) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); @@ -699,7 +628,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - @Override public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); @@ -718,13 +646,11 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.isPercent = false; result.isTempCancel = false; if (L.isEnabled(L.PUMP)) - log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount - + " Asked: " + insulin); + log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount + " Asked: " + insulin); return result; } boolean connectionOK = danaRSService.extendedBolus(insulin, durationInHalfHours); - if (connectionOK && pump.isExtendedInProgress - && Math.abs(pump.extendedBolusAbsoluteRate - insulin) < getPumpDescription().extendedBolusStep) { + if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAbsoluteRate - insulin) < getPumpDescription().extendedBolusStep) { result.enacted = true; result.success = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); @@ -744,7 +670,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return result; } - @Override public synchronized PumpEnactResult cancelTempBasal(boolean force) { PumpEnactResult result = new PumpEnactResult(); @@ -770,7 +695,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override public synchronized PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); @@ -794,7 +718,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } } - @Override public JSONObject getJSONStatus(Profile profile, String profileName) { DanaRPump pump = DanaRPump.getInstance(); @@ -837,7 +760,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte pumpjson.put("battery", battery); pumpjson.put("status", status); pumpjson.put("extended", extended); - pumpjson.put("reservoir", (int)pump.reservoirRemainingUnits); + pumpjson.put("reservoir", (int) pump.reservoirRemainingUnits); pumpjson.put("clock", DateUtil.toISOString(now)); } catch (JSONException e) { log.error("Unhandled exception", e); @@ -845,45 +768,38 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return pumpjson; } - @Override public String deviceID() { return DanaRPump.getInstance().serialNumber; } - @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override public String shortStatus(boolean veryShort) { DanaRPump pump = DanaRPump.getInstance(); String ret = ""; if (pump.lastConnection != 0) { Long agoMsec = System.currentTimeMillis() - pump.lastConnection; - int agoMin = (int)(agoMsec / 60d / 1000d); + int agoMin = (int) (agoMsec / 60d / 1000d); ret += "LastConn: " + agoMin + " minago\n"; } if (pump.lastBolusTime != 0) { - ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" - + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; + ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; } - TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin() - .getRealTempBasalFromHistory(System.currentTimeMillis()); + TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { ret += "Temp: " + activeTemp.toStringFull() + "\n"; } - ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory( - System.currentTimeMillis()); + ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); if (activeExtendedBolus != null) { ret += "Extended: " + activeExtendedBolus.toString() + "\n"; } if (!veryShort) { - ret += "TDD: " + DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits - + " U\n"; + ret += "TDD: " + DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits + " U\n"; } ret += "IOB: " + pump.iob + "U\n"; ret += "Reserv: " + DecimalFormatter.to0Decimal(pump.reservoirRemainingUnits) + "U\n"; @@ -891,27 +807,29 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte return ret; } - @Override public boolean isFakingTempsByExtendedBoluses() { return false; } - @Override public PumpEnactResult loadTDDs() { return loadHistory(RecordTypes.RECORD_TYPE_DAILY); } - @Override public List getCustomActions() { return null; } + @Override + public void executeCustomAction(CustomActionType customActionType) { + + } @Override - public PumpEnactResult executeCustomAction(CustomActionType customActionType) { - return null; + public boolean canHandleDST() { + return false; } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index 438142f5f1..9e3ca499d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -19,9 +19,11 @@ import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; + import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.configBuilder.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; + import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 4aefd391c1..26f5180f47 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -298,4 +298,4 @@ public class LocalInsightFragment extends SubscriberFragment implements View.OnC statusItems.add(getStatusItem(label, MainApp.gs(R.string.eb_formatter, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration()))); } } -} +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 4b7d57a7c5..ccc38c1b9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -1,17 +1,5 @@ package info.nightscout.androidaps.plugins.pump.insight; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.content.ComponentName; import android.content.Context; import android.content.Intent; @@ -20,6 +8,22 @@ import android.os.Handler; import android.os.IBinder; import android.os.Looper; +import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; +import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; +import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.*; +import info.nightscout.androidaps.plugins.pump.insight.descriptors.*; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -43,8 +47,6 @@ 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.actions.defs.CustomAction; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; @@ -71,12 +73,6 @@ import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.StartOfTBREvent; import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.TotalDailyDoseEvent; import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history_events.TubeFilledEvent; -import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.BRProfile1Block; -import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.BRProfileBlock; -import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.FactoryMinBolusAmountBlock; -import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.MaxBasalAmountBlock; -import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.MaxBolusAmountBlock; -import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock; import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.CancelBolusMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.CancelTBRMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.remote_control.ChangeTBRMessage; @@ -100,18 +96,6 @@ import info.nightscout.androidaps.plugins.pump.insight.connection_service.Insigh import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID; import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset; import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveTBR; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertType; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.BasalProfileBlock; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.BatteryStatus; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.BolusType; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.CartridgeStatus; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.OperatingMode; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.PumpTime; -import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose; import info.nightscout.androidaps.plugins.pump.insight.exceptions.InsightException; import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.AppLayerErrorException; import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException; @@ -133,20 +117,18 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con private InsightConnectionService connectionService; private long timeOffset; private ServiceConnection serviceConnection = new ServiceConnection() { - @Override public void onServiceConnected(ComponentName name, IBinder binder) { if (binder instanceof InsightConnectionService.LocalBinder) { - connectionService = ((InsightConnectionService.LocalBinder)binder).getService(); + connectionService = ((InsightConnectionService.LocalBinder) binder).getService(); connectionService.registerStateCallback(LocalInsightPlugin.this); } else if (binder instanceof InsightAlertService.LocalBinder) { - alertService = ((InsightAlertService.LocalBinder)binder).getService(); + alertService = ((InsightAlertService.LocalBinder) binder).getService(); } if (connectionService != null && alertService != null) MainApp.bus().post(new EventInitializationChanged()); } - @Override public void onServiceDisconnected(ComponentName name) { connectionService = null; @@ -156,6 +138,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con private final Object $bolusLock = new Object[0]; private int bolusID; private boolean bolusCancelled; + private BasalProfile activeBasalProfile; private List profileBlocks; private boolean limitsFetched; private double maximumBolusAmount; @@ -173,172 +156,149 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con private boolean statusLoaded; private TBROverNotificationBlock tbrOverNotificationBlock; - public static LocalInsightPlugin getPlugin() { - if (instance == null) - instance = new LocalInsightPlugin(); + if (instance == null) instance = new LocalInsightPlugin(); return instance; } - public LocalInsightPlugin() { - super(new PluginDescription().pluginName(R.string.insight_local).shortName(R.string.insightpump_shortname) - .mainType(PluginType.PUMP).description(R.string.description_pump_insight_local) - .fragmentClass(LocalInsightFragment.class.getName()).preferencesId(R.xml.pref_insight_local)); + super(new PluginDescription() + .pluginName(R.string.insight_local) + .shortName(R.string.insightpump_shortname) + .mainType(PluginType.PUMP) + .description(R.string.description_pump_insight_local) + .fragmentClass(LocalInsightFragment.class.getName()) + .preferencesId(R.xml.pref_insight_local)); pumpDescription = new PumpDescription(); pumpDescription.setPumpDescription(PumpType.AccuChekInsight); } - public TBROverNotificationBlock getTBROverNotificationBlock() { return tbrOverNotificationBlock; } - public long getLastUpdated() { return lastUpdated; } - public InsightConnectionService getConnectionService() { return connectionService; } - public OperatingMode getOperatingMode() { return operatingMode; } - public BatteryStatus getBatteryStatus() { return batteryStatus; } - public CartridgeStatus getCartridgeStatus() { return cartridgeStatus; } - public TotalDailyDose getTotalDailyDose() { return totalDailyDose; } - public ActiveBasalRate getActiveBasalRate() { return activeBasalRate; } - public ActiveTBR getActiveTBR() { return activeTBR; } - public List getActiveBoluses() { return activeBoluses; } - @Override protected void onStart() { super.onStart(); - MainApp.instance().bindService(new Intent(MainApp.instance(), InsightConnectionService.class), - serviceConnection, Context.BIND_AUTO_CREATE); - MainApp.instance().bindService(new Intent(MainApp.instance(), InsightAlertService.class), serviceConnection, - Context.BIND_AUTO_CREATE); + MainApp.instance().bindService(new Intent(MainApp.instance(), InsightConnectionService.class), serviceConnection, Context.BIND_AUTO_CREATE); + MainApp.instance().bindService(new Intent(MainApp.instance(), InsightAlertService.class), serviceConnection, Context.BIND_AUTO_CREATE); } - @Override protected void onStop() { super.onStop(); MainApp.instance().unbindService(serviceConnection); } - @Override public boolean isInitialized() { return connectionService != null && alertService != null && connectionService.isPaired(); } - @Override public boolean isSuspended() { return operatingMode != null && operatingMode != OperatingMode.STARTED; } - @Override public boolean isBusy() { return false; } - @Override public boolean isConnected() { - return connectionService != null && alertService != null && connectionService.hasRequestedConnection(this) - && connectionService.getState() == InsightState.CONNECTED; + return connectionService != null + && alertService != null + && connectionService.hasRequestedConnection(this) + && connectionService.getState() == InsightState.CONNECTED; } - @Override public boolean isConnecting() { if (connectionService == null || alertService == null || !connectionService.hasRequestedConnection(this)) return false; InsightState state = connectionService.getState(); - return state == InsightState.CONNECTING || state == InsightState.APP_CONNECT_MESSAGE - || state == InsightState.RECOVERING; + return state == InsightState.CONNECTING + || state == InsightState.APP_CONNECT_MESSAGE + || state == InsightState.RECOVERING; } - @Override public boolean isHandshakeInProgress() { return false; } - @Override public void finishHandshaking() { } - @Override public void connect(String reason) { if (connectionService != null && alertService != null) connectionService.requestConnection(this); } - @Override public void disconnect(String reason) { if (connectionService != null && alertService != null) connectionService.withdrawConnectionRequest(this); } - @Override public void stopConnecting() { if (connectionService != null && alertService != null) connectionService.withdrawConnectionRequest(this); } - @Override public void getPumpStatus() { try { - tbrOverNotificationBlock = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, - TBROverNotificationBlock.class); + tbrOverNotificationBlock = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, TBROverNotificationBlock.class); readHistory(); fetchBasalProfile(); fetchLimitations(); updatePumpTimeIfNeeded(); fetchStatus(); } catch (AppLayerErrorException e) { - log.info("Exception while fetching status: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception while fetching status: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception while fetching status: " + e.getClass().getCanonicalName()); } catch (Exception e) { @@ -346,7 +306,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - private void updatePumpTimeIfNeeded() throws Exception { PumpTime pumpTime = connectionService.requestMessage(new GetDateTimeMessage()).await().getPumpTime(); Calendar calendar = Calendar.getInstance(); @@ -367,23 +326,19 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con SetDateTimeMessage setDateTimeMessage = new SetDateTimeMessage(); setDateTimeMessage.setPumpTime(pumpTime); connectionService.requestMessage(setDateTimeMessage).await(); - Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, - MainApp.gs(R.string.pump_time_updated), Notification.INFO, 60); + Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, MainApp.gs(R.string.pump_time_updated), Notification.INFO, 60); MainApp.bus().post(new EventNewNotification(notification)); } } - private void fetchBasalProfile() throws Exception { - profileBlocks = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, - BRProfile1Block.class).getProfileBlocks(); + activeBasalProfile = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, ActiveBRProfileBlock.class).getActiveBasalProfile(); + profileBlocks = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, BRProfile1Block.class).getProfileBlocks(); } - private void fetchStatus() throws Exception { if (statusLoaded) { - GetPumpStatusRegisterMessage registerMessage = connectionService.requestMessage( - new GetPumpStatusRegisterMessage()).await(); + GetPumpStatusRegisterMessage registerMessage = connectionService.requestMessage(new GetPumpStatusRegisterMessage()).await(); ResetPumpStatusRegisterMessage resetMessage = new ResetPumpStatusRegisterMessage(); resetMessage.setOperatingModeChanged(registerMessage.isOperatingModeChanged()); resetMessage.setBatteryStatusChanged(registerMessage.isBatteryStatusChanged()); @@ -393,25 +348,20 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con resetMessage.setActiveBolusesChanged(registerMessage.isActiveBolusesChanged()); connectionService.requestMessage(resetMessage).await(); if (registerMessage.isOperatingModeChanged()) - operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await() - .getOperatingMode(); + operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await().getOperatingMode(); if (registerMessage.isBatteryStatusChanged()) - batteryStatus = connectionService.requestMessage(new GetBatteryStatusMessage()).await() - .getBatteryStatus(); + batteryStatus = connectionService.requestMessage(new GetBatteryStatusMessage()).await().getBatteryStatus(); if (registerMessage.isCartridgeStatusChanged()) - cartridgeStatus = connectionService.requestMessage(new GetCartridgeStatusMessage()).await() - .getCartridgeStatus(); + cartridgeStatus = connectionService.requestMessage(new GetCartridgeStatusMessage()).await().getCartridgeStatus(); if (registerMessage.isTotalDailyDoseChanged()) totalDailyDose = connectionService.requestMessage(new GetTotalDailyDoseMessage()).await().getTDD(); if (operatingMode == OperatingMode.STARTED) { if (registerMessage.isActiveBasalRateChanged()) - activeBasalRate = connectionService.requestMessage(new GetActiveBasalRateMessage()).await() - .getActiveBasalRate(); + activeBasalRate = connectionService.requestMessage(new GetActiveBasalRateMessage()).await().getActiveBasalRate(); if (registerMessage.isActiveTBRChanged()) activeTBR = connectionService.requestMessage(new GetActiveTBRMessage()).await().getActiveTBR(); if (registerMessage.isActiveBolusesChanged()) - activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await() - .getActiveBoluses(); + activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await().getActiveBoluses(); } else { activeBasalRate = null; activeTBR = null; @@ -430,15 +380,12 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con connectionService.requestMessage(resetMessage).await(); operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await().getOperatingMode(); batteryStatus = connectionService.requestMessage(new GetBatteryStatusMessage()).await().getBatteryStatus(); - cartridgeStatus = connectionService.requestMessage(new GetCartridgeStatusMessage()).await() - .getCartridgeStatus(); + cartridgeStatus = connectionService.requestMessage(new GetCartridgeStatusMessage()).await().getCartridgeStatus(); totalDailyDose = connectionService.requestMessage(new GetTotalDailyDoseMessage()).await().getTDD(); if (operatingMode == OperatingMode.STARTED) { - activeBasalRate = connectionService.requestMessage(new GetActiveBasalRateMessage()).await() - .getActiveBasalRate(); + activeBasalRate = connectionService.requestMessage(new GetActiveBasalRateMessage()).await().getActiveBasalRate(); activeTBR = connectionService.requestMessage(new GetActiveTBRMessage()).await().getActiveTBR(); - activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await() - .getActiveBoluses(); + activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await().getActiveBoluses(); } else { activeBasalRate = null; activeTBR = null; @@ -453,22 +400,16 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con }); } - private void fetchLimitations() throws Exception { - maximumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, - MaxBolusAmountBlock.class).getAmountLimitation(); - maximumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, - MaxBasalAmountBlock.class).getAmountLimitation(); - minimumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, - FactoryMinBolusAmountBlock.class).getAmountLimitation(); - minimumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, - FactoryMinBolusAmountBlock.class).getAmountLimitation(); + maximumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, MaxBolusAmountBlock.class).getAmountLimitation(); + maximumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, MaxBasalAmountBlock.class).getAmountLimitation(); + minimumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBolusAmountBlock.class).getAmountLimitation(); + minimumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBolusAmountBlock.class).getAmountLimitation(); this.pumpDescription.basalMaximumRate = maximumBasalAmount; this.pumpDescription.basalMinimumRate = minimumBasalAmount; limitsFetched = true; } - @Override public PumpEnactResult setNewBasalProfile(Profile profile) { PumpEnactResult result = new PumpEnactResult(); @@ -481,17 +422,19 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con nextValue = profile.getBasalValues()[i + 1]; BasalProfileBlock profileBlock = new BasalProfileBlock(); profileBlock.setBasalAmount(basalValue.value); - profileBlock - .setDuration((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60)); + profileBlock.setDuration((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60)); profileBlocks.add(profileBlock); } try { + ActiveBRProfileBlock activeBRProfileBlock = new ActiveBRProfileBlock(); + activeBRProfileBlock.setActiveBasalProfile(BasalProfile.PROFILE_1); + ParameterBlockUtil.writeConfigurationBlock(connectionService, activeBRProfileBlock); + activeBasalProfile = BasalProfile.PROFILE_1; BRProfileBlock profileBlock = new BRProfile1Block(); profileBlock.setProfileBlocks(profileBlocks); ParameterBlockUtil.writeConfigurationBlock(connectionService, profileBlock); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - 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)); result.success = true; result.enacted = true; @@ -502,43 +445,36 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } catch (Exception ignored) { } } catch (AppLayerErrorException e) { - log.info("Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, - MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + log.info("Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while setting profile: " + e.getClass().getCanonicalName()); - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, - MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = ExceptionTranslator.getString(e); } catch (Exception e) { log.error("Exception while setting profile", e); - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, - MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); result.comment = ExceptionTranslator.getString(e); } return result; } - @Override public boolean isThisProfileSet(Profile profile) { - if (!isInitialized() || profileBlocks == null) - return true; - if (profile.getBasalValues().length != profileBlocks.size()) - return false; + if (!isInitialized() || profileBlocks == null) return true; + if (profile.getBasalValues().length != profileBlocks.size()) return false; + if (activeBasalProfile != BasalProfile.PROFILE_1) return false; for (int i = 0; i < profileBlocks.size(); i++) { BasalProfileBlock profileBlock = profileBlocks.get(i); Profile.BasalValue basalValue = profile.getBasalValues()[i]; Profile.BasalValue nextValue = null; if (profile.getBasalValues().length > i + 1) nextValue = profile.getBasalValues()[i + 1]; - if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - - basalValue.timeAsSeconds) + if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) return false; if (Math.abs(profileBlock.getBasalAmount() - basalValue.value) > 0.01D) return false; @@ -546,42 +482,31 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return true; } - @Override public long lastDataTime() { - if (connectionService == null || alertService == null) - return System.currentTimeMillis(); + if (connectionService == null || alertService == null) return System.currentTimeMillis(); return connectionService.getLastDataTime(); } - @Override public double getBaseBasalRate() { - if (connectionService == null || alertService == null) - return 0; - if (activeBasalRate != null) - return activeBasalRate.getActiveBasalRate(); - else - return 0; + if (connectionService == null || alertService == null) return 0; + if (activeBasalRate != null) return activeBasalRate.getActiveBasalRate(); + else return 0; } - @Override public double getReservoirLevel() { - if (cartridgeStatus == null) - return 0; + if (cartridgeStatus == null) return 0; return cartridgeStatus.getRemainingAmount(); } - @Override public int getBatteryLevel() { - if (batteryStatus == null) - return 0; + if (batteryStatus == null) return 0; return batteryStatus.getBatteryAmount(); } - @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { PumpEnactResult result = new PumpEnactResult(); @@ -617,15 +542,11 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); while (true) { synchronized ($bolusLock) { - if (bolusCancelled) - break; + if (bolusCancelled) break; } - OperatingMode operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()) - .await().getOperatingMode(); - if (operatingMode != OperatingMode.STARTED) - break; - List activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()) - .await().getActiveBoluses(); + OperatingMode operatingMode = connectionService.requestMessage(new GetOperatingModeMessage()).await().getOperatingMode(); + if (operatingMode != OperatingMode.STARTED) break; + List activeBoluses = connectionService.requestMessage(new GetActiveBolusesMessage()).await().getActiveBoluses(); ActiveBolus activeBolus = null; for (ActiveBolus bolus : activeBoluses) { if (bolus.getBolusID() == bolusID) { @@ -636,18 +557,15 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con if (activeBolus != null) { trials = -1; int percentBefore = bolusingEvent.percent; - bolusingEvent.percent = (int)(100D / activeBolus.getInitialAmount() * (activeBolus - .getInitialAmount() - activeBolus.getRemainingAmount())); - bolusingEvent.status = MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount()); + bolusingEvent.percent = (int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount())); + bolusingEvent.status = MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount()); if (percentBefore != bolusingEvent.percent) MainApp.bus().post(bolusingEvent); } else { synchronized ($bolusLock) { if (bolusCancelled || trials == -1 || trials++ >= 5) { if (!bolusCancelled) { - bolusingEvent.status = MainApp.gs(R.string.insight_delivered, - detailedBolusInfo.insulin, detailedBolusInfo.insulin); + bolusingEvent.status = MainApp.gs(R.string.insight_delivered, detailedBolusInfo.insulin, detailedBolusInfo.insulin); bolusingEvent.percent = 100; MainApp.bus().post(bolusingEvent); } @@ -660,8 +578,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con readHistory(); fetchStatus(); } catch (AppLayerErrorException e) { - log.info("Exception while delivering bolus: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception while delivering bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while delivering bolus: " + e.getClass().getCanonicalName()); @@ -678,7 +595,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override public void stopBolusDelivering() { new Thread(() -> { @@ -692,8 +608,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } confirmAlert(AlertType.WARNING_38); } catch (AppLayerErrorException e) { - log.info("Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception while canceling bolus: " + e.getClass().getCanonicalName()); } catch (Exception e) { @@ -702,15 +617,11 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con }).start(); } - @Override - public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, - boolean enforceNew) { + public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); - if (activeBasalRate == null) - return result; - if (activeBasalRate.getActiveBasalRate() == 0) - return result; + if (activeBasalRate == null) return result; + if (activeBasalRate.getActiveBasalRate() == 0) return result; double percent = 100D / activeBasalRate.getActiveBasalRate() * absoluteRate; if (isFakingTempsByExtendedBoluses()) { PumpEnactResult cancelEBResult = cancelExtendedBolusOnly(); @@ -719,7 +630,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); if (cancelTBRResult.success) { PumpEnactResult ebResult = setExtendedBolusOnly((absoluteRate - getBaseBasalRate()) / 60D - * ((double)durationInMinutes), durationInMinutes); + * ((double) durationInMinutes), durationInMinutes); if (ebResult.success) { result.success = true; result.enacted = true; @@ -734,13 +645,13 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.comment = cancelTBRResult.comment; } } else { - return setTempBasalPercent((int)Math.round(percent), durationInMinutes, profile, enforceNew); + return setTempBasalPercent((int) Math.round(percent), durationInMinutes, profile, enforceNew); } } else { result.comment = cancelEBResult.comment; } } else { - return setTempBasalPercent((int)Math.round(percent), durationInMinutes, profile, enforceNew); + return setTempBasalPercent((int) Math.round(percent), durationInMinutes, profile, enforceNew); } try { fetchStatus(); @@ -755,16 +666,12 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, - boolean enforceNew) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); - percent = (int)Math.round(((double)percent) / 10d) * 10; - if (percent == 100) - return cancelTempBasal(true); - else if (percent > 250) - percent = 250; + percent = (int) Math.round(((double) percent) / 10d) * 10; + if (percent == 100) return cancelTempBasal(true); + else if (percent > 250) percent = 250; try { if (activeTBR != null) { ChangeTBRMessage message = new ChangeTBRMessage(); @@ -798,16 +705,15 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { PumpEnactResult result = cancelExtendedBolusOnly(); + if (result.success) result = setExtendedBolusOnly(insulin, durationInMinutes); try { fetchStatus(); readHistory(); } catch (AppLayerErrorException e) { - log.info("Exception after delivering extended bolus: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception after delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception after delivering extended bolus: " + e.getClass().getCanonicalName()); } catch (Exception e) { @@ -816,7 +722,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - public PumpEnactResult setExtendedBolusOnly(Double insulin, Integer durationInMinutes) { PumpEnactResult result = new PumpEnactResult(); try { @@ -842,8 +747,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.enacted = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { - log.info("Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while delivering extended bolus: " + e.getClass().getCanonicalName()); @@ -855,13 +759,11 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); PumpEnactResult cancelEBResult = null; - if (isFakingTempsByExtendedBoluses()) - cancelEBResult = cancelExtendedBolusOnly(); + if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly(); PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); result.success = (cancelEBResult != null && cancelEBResult.success) && cancelTBRResult.success; result.enacted = (cancelEBResult != null && cancelEBResult.enacted) || cancelTBRResult.enacted; @@ -870,8 +772,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con fetchStatus(); readHistory(); } catch (AppLayerErrorException e) { - log.info("Exception after canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception after canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception after canceling TBR: " + e.getClass().getCanonicalName()); } catch (Exception e) { @@ -880,7 +781,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - private PumpEnactResult cancelTempBasalOnly() { PumpEnactResult result = new PumpEnactResult(); try { @@ -896,8 +796,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.success = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { - log.info("Exception while canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception while canceling TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while canceling TBR: " + e.getClass().getCanonicalName()); @@ -909,7 +808,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = cancelExtendedBolusOnly(); @@ -917,8 +815,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con fetchStatus(); readHistory(); } catch (AppLayerErrorException e) { - log.info("Exception after canceling extended bolus: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception after canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception after canceling extended bolus: " + e.getClass().getCanonicalName()); } catch (Exception e) { @@ -927,33 +824,29 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - private PumpEnactResult cancelExtendedBolusOnly() { PumpEnactResult result = new PumpEnactResult(); try { for (ActiveBolus activeBolus : activeBoluses) { - if (activeBolus.getBolusType() == BolusType.EXTENDED - || activeBolus.getBolusType() == BolusType.MULTIWAVE) { + if (activeBolus.getBolusType() == BolusType.EXTENDED || activeBolus.getBolusType() == BolusType.MULTIWAVE) { alertService.ignore(AlertType.WARNING_38); CancelBolusMessage cancelBolusMessage = new CancelBolusMessage(); cancelBolusMessage.setBolusID(activeBolus.getBolusID()); connectionService.requestMessage(cancelBolusMessage).await(); confirmAlert(AlertType.WARNING_38); alertService.ignore(null); - InsightBolusID insightBolusID = MainApp.getDbHelper().getInsightBolusID( - connectionService.getPumpSystemIdentification().getSerialNumber(), activeBolus.getBolusID(), - System.currentTimeMillis()); + InsightBolusID insightBolusID = MainApp.getDbHelper().getInsightBolusID(connectionService.getPumpSystemIdentification().getSerialNumber(), + activeBolus.getBolusID(), System.currentTimeMillis()); if (insightBolusID != null) { ExtendedBolus extendedBolus = MainApp.getDbHelper().getExtendedBolusByPumpId(insightBolusID.id); if (extendedBolus != null) { - extendedBolus.durationInMinutes = (int)((System.currentTimeMillis() - extendedBolus.date) / 60000); + extendedBolus.durationInMinutes = (int) ((System.currentTimeMillis() - extendedBolus.date) / 60000); if (extendedBolus.durationInMinutes <= 0) { ; final String _id = extendedBolus._id; if (NSUpload.isIdValid(_id)) NSUpload.removeCareportalEntryFromNS(_id); - else - UploadQueue.removeID("dbAdd", _id); + else UploadQueue.removeID("dbAdd", _id); MainApp.getDbHelper().delete(extendedBolus); } else TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); @@ -966,8 +859,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.success = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { - log.info("Exception while canceling extended bolus: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception while canceling extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while canceling extended bolus: " + e.getClass().getCanonicalName()); @@ -979,25 +871,21 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - private void confirmAlert(AlertType alertType) { try { long started = System.currentTimeMillis(); while (System.currentTimeMillis() - started < 10000) { - GetActiveAlertMessage activeAlertMessage = connectionService - .requestMessage(new GetActiveAlertMessage()).await(); + GetActiveAlertMessage activeAlertMessage = connectionService.requestMessage(new GetActiveAlertMessage()).await(); if (activeAlertMessage.getAlert() != null) { if (activeAlertMessage.getAlert().getAlertType() == alertType) { ConfirmAlertMessage confirmMessage = new ConfirmAlertMessage(); confirmMessage.setAlertID(activeAlertMessage.getAlert().getAlertId()); connectionService.requestMessage(confirmMessage).await(); - } else - break; + } else break; } } } catch (AppLayerErrorException e) { - log.info("Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception while confirming alert: " + e.getClass().getCanonicalName()); } catch (Exception e) { @@ -1005,7 +893,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); @@ -1054,15 +941,12 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return pump; } - @Override public String deviceID() { - if (connectionService == null || alertService == null) - return null; + if (connectionService == null || alertService == null) return null; return connectionService.getPumpSystemIdentification().getSerialNumber(); } - public PumpEnactResult stopPump() { PumpEnactResult result = new PumpEnactResult(); try { @@ -1074,8 +958,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con fetchStatus(); readHistory(); } catch (AppLayerErrorException e) { - log.info("Exception while stopping pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception while stopping pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while stopping pump: " + e.getClass().getCanonicalName()); @@ -1087,7 +970,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - public PumpEnactResult startPump() { PumpEnactResult result = new PumpEnactResult(); try { @@ -1099,8 +981,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con fetchStatus(); readHistory(); } catch (AppLayerErrorException e) { - log.info("Exception while starting pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception while starting pump: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { log.info("Exception while starting pump: " + e.getClass().getCanonicalName()); @@ -1112,7 +993,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - public PumpEnactResult setTBROverNotification(boolean enabled) { PumpEnactResult result = new PumpEnactResult(); boolean valueBefore = tbrOverNotificationBlock.isEnabled(); @@ -1123,8 +1003,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.enacted = true; } catch (AppLayerErrorException e) { tbrOverNotificationBlock.setEnabled(valueBefore); - log.info("Exception while updating TBR notification block: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception while updating TBR notification block: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment = ExceptionTranslator.getString(e); } catch (InsightException e) { tbrOverNotificationBlock.setEnabled(valueBefore); @@ -1138,36 +1017,28 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return result; } - @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override public String shortStatus(boolean veryShort) { StringBuilder ret = new StringBuilder(); if (connectionService.getLastConnected() != 0) { Long agoMsec = System.currentTimeMillis() - connectionService.getLastConnected(); - int agoMin = (int)(agoMsec / 60d / 1000d); + int agoMin = (int) (agoMsec / 60d / 1000d); ret.append(MainApp.gs(R.string.short_status_last_connected, agoMin) + "\n"); } if (activeTBR != null) { - ret.append(MainApp.gs(R.string.short_status_tbr, activeTBR.getPercentage(), activeTBR.getInitialDuration() - - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()) - + "\n"); + ret.append(MainApp.gs(R.string.short_status_tbr, activeTBR.getPercentage(), + activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()) + "\n"); + } + if (activeBoluses != null) for (ActiveBolus activeBolus : activeBoluses) { + if (activeBolus.getBolusType() == BolusType.STANDARD) continue; + ret.append(MainApp.gs(activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave : R.string.short_status_extended, + activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration()) + "\n"); } - if (activeBoluses != null) - for (ActiveBolus activeBolus : activeBoluses) { - if (activeBolus.getBolusType() == BolusType.STANDARD) - continue; - ret.append(MainApp.gs( - activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave - : R.string.short_status_extended, activeBolus.getRemainingAmount(), activeBolus - .getInitialAmount(), activeBolus.getRemainingDuration()) - + "\n"); - } if (!veryShort && totalDailyDose != null) { ret.append(MainApp.gs(R.string.short_status_tdd, totalDailyDose.getBolusAndBasal()) + "\n"); } @@ -1180,26 +1051,32 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return ret.toString(); } - @Override public boolean isFakingTempsByExtendedBoluses() { return SP.getBoolean("insight_enable_tbr_emulation", false); } - @Override public PumpEnactResult loadTDDs() { return new PumpEnactResult().success(true); } + @Override + public List getCustomActions() { + return null; + } + + @Override + public void executeCustomAction(CustomActionType customActionType) { + + } private void readHistory() { try { PumpTime pumpTime = connectionService.requestMessage(new GetDateTimeMessage()).await().getPumpTime(); String pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); - timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - - parseDate(pumpTime.getYear(), pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), - pumpTime.getMinute(), pumpTime.getSecond()); + timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(), + pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond()); InsightHistoryOffset historyOffset = MainApp.getDbHelper().getInsightHistoryOffset(pumpSerial); try { List historyEvents = new ArrayList<>(); @@ -1208,25 +1085,21 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con startMessage.setDirection(HistoryReadingDirection.BACKWARD); startMessage.setOffset(0xFFFFFFFF); connectionService.requestMessage(startMessage).await(); - historyEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await() - .getHistoryEvents(); + historyEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await().getHistoryEvents(); } else { StartReadingHistoryMessage startMessage = new StartReadingHistoryMessage(); startMessage.setDirection(HistoryReadingDirection.FORWARD); startMessage.setOffset(historyOffset.offset + 1); connectionService.requestMessage(startMessage).await(); while (true) { - List newEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()) - .await().getHistoryEvents(); - if (newEvents.size() == 0) - break; + List newEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await().getHistoryEvents(); + if (newEvents.size() == 0) break; historyEvents.addAll(newEvents); } } Collections.sort(historyEvents); Collections.reverse(historyEvents); - if (historyOffset != null) - processHistoryEvents(pumpSerial, historyEvents); + if (historyOffset != null) processHistoryEvents(pumpSerial, historyEvents); if (historyEvents.size() > 0) { historyOffset = new InsightHistoryOffset(); historyOffset.pumpSerial = pumpSerial; @@ -1234,8 +1107,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con MainApp.getDbHelper().createOrUpdate(historyOffset); } } catch (AppLayerErrorException e) { - log.info("Exception while reading history: " + e.getClass().getCanonicalName() + " (" - + e.getErrorCode() + ")"); + log.info("Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception while reading history: " + e.getClass().getSimpleName()); } catch (Exception e) { @@ -1247,18 +1119,15 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } } catch (AppLayerErrorException e) { - log.info("Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() - + ")"); + log.info("Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); } catch (InsightException e) { log.info("Exception while reading history: " + e.getClass().getSimpleName()); } catch (Exception e) { log.error("Exception while reading history", e); } - new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post( - new EventRefreshOverview("LocalInsightPlugin::readHistory"))); + new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::readHistory"))); } - private void processHistoryEvents(String serial, List historyEvents) { List temporaryBasals = new ArrayList<>(); List pumpStartedEvents = new ArrayList<>(); @@ -1268,11 +1137,10 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con Collections.reverse(temporaryBasals); for (InsightPumpID pumpID : pumpStartedEvents) { InsightPumpID stoppedEvent = MainApp.getDbHelper().getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp); - if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) - continue; + if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue; long tbrStart = stoppedEvent.timestamp + 10000; TemporaryBasal temporaryBasal = new TemporaryBasal(); - temporaryBasal.durationInMinutes = (int)((pumpID.timestamp - tbrStart) / 60000); + temporaryBasal.durationInMinutes = (int) ((pumpID.timestamp - tbrStart) / 60000); temporaryBasal.date = tbrStart; temporaryBasal.source = Source.PUMP; temporaryBasal.pumpId = pumpID.id; @@ -1280,61 +1148,50 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con temporaryBasal.isAbsolute = false; temporaryBasals.add(temporaryBasal); } - Collections.sort(temporaryBasals, (o1, o2) -> (int)(o1.date - o2.date)); + Collections.sort(temporaryBasals, (o1, o2) -> (int) (o1.date - o2.date)); for (TemporaryBasal temporaryBasal : temporaryBasals) TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); } - - private boolean processHistoryEvent(String serial, List temporaryBasals, - List pumpStartedEvents, HistoryEvent event) { - if (event instanceof DefaultDateTimeSetEvent) - return false; + private boolean processHistoryEvent(String serial, List temporaryBasals, List pumpStartedEvents, HistoryEvent event) { + if (event instanceof DefaultDateTimeSetEvent) return false; else if (event instanceof DateTimeChangedEvent) - processDateTimeChangedEvent((DateTimeChangedEvent)event); + processDateTimeChangedEvent((DateTimeChangedEvent) event); else if (event instanceof CannulaFilledEvent) - processCannulaFilledEvent((CannulaFilledEvent)event); + processCannulaFilledEvent((CannulaFilledEvent) event); else if (event instanceof TotalDailyDoseEvent) - processTotalDailyDoseEvent((TotalDailyDoseEvent)event); - else if (event instanceof TubeFilledEvent) - processTubeFilledEvent((TubeFilledEvent)event); + processTotalDailyDoseEvent((TotalDailyDoseEvent) event); + else if (event instanceof TubeFilledEvent) processTubeFilledEvent((TubeFilledEvent) event); else if (event instanceof SniffingDoneEvent) - processSniffingDoneEvent((SniffingDoneEvent)event); - else if (event instanceof PowerUpEvent) - processPowerUpEvent((PowerUpEvent)event); + processSniffingDoneEvent((SniffingDoneEvent) event); + else if (event instanceof PowerUpEvent) processPowerUpEvent((PowerUpEvent) event); else if (event instanceof OperatingModeChangedEvent) - processOperatingModeChangedEvent(serial, pumpStartedEvents, (OperatingModeChangedEvent)event); + processOperatingModeChangedEvent(serial, pumpStartedEvents, (OperatingModeChangedEvent) event); else if (event instanceof StartOfTBREvent) - processStartOfTBREvent(serial, temporaryBasals, (StartOfTBREvent)event); + processStartOfTBREvent(serial, temporaryBasals, (StartOfTBREvent) event); else if (event instanceof EndOfTBREvent) - processEndOfTBREvent(serial, temporaryBasals, (EndOfTBREvent)event); + processEndOfTBREvent(serial, temporaryBasals, (EndOfTBREvent) event); else if (event instanceof BolusProgrammedEvent) - processBolusProgrammedEvent(serial, (BolusProgrammedEvent)event); + processBolusProgrammedEvent(serial, (BolusProgrammedEvent) event); else if (event instanceof BolusDeliveredEvent) - processBolusDeliveredEvent(serial, (BolusDeliveredEvent)event); + processBolusDeliveredEvent(serial, (BolusDeliveredEvent) event); else if (event instanceof OccurrenceOfAlertEvent) - processOccurrenceOfAlertEvent((OccurrenceOfAlertEvent)event); + processOccurrenceOfAlertEvent((OccurrenceOfAlertEvent) event); return true; } - private void processDateTimeChangedEvent(DateTimeChangedEvent event) { - long timeAfter = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()); - long timeBefore = parseDate(event.getBeforeYear(), event.getBeforeMonth(), event.getBeforeDay(), - event.getBeforeHour(), event.getBeforeMinute(), event.getBeforeSecond()); + long timeAfter = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()); + long timeBefore = parseDate(event.getBeforeYear(), event.getBeforeMonth(), event.getBeforeDay(), event.getBeforeHour(), event.getBeforeMinute(), event.getBeforeSecond()); timeOffset -= timeAfter - timeBefore; } - private void processCannulaFilledEvent(CannulaFilledEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, CareportalEvent.SITECHANGE); } - private void processTotalDailyDoseEvent(TotalDailyDoseEvent event) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(0)); @@ -1349,42 +1206,30 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con MainApp.getDbHelper().createOrUpdateTDD(tdd); } - private void processTubeFilledEvent(TubeFilledEvent event) { - if (!SP.getBoolean("insight_log_tube_changes", false)) - return; + if (!SP.getBoolean("insight_log_tube_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; logNote(timestamp, MainApp.gs(R.string.tube_changed)); } - private void processSniffingDoneEvent(SniffingDoneEvent event) { - if (!SP.getBoolean("insight_log_site_changes", false)) - return; + if (!SP.getBoolean("insight_log_site_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, CareportalEvent.INSULINCHANGE); } - private void processPowerUpEvent(PowerUpEvent event) { - if (!SP.getBoolean("insight_log_battery_changes", false)) - return; + if (!SP.getBoolean("insight_log_battery_changes", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, CareportalEvent.PUMPBATTERYCHANGE); } - - private void processOperatingModeChangedEvent(String serial, List pumpStartedEvents, - OperatingModeChangedEvent event) { + private void processOperatingModeChangedEvent(String serial, List pumpStartedEvents, OperatingModeChangedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightPumpID pumpID = new InsightPumpID(); pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; @@ -1410,11 +1255,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con MainApp.getDbHelper().createOrUpdate(pumpID); } - private void processStartOfTBREvent(String serial, List temporaryBasals, StartOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightPumpID pumpID = new InsightPumpID(); pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; @@ -1431,11 +1274,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con temporaryBasals.add(temporaryBasal); } - private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightPumpID pumpID = new InsightPumpID(); pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; @@ -1450,11 +1291,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con temporaryBasals.add(temporaryBasal); } - private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightBolusID bolusID = MainApp.getDbHelper().getInsightBolusID(serial, event.getBolusID(), timestamp); if (bolusID != null && bolusID.endID != null) { bolusID.startID = event.getEventPosition(); @@ -1489,15 +1328,11 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - private void processBolusDeliveredEvent(String serial, BolusDeliveredEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; - long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond(), event.getStartHour(), - event.getStartMinute(), event.getStartSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; + long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), + event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset; InsightBolusID bolusID = MainApp.getDbHelper().getInsightBolusID(serial, event.getBolusID(), timestamp); if (bolusID == null || bolusID.endID != null) { bolusID = new InsightBolusID(); @@ -1520,10 +1355,8 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con ExtendedBolus extendedBolus = MainApp.getDbHelper().getExtendedBolusByPumpId(bolusID.id); if (extendedBolus != null) { final String _id = extendedBolus._id; - if (NSUpload.isIdValid(_id)) - NSUpload.removeCareportalEntryFromNS(_id); - else - UploadQueue.removeID("dbAdd", _id); + if (NSUpload.isIdValid(_id)) NSUpload.removeCareportalEntryFromNS(_id); + else UploadQueue.removeID("dbAdd", _id); MainApp.getDbHelper().delete(extendedBolus); } } else { @@ -1539,13 +1372,10 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - private void processOccurrenceOfAlertEvent(OccurrenceOfAlertEvent event) { - if (!SP.getBoolean("insight_log_alerts", false)) - return; + if (!SP.getBoolean("insight_log_alerts", false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), - event.getEventHour(), event.getEventMinute(), event.getEventSecond()) - + timeOffset; + event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; Integer code = null; Integer title = null; switch (event.getAlertType()) { @@ -1630,7 +1460,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con logNote(timestamp, MainApp.gs(R.string.insight_alert_formatter, MainApp.gs(code), MainApp.gs(title))); } - private long parseDate(int year, int month, int day, int hour, int minute, int second) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.set(Calendar.YEAR, year); @@ -1642,15 +1471,13 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return calendar.getTimeInMillis(); } - private void logNote(long date, String note) { try { if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null) return; JSONObject data = new JSONObject(); String enteredBy = SP.getString("careportal_enteredby", ""); - if (!enteredBy.equals("")) - data.put("enteredBy", enteredBy); + if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", CareportalEvent.NOTE); data.put("notes", note); @@ -1660,9 +1487,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - - private long parseRelativeDate(int year, int month, int day, int hour, int minute, int second, int relativeHour, - int relativeMinute, int relativeSecond) { + private long parseRelativeDate(int year, int month, int day, int hour, int minute, int second, int relativeHour, int relativeMinute, int relativeSecond) { if (relativeHour * 60 * 60 + relativeMinute * 60 + relativeSecond >= hour * 60 * 60 * minute * 60 + second) day--; Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); @@ -1675,15 +1500,13 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con return calendar.getTimeInMillis(); } - private void uploadCareportalEvent(long date, String event) { if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null) return; try { JSONObject data = new JSONObject(); String enteredBy = SP.getString("careportal_enteredby", ""); - if (!enteredBy.equals("")) - data.put("enteredBy", enteredBy); + if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", event); NSUpload.uploadCareportalEntryToNS(data); @@ -1692,48 +1515,33 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } } - @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - percentRate.setIfGreater(0, - String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), - this); - percentRate.setIfSmaller( - getPumpDescription().maxTempPercent, - String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, - MainApp.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this); return percentRate; } - @Override public Constraint applyBolusConstraints(Constraint insulin) { - if (!limitsFetched) - return insulin; - insulin - .setIfSmaller(maximumBolusAmount, - String.format(MainApp.gs(R.string.limitingbolus), maximumBolusAmount, MainApp.gs(R.string.pumplimit)), - this); + if (!limitsFetched) return insulin; + insulin.setIfSmaller(maximumBolusAmount, String.format(MainApp.gs(R.string.limitingbolus), maximumBolusAmount, MainApp.gs(R.string.pumplimit)), this); if (insulin.value() < minimumBolusAmount) { - // TODO: Add function to Constraints or use different approach + //TODO: Add function to Constraints or use different approach // This only works if the interface of the InsightPlugin is called last. // If not, another constraint could theoretically set the value between 0 and minimumBolusAmount - insulin.set(0d, - String.format(MainApp.gs(R.string.limitingbolus), minimumBolusAmount, MainApp.gs(R.string.pumplimit)), - this); + insulin.set(0d, String.format(MainApp.gs(R.string.limitingbolus), minimumBolusAmount, MainApp.gs(R.string.pumplimit)), this); } return insulin; } - @Override public void onStateChanged(InsightState state) { if (state == InsightState.CONNECTED) { statusLoaded = false; - new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post( - new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE))); + new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE))); } else if (state == InsightState.NOT_PAIRED) { connectionService.withdrawConnectionRequest(this); statusLoaded = false; @@ -1746,35 +1554,24 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con activeTBR = null; activeBoluses = null; tbrOverNotificationBlock = null; - new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post( - new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); + new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); } new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventLocalInsightUpdateGUI())); } - @Override public void onPumpPaired() { ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Pump paired", null); } - @Override public void onTimeoutDuringHandshake() { - Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, - MainApp.gs(R.string.timeout_during_handshake), Notification.URGENT); + Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, MainApp.gs(R.string.timeout_during_handshake), Notification.URGENT); new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventNewNotification(notification))); } - @Override - public List getCustomActions() { - return null; + public boolean canHandleDST() { + return true; } - - - @Override - public PumpEnactResult executeCustomAction(CustomActionType customActionType) { - return null; - } -} +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java index 47220fc1e3..89d1184581 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java @@ -1,12 +1,12 @@ package info.nightscout.androidaps.plugins.pump.mdi; -import java.util.List; - import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -24,16 +24,15 @@ import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; + /** * Created by mike on 05.08.2016. */ public class MDIPlugin extends PluginBase implements PumpInterface { - private static Logger log = LoggerFactory.getLogger(MDIPlugin.class); private static MDIPlugin plugin = null; - public static MDIPlugin getPlugin() { if (plugin == null) plugin = new MDIPlugin(); @@ -42,10 +41,12 @@ public class MDIPlugin extends PluginBase implements PumpInterface { private PumpDescription pumpDescription = new PumpDescription(); - private MDIPlugin() { - super(new PluginDescription().mainType(PluginType.PUMP).pluginName(R.string.mdi) - .description(R.string.description_pump_mdi)); + super(new PluginDescription() + .mainType(PluginType.PUMP) + .pluginName(R.string.mdi) + .description(R.string.description_pump_mdi) + ); pumpDescription.isBolusCapable = true; pumpDescription.bolusStep = 0.5d; @@ -55,82 +56,68 @@ public class MDIPlugin extends PluginBase implements PumpInterface { pumpDescription.isRefillingCapable = false; } - @Override public boolean isFakingTempsByExtendedBoluses() { return false; } - @Override public PumpEnactResult loadTDDs() { - // no result, could read DB in the future? + //no result, could read DB in the future? PumpEnactResult result = new PumpEnactResult(); return result; } - @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) { } - @Override public void disconnect(String reason) { } - @Override public void stopConnecting() { } - @Override public void getPumpStatus() { } - @Override public PumpEnactResult setNewBasalProfile(Profile profile) { // Do nothing here. we are using ConfigBuilderPlugin.getPlugin().getActiveProfile().getProfile(); @@ -139,36 +126,26 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override public boolean isThisProfileSet(Profile profile) { return false; } - @Override public long lastDataTime() { return System.currentTimeMillis(); } - @Override public double getBaseBasalRate() { return 0d; } + @Override + public double getReservoirLevel() { return -1; } @Override - public double getReservoirLevel() { - return -1; - } - - - @Override - public int getBatteryLevel() { - return -1; - } - + public int getBatteryLevel() { return -1; } @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { @@ -181,15 +158,12 @@ public class MDIPlugin extends PluginBase implements PumpInterface { 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) { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); @@ -198,10 +172,8 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, - boolean enforceNew) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); @@ -210,7 +182,6 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { PumpEnactResult result = new PumpEnactResult(); @@ -221,7 +192,6 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override public PumpEnactResult cancelTempBasal(boolean force) { PumpEnactResult result = new PumpEnactResult(); @@ -232,7 +202,6 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); @@ -243,7 +212,6 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return result; } - @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); @@ -267,33 +235,34 @@ public class MDIPlugin extends PluginBase implements PumpInterface { return pump; } - @Override public String deviceID() { return "MDI"; } - @Override public PumpDescription getPumpDescription() { return pumpDescription; } - @Override public String shortStatus(boolean veryShort) { return deviceID(); } - @Override public List getCustomActions() { return null; } + @Override + public void executeCustomAction(CustomActionType customActionType) { + + } @Override - public PumpEnactResult executeCustomAction(CustomActionType customActionType) { - return null; + public boolean canHandleDST() { + return true; } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java index b03847182c..0b764f5382 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java @@ -20,11 +20,14 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; +import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.FabricPrivacy; + public class VirtualPumpFragment extends SubscriberFragment { private static Logger log = LoggerFactory.getLogger(VirtualPumpFragment.class); @@ -119,4 +122,6 @@ public class VirtualPumpFragment extends SubscriberFragment { } }); } + + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java index 1615d9c794..461f71c31d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java @@ -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,74 +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? + //no result, could read DB in the future? return new PumpEnactResult(); } + @Override + public List 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) @@ -198,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(); @@ -251,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) { @@ -278,7 +262,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { SystemClock.sleep(200); EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), delivering); - bolusingEvent.percent = Math.min((int)(delivering / detailedBolusInfo.insulin * 100), 100); + bolusingEvent.percent = Math.min((int) (delivering / detailedBolusInfo.insulin * 100), 100); MainApp.bus().post(bolusingEvent); delivering += 0.1d; } @@ -289,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; @@ -324,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; @@ -346,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; @@ -369,7 +355,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { return result; } - @Override public PumpEnactResult cancelTempBasal(boolean force) { PumpEnactResult result = new PumpEnactResult(); @@ -380,7 +365,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { result.enacted = true; TemporaryBasal tempStop = new TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); - // tempBasal = null; + //tempBasal = null; if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling temp basal: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); @@ -389,7 +374,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { return result; } - @Override public PumpEnactResult cancelExtendedBolus() { PumpEnactResult result = new PumpEnactResult(); @@ -409,7 +393,6 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { return result; } - @Override public JSONObject getJSONStatus(Profile profile, String profileName) { long now = System.currentTimeMillis(); @@ -453,29 +436,30 @@ 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; + } + public void refreshConfiguration() { String pumptype = SP.getString(R.string.key_virtualpump_type, "Generic AAPS"); @@ -497,15 +481,4 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { } - - @Override - public List getCustomActions() { - return null; - } - - - @Override - public PumpEnactResult executeCustomAction(CustomActionType customActionType) { - return null; - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java index 09e85b2417..211cbb0bb0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java @@ -21,10 +21,10 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; @@ -67,7 +67,7 @@ public class BGSourceFragment extends SubscriberFragment { } @Subscribe - public void onStatusEvent(final EventNewBG unused) { + public void onStatusEvent(final EventAutosensCalculationFinished unused) { updateGUI(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java index 083b63c924..64e93f3f95 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java @@ -28,12 +28,12 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.dialogs.WizardInfoDialog; @@ -266,7 +266,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. } @Subscribe - public void onStatusEvent(final EventNewBG ev) { + public void onStatusEvent(final EventAutosensCalculationFinished ev) { updateGUI(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java index dbbf59311c..93f2a64006 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -25,14 +25,14 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { @@ -186,7 +186,7 @@ public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { } @Subscribe - public void onStatusEvent(final EventNewBG ev) { + public void onStatusEvent(final EventAutosensCalculationFinished ev) { updateGUI(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java index dbb6ff99d7..b928263ed5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -25,16 +25,16 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { @@ -212,7 +212,7 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { } @Subscribe - public void onStatusEvent(final EventNewBG ignored) { + public void onStatusEvent(final EventAutosensCalculationFinished ignored) { updateGUI(); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java b/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java index 943de83cef..7cc4424244 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java @@ -182,4 +182,9 @@ public class DateUtil { public static long roundDateToSec(long date) { return date - date % 1000; } + + public static boolean isCloseToNow(long date) { + long diff = Math.abs(date - now()); + return diff < T.mins(2).msecs(); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/MidnightTime.java b/app/src/main/java/info/nightscout/androidaps/utils/MidnightTime.java index d3d75feda3..668ca02e96 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/MidnightTime.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/MidnightTime.java @@ -5,7 +5,7 @@ import android.util.LongSparseArray; import java.util.Calendar; public class MidnightTime { - private static LongSparseArray times = new LongSparseArray(); + private static final LongSparseArray times = new LongSparseArray<>(); private static long hits = 0; private static long misses = 0; @@ -20,20 +20,23 @@ public class MidnightTime { } public static long calc(long time) { - Long m = (Long) times.get(time); - if (m != null) { - ++hits; - return m; + Long m; + synchronized (times) { + m = times.get(time); + if (m != null) { + ++hits; + return m; + } + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(time); + c.set(Calendar.HOUR_OF_DAY, 0); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + m = c.getTimeInMillis(); + times.append(time, m); + ++misses; } - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(time); - c.set(Calendar.HOUR_OF_DAY, 0); - c.set(Calendar.MINUTE, 0); - c.set(Calendar.SECOND, 0); - c.set(Calendar.MILLISECOND, 0); - m = c.getTimeInMillis(); - times.append(time, m); - ++misses; return m; } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/VersionChecker.java b/app/src/main/java/info/nightscout/androidaps/utils/VersionChecker.java index ea5c15cbec..fd636b4596 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/VersionChecker.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/VersionChecker.java @@ -43,7 +43,6 @@ public class VersionChecker { if (inputStream != null) { String result = findLine(inputStream); if (result != null) { - result = result.replace("version", "").replace("\"", "").replace("\\s+", "").trim(); int compare = result.compareTo(BuildConfig.VERSION_NAME.replace("\"", "")); if (compare == 0) { log.debug("Version equal to master"); @@ -75,14 +74,14 @@ public class VersionChecker { private static String findLine(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; - String regex = "(.*)version(.*)\"(\\d+)\\.(\\d+)\"(.*)"; + String regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)"; Pattern p = Pattern.compile(regex); while ((line = bufferedReader.readLine()) != null) { Matcher m = p.matcher(line); if (m.matches()) { log.debug("+++ " + line); - return line; + return m.group(3); } else { log.debug("--- " + line); } diff --git a/app/src/main/res/layout/objectives_item.xml b/app/src/main/res/layout/objectives_item.xml index b6029e5842..283195db23 100644 --- a/app/src/main/res/layout/objectives_item.xml +++ b/app/src/main/res/layout/objectives_item.xml @@ -65,6 +65,13 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/objectives_button_start" /> + +