Changes after merge, compilable, but medtronic is still in old structure.

This commit is contained in:
Andy Rozman 2019-03-02 20:24:53 +00:00
parent 289902633e
commit f7395c7a2c
78 changed files with 2333 additions and 1207 deletions

View file

@ -64,7 +64,7 @@ android {
multiDexEnabled true
versionCode 1500
// dev_version: 2.1
version "medtronic-0.7"
version "medtronic-0.8.0"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
@ -105,7 +105,7 @@ android {
resValue "string", "app_name", "AndroidAPS"
versionName version + "-pumpcontrol"
manifestPlaceholders = [
appIcon: "@mipmap/ic_launcher",
appIcon : "@mipmap/ic_launcher",
appIconRound: "@mipmap/ic_launcher_round"
]
}
@ -115,7 +115,7 @@ android {
resValue "string", "app_name", "Pumpcontrol"
versionName version
manifestPlaceholders = [
appIcon: "@mipmap/ic_pumpcontrol",
appIcon : "@mipmap/ic_pumpcontrol",
appIconRound: "@null"
]
}
@ -125,7 +125,7 @@ android {
resValue "string", "app_name", "NSClient"
versionName version + "-nsclient"
manifestPlaceholders = [
appIcon: "@mipmap/ic_yellowowl",
appIcon : "@mipmap/ic_yellowowl",
appIconRound: "@null"
]
}
@ -135,7 +135,7 @@ android {
resValue "string", "app_name", "NSClient2"
versionName version + "-nsclient"
manifestPlaceholders = [
appIcon: "@mipmap/ic_yellowowl",
appIcon : "@mipmap/ic_yellowowl",
appIconRound: "@null"
]
}
@ -150,7 +150,7 @@ android {
unitTests.includeAndroidResources = true
}
useLibrary "org.apache.http.legacy"
useLibrary "org.apache.http.legacy"
}
allprojects {

View file

@ -38,6 +38,7 @@
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@ -52,7 +53,7 @@
android:name=".plugins.general.overview.Dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".plugins.Overview.Dialogs.MessageHelperActivity"
android:name=".plugins.general.overview.Dialogs.MessageHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".activities.AgreementActivity" />

View file

@ -1,12 +1,25 @@
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;
@ -15,20 +28,16 @@ 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;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.PumpMedtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
@ -85,11 +94,11 @@ import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import io.fabric.sdk.android.Fabric;
import info.nightscout.utils.SP;
public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(L.CORE);
private static KeepAliveReceiver keepAliveReceiver;
@ -112,6 +121,7 @@ public class MainApp extends Application {
public static boolean devBranch;
public static boolean engineeringMode;
@Override
public void onCreate() {
super.onCreate();
@ -153,7 +163,8 @@ public class MainApp extends Application {
// 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());
@ -161,28 +172,43 @@ 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());
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(ComboPlugin.getPlugin());
if (Config.MDI)
pluginsList.add(MDIPlugin.getPlugin());
if (Config.PUMPDRIVERS && engineeringMode) {
pluginsList.add(MedtronicPumpPlugin.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.APS)
pluginsList.add(ObjectivesPlugin.getPlugin());
pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin());
pluginsList.add(SourceMM640gPlugin.getPlugin());
@ -192,7 +218,8 @@ 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));
@ -220,6 +247,7 @@ public class MainApp extends Application {
}
}
private void registerLocalBroadcastReceiver() {
lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT));
@ -235,16 +263,16 @@ 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));
}
@ -254,7 +282,7 @@ public class MainApp extends Application {
// SP.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, null);
SP.remove(MedtronicConst.Statistics.LastPumpHistoryEntry); // FIXME remove
//SP.putString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)");
// 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() {
@ -294,11 +322,13 @@ public class MainApp extends Application {
}
}
public void stopKeepAliveService() {
if (keepAliveReceiver != null)
KeepAliveReceiver.cancelAlarm(this);
}
public static void subscribe(Object subscriber) {
try {
bus().register(subscriber);
@ -307,6 +337,7 @@ public class MainApp extends Application {
}
}
public static void unsubscribe(Object subscriber) {
try {
bus().unregister(subscriber);
@ -315,34 +346,42 @@ 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();
@ -350,14 +389,17 @@ public class MainApp extends Application {
}
}
public static ConstraintChecker getConstraintChecker() {
return sConstraintsChecker;
}
public static ArrayList<PluginBase> getPluginsList() {
return pluginsList;
}
public static ArrayList<PluginBase> getSpecificPluginsList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
@ -372,6 +414,7 @@ public class MainApp extends Application {
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
@ -387,6 +430,7 @@ public class MainApp extends Application {
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList<PluginBase> newList = new ArrayList<>();
@ -401,6 +445,7 @@ public class MainApp extends Application {
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
@ -416,12 +461,13 @@ public class MainApp extends Application {
return newList;
}
@Nullable
public static <T extends PluginBase> T getSpecificPlugin(Class<T> pluginClass) {
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (pluginClass.isAssignableFrom(p.getClass()))
return (T) p;
return (T)p;
}
} else {
log.error("pluginsList=null");
@ -429,16 +475,26 @@ 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;
@ -448,6 +504,7 @@ public class MainApp extends Application {
return R.mipmap.ic_launcher;
}
public static int getNotificationIcon() {
if (Config.NSCLIENT)
return R.drawable.ic_notif_nsclient;
@ -457,6 +514,7 @@ public class MainApp extends Application {
return R.drawable.ic_notif_aaps;
}
@Override
public void onTerminate() {
if (L.isEnabled(L.CORE))

View file

@ -19,14 +19,18 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.PumpMedtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
@ -38,17 +42,16 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.SP;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
MyPreferenceFragment myPreferenceFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -60,6 +63,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
MainApp.bus().post(new EventPreferenceChange(key));
@ -67,41 +71,46 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
String lang = sharedPreferences.getString("language", "en");
LocaleHelper.setLocale(getApplicationContext(), lang);
MainApp.bus().post(new EventRefreshGui(true));
//recreate() does not update language so better close settings
// recreate() does not update language so better close settings
finish();
}
if (key.equals("short_tabtitles")) {
MainApp.bus().post(new EventRefreshGui());
}
if (key.equals(MainApp.gs(R.string.key_openapsama_useautosens)) && SP.getBoolean(R.string.key_openapsama_useautosens, false)) {
OKDialog.show(this, MainApp.gs(R.string.configbuilder_sensitivity), MainApp.gs(R.string.sensitivity_warning), null);
if (key.equals(MainApp.gs(R.string.key_openapsama_useautosens))
&& SP.getBoolean(R.string.key_openapsama_useautosens, false)) {
OKDialog.show(this, MainApp.gs(R.string.configbuilder_sensitivity),
MainApp.gs(R.string.sensitivity_warning), null);
}
updatePrefSummary(myPreferenceFragment.getPreference(key));
}
private static void updatePrefSummary(Preference pref) {
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
ListPreference listPref = (ListPreference)pref;
pref.setSummary(listPref.getEntry());
}
if (pref instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
EditTextPreference editTextPref = (EditTextPreference)pref;
if (pref.getKey().contains("password") || pref.getKey().contains("secret")) {
pref.setSummary("******");
} else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) {
pref.setSummary(SP.getString(R.string.key_danars_name, ""));
} else if (editTextPref.getText() != null) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
((EditTextPreference)pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText());
} else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) {
} else if (pref.getKey().contains("smscommunicator_allowednumbers")
&& TextUtils.isEmpty(editTextPref.getText().trim())) {
pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary));
}
}
}
public static void initSummary(Preference p) {
if (p instanceof PreferenceGroup) {
PreferenceGroup pGrp = (PreferenceGroup) p;
PreferenceGroup pGrp = (PreferenceGroup)p;
for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
initSummary(pGrp.getPreference(i));
}
@ -111,19 +120,23 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
}
public static class MyPreferenceFragment extends PreferenceFragment {
private Integer id;
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
id = args.getInt("id");
}
void addPreferencesFromResourceIfEnabled(PluginBase p, PluginType type) {
if (p.isEnabled(type) && p.getPreferencesId() != -1)
addPreferencesFromResource(p.getPreferencesId());
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -155,7 +168,8 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
}
addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(),
PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY);
@ -169,9 +183,9 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP);
if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) {
|| DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) {
addPreferencesFromResource(R.xml.pref_danarprofile);
}
}
@ -195,10 +209,14 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
if (Config.NSCLIENT) {
PreferenceScreen scrnAdvancedSettings = (PreferenceScreen)findPreference(getString(R.string.key_advancedsettings));
if (scrnAdvancedSettings != null) {
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_warning)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_critical)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_warning)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_critical)));
scrnAdvancedSettings
.removePreference(getPreference(getString(R.string.key_statuslights_res_warning)));
scrnAdvancedSettings
.removePreference(getPreference(getString(R.string.key_statuslights_res_critical)));
scrnAdvancedSettings
.removePreference(getPreference(getString(R.string.key_statuslights_bat_warning)));
scrnAdvancedSettings
.removePreference(getPreference(getString(R.string.key_statuslights_bat_critical)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights)));
}
}
@ -206,12 +224,14 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
initSummary(getPreferenceScreen());
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("id", id);
}
public Preference getPreference(String key) {
return findPreference(key);
}

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps.interfaces;
import org.json.JSONObject;
import java.util.List;
import org.json.JSONObject;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.plugins.Actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.Actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
/**
* Created by mike on 04.06.2016.
@ -16,57 +16,105 @@ import info.nightscout.androidaps.plugins.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();
List<CustomAction> getCustomActions();
PumpEnactResult executeCustomAction(CustomActionType customActionType);
}

View file

@ -28,14 +28,14 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.PumpCommon.data.PumpStatus;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
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.DecimalFormatter;
/**
* Created by andy on 23.04.18.

View file

@ -49,7 +49,7 @@ import info.nightscout.androidaps.plugins.PumpCommon.utils.LocationHelper;
import info.nightscout.androidaps.plugins.PumpMedtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.PumpMedtronic.events.EventMedtronicPumpConfigurationChanged;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
// IMPORTANT: This activity needs to be called from RileyLinkSelectPreference (see pref_medtronic.xml as example)
public class RileyLinkBLEScanActivity extends AppCompatActivity {

View file

@ -5,7 +5,6 @@ import org.slf4j.LoggerFactory;
import android.content.Context;
import info.nightscout.androidaps.plugins.PumpCommon.data.PumpStatus;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.ble.RFSpy;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.ble.RileyLinkCommunicationException;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.ble.data.FrequencyScanResults;
@ -22,7 +21,8 @@ import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.
import info.nightscout.androidaps.plugins.PumpCommon.utils.ByteUtil;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.utils.SP;
/**
* This is abstract class for RileyLink Communication, this one needs to be extended by specific "Pump" class.

View file

@ -37,6 +37,7 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
TextView pumpFrequency;
TextView lastUsedFrequency;
TextView lastDeviceContact;
TextView firmwareVersion;
RileyLinkServiceData rileyLinkServiceData;
@ -67,12 +68,13 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
this.pumpFrequency = getActivity().findViewById(R.id.rls_t1_pump_frequency);
this.lastUsedFrequency = getActivity().findViewById(R.id.rls_t1_last_used_frequency);
this.lastDeviceContact = getActivity().findViewById(R.id.rls_t1_last_device_contact);
this.firmwareVersion = getActivity().findViewById(R.id.rls_t1_firmware_version);
if (!first) {
// 7-12
int[] ids = { R.id.rls_t1_tv02, R.id.rls_t1_tv03, R.id.rls_t1_tv04, R.id.rls_t1_tv05, R.id.rls_t1_tv07, //
R.id.rls_t1_tv08, R.id.rls_t1_tv09, R.id.rls_t1_tv10, R.id.rls_t1_tv11, R.id.rls_t1_tv12 };
R.id.rls_t1_tv08, R.id.rls_t1_tv09, R.id.rls_t1_tv10, R.id.rls_t1_tv11, R.id.rls_t1_tv12, R.id.rls_t1_tv13 };
for (int id : ids) {
@ -97,6 +99,9 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
"-"
: MainApp.gs(rileyLinkServiceData.errorCode.getResourceId(targetDevice)));
this.firmwareVersion.setText("BLE113: " + rileyLinkServiceData.versionBLE113 + "\nCC110: "
+ rileyLinkServiceData.versionCC110.toString());
// TODO add handling for Omnipod pump status
this.medtronicPumpStatus = MedtronicUtil.getPumpStatus();

View file

@ -29,7 +29,7 @@ import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.ServiceTask;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.ServiceTaskExecutor;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.WakeAndTuneTask;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
/**
* I added this class outside of RileyLinkService, because for now it's very important part of RL framework and

View file

@ -24,7 +24,7 @@ import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.data.S
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.data.ServiceTransport;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
/**
* Created by andy on 5/6/18.

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.defs.RileyLink
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.defs.RileyLinkTargetDevice;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.data.ServiceTransport;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
/**
* Created by geoff on 7/9/16.

View file

@ -7,7 +7,7 @@ import android.util.AttributeSet;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
/**
* Created by andy on 10/18/18.

View file

@ -5,6 +5,7 @@ package info.nightscout.androidaps.plugins.PumpCommon.utils;
*/
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.joda.time.LocalDateTime;
@ -103,6 +104,21 @@ public class DateTimeUtil {
}
public static long toATechDate(Date date) {
long atechDateTime = 0L;
atechDateTime += date.getYear() * 10000000000L;
atechDateTime += date.getMonth() * 100000000L;
atechDateTime += date.getDay() * 1000000L;
atechDateTime += date.getHours() * 10000L;
atechDateTime += date.getMinutes() * 100L;
atechDateTime += date.getSeconds();
return atechDateTime;
}
public static String toString(long atechDateTime) {
int year = (int)(atechDateTime / 10000000000L);
atechDateTime -= year * 10000000000L;
@ -136,4 +152,44 @@ public class DateTimeUtil {
int year = (int)(atechDateTime / 10000000000L);
return year;
}
public static boolean isSameDayATDAndMillis(long atechDateTime, long date) {
Date dt = new Date(date);
long entryDate = toATechDate(dt);
return (isSameDay(atechDateTime, entryDate));
}
public static long toMillisFromATD(long atechDateTime) {
int year = (int)(atechDateTime / 10000000000L);
atechDateTime -= year * 10000000000L;
int month = (int)(atechDateTime / 100000000L);
atechDateTime -= month * 100000000L;
int dayOfMonth = (int)(atechDateTime / 1000000L);
atechDateTime -= dayOfMonth * 1000000L;
int hourOfDay = (int)(atechDateTime / 10000L);
atechDateTime -= hourOfDay * 10000L;
int minute = (int)(atechDateTime / 100L);
atechDateTime -= minute * 100L;
int second = (int)atechDateTime;
Date d = new Date();
d.setDate(dayOfMonth);
d.setMonth(month - 1);
d.setYear(year);
d.setHours(hourOfDay);
d.setMinutes(minute);
d.setSeconds(second);
return d.getTime();
}
}

View file

@ -7,7 +7,7 @@ import com.crashlytics.android.answers.CustomEvent;
import com.google.common.base.Splitter;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.FabricPrivacy;
/**
* Created by andy on 10/26/18.

View file

@ -31,8 +31,6 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.defs.RileyLinkError;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.defs.RileyLinkServiceState;
@ -46,12 +44,14 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.events.EventMedtronicDev
import info.nightscout.androidaps.plugins.PumpMedtronic.events.EventMedtronicPumpConfigurationChanged;
import info.nightscout.androidaps.plugins.PumpMedtronic.events.EventMedtronicPumpValuesChanged;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.events.EventQueueChanged;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SetWarnColor;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.SetWarnColor;
public class MedtronicFragment extends SubscriberFragment {

View file

@ -30,20 +30,14 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventRefreshOverview;
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.Actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.Actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.MessageHelperActivity;
import info.nightscout.androidaps.plugins.PumpCommon.PumpPluginAbstract;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.defs.RileyLinkServiceState;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.ServiceTaskExecutor;
@ -68,9 +62,14 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.events.EventMedtronicPum
import info.nightscout.androidaps.plugins.PumpMedtronic.service.RileyLinkMedtronicService;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.overview.Dialogs.MessageHelperActivity;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
/**
* Created by andy on 23.04.18.
@ -97,18 +96,18 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
public static Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
public static Gson gsonInstancePretty = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting().create();
.setPrettyPrinting().create();
private MedtronicPumpPlugin() {
super(new PluginDescription() //
.mainType(PluginType.PUMP) //
.fragmentClass(MedtronicFragment.class.getName()) //
.pluginName(R.string.medtronic_name) //
.shortName(R.string.medtronic_name_short) //
.preferencesId(R.xml.pref_medtronic).description(R.string.description_pump_medtronic), //
PumpType.Medtronic_522_722 // we default to most basic model, correct model from config is loaded later
.mainType(PluginType.PUMP) //
.fragmentClass(MedtronicFragment.class.getName()) //
.pluginName(R.string.medtronic_name) //
.shortName(R.string.medtronic_name_short) //
.preferencesId(R.xml.pref_medtronic).description(R.string.description_pump_medtronic), //
PumpType.Medtronic_522_722 // we default to most basic model, correct model from config is loaded later
);
// TODO remove this later
@ -130,7 +129,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
public void onServiceConnected(ComponentName name, IBinder service) {
if (isLoggingEnabled())
LOG.debug("RileyLinkMedtronicService is connected");
RileyLinkMedtronicService.LocalBinder mLocalBinder = (RileyLinkMedtronicService.LocalBinder) service;
RileyLinkMedtronicService.LocalBinder mLocalBinder = (RileyLinkMedtronicService.LocalBinder)service;
medtronicService = mLocalBinder.getServiceInstance();
new Thread(() -> {
@ -219,7 +218,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (this.isInitialized) {
Map<MedtronicStatusRefreshType, Long> statusRefresh = workWithStatusRefresh(
StatusRefreshAction.GetData, null, null);
StatusRefreshAction.GetData, null, null);
if (doWeHaveAnyStatusNeededRefereshing(statusRefresh)) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Scheduled Status Refresh", null);
@ -325,8 +324,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
RileyLinkServiceState rileyLinkServiceState = MedtronicUtil.getServiceState();
if (rileyLinkServiceState != RileyLinkServiceState.PumpConnectorReady //
&& rileyLinkServiceState != RileyLinkServiceState.RileyLinkReady //
&& rileyLinkServiceState != RileyLinkServiceState.TuneUpDevice) {
&& rileyLinkServiceState != RileyLinkServiceState.RileyLinkReady //
&& rileyLinkServiceState != RileyLinkServiceState.TuneUpDevice) {
if (isLoggingEnabled())
LOG.error("RileyLink unreachable.");
return false;
@ -339,7 +338,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private void refreshAnyStatusThatNeedsToBeRefreshed() {
Map<MedtronicStatusRefreshType, Long> statusRefresh = workWithStatusRefresh(StatusRefreshAction.GetData, null,
null);
null);
if (!doWeHaveAnyStatusNeededRefereshing(statusRefresh)) {
return;
@ -368,7 +367,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
case PumpHistory: {
readPumpHistory();
}
break;
break;
case PumpTime:
case BatteryStatus:
@ -377,13 +376,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
refreshTypesNeededToReschedule.add(refreshType.getKey());
resetTime = true;
}
break;
break;
case Configuration: {
medtronicUIComm.executeCommand(refreshType.getKey().getCommandType());
resetTime = true;
}
break;
break;
}
}
}
@ -499,9 +498,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
}
FabricPrivacy.getInstance().logCustom( //
new CustomEvent("MedtronicInitializePump") //
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) //
.putCustomAttribute("version", BuildConfig.VERSION));
new CustomEvent("MedtronicInitializePump") //
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) //
.putCustomAttribute("version", BuildConfig.VERSION));
isInitialized = true;
// this.pumpState = PumpDriverState.Initialized;
@ -526,7 +525,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// LOG.info("isThisProfileSet: check");
LOG.info("isThisProfileSet: check [basalProfileChanged={}, basalByHourSet={}, isBasalProfileInvalid={}",
basalProfileChanged, getMDTPumpStatus().basalsByHour != null, isBasalProfileInvalid);
basalProfileChanged, getMDTPumpStatus().basalsByHour != null, isBasalProfileInvalid);
if (!basalProfileChanged && getMDTPumpStatus().basalsByHour != null && !isBasalProfileInvalid) {
if (isLoggingEnabled())
@ -602,7 +601,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (isLoggingEnabled())
LOG.debug("Current Basals (h): "
+ (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour)));
+ (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour)));
int index = 0;
@ -656,11 +655,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return getMDTPumpStatus().getBasalProfileForHour();
}
@Override
public double getReservoirLevel() {
return getMDTPumpStatus().reservoirRemainingUnits;
}
@Override
public int getBatteryLevel() {
return getMDTPumpStatus().batteryRemaining;
@ -734,9 +735,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// LOG.debug("MedtronicPumpPlugin::deliverBolus - Start delivery");
MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetBolus,
detailedBolusInfo.insulin);
detailedBolusInfo.insulin);
Boolean response = (Boolean) responseTask.returnData;
Boolean response = (Boolean)responseTask.returnData;
setRefreshButtonEnabled(true);
@ -770,18 +771,18 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
getMDTPumpStatus().reservoirRemainingUnits -= detailedBolusInfo.insulin;
incrementStatistics(detailedBolusInfo.isSMB ? MedtronicConst.Statistics.SMBBoluses
: MedtronicConst.Statistics.StandardBoluses);
: MedtronicConst.Statistics.StandardBoluses);
return new PumpEnactResult().success(response) //
.enacted(response) //
.bolusDelivered(detailedBolusInfo.insulin) //
.carbsDelivered(detailedBolusInfo.carbs);
.enacted(response) //
.bolusDelivered(detailedBolusInfo.insulin) //
.carbsDelivered(detailedBolusInfo.carbs);
} else {
return new PumpEnactResult() //
.success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered));
.success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered));
}
} finally {
@ -801,13 +802,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (success) {
return new PumpEnactResult() //
.success(true) //
.enacted(false);
.success(true) //
.enacted(false);
} else {
return new PumpEnactResult() //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
}
}
@ -832,7 +833,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// if false and the same rate is requested enacted=false and success=true is returned and TBR is not changed
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile,
boolean enforceNew) {
boolean enforceNew) {
setRefreshButtonEnabled(false);
@ -841,9 +842,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
setRefreshButtonEnabled(true);
return new PumpEnactResult() //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
}
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable);
@ -861,11 +862,11 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
LOG.warn(getLogPrefix() + "setTempBasalAbsolute - Could not read current TBR, canceling operation.");
finishAction("TBR");
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr));
.comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr));
} else {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute: Current Basal: duration: {} min, rate={}",
tbrCurrent.getDurationMinutes(), tbrCurrent.getInsulinRate());
tbrCurrent.getDurationMinutes(), tbrCurrent.getInsulinRate());
}
if (!enforceNew) {
@ -897,7 +898,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR);
Boolean response = (Boolean) responseTask2.returnData;
Boolean response = (Boolean)responseTask2.returnData;
if (response) {
if (isLoggingEnabled())
@ -909,15 +910,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
finishAction("TBR");
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr_stop_op));
.comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr_stop_op));
}
}
// now start new TBR
MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetTemporaryBasal,
absoluteRate, durationInMinutes);
absoluteRate, durationInMinutes);
Boolean response = (Boolean) responseTask.returnData;
Boolean response = (Boolean)responseTask.returnData;
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "setTempBasalAbsolute - setTBR. Response: " + response);
@ -929,10 +930,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
pumpStatusLocal.tempBasalLength = durationInMinutes;
TemporaryBasal tempStart = new TemporaryBasal() //
.date(System.currentTimeMillis()) //
.duration(durationInMinutes) //
.absolute(absoluteRate) //
.source(Source.USER);
.date(System.currentTimeMillis()) //
.duration(durationInMinutes) //
.absolute(absoluteRate) //
.source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStart);
@ -941,13 +942,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
finishAction("TBR");
return new PumpEnactResult().success(response).enacted(response) //
.absolute(absoluteRate).duration(durationInMinutes);
.absolute(absoluteRate).duration(durationInMinutes);
} else {
finishAction("TBR");
return new PumpEnactResult().success(response).enacted(response) //
.comment(MainApp.gs(R.string.medtronic_cmd_tbr_could_not_be_delivered));
.comment(MainApp.gs(R.string.medtronic_cmd_tbr_could_not_be_delivered));
}
}
@ -982,7 +983,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
}
if (this.getMDTPumpStatus().basalProfileStatus != BasalProfileStatus.NotInitialized
&& medtronicHistoryData.hasBasalProfileChanged()) {
&& medtronicHistoryData.hasBasalProfileChanged()) {
medtronicHistoryData.processLastBasalProfileChange(getMDTPumpStatus());
// this.basalProfileChanged = true;
}
@ -990,7 +991,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
PumpDriverState previousState = this.pumpState;
if (medtronicHistoryData.isPumpSuspended(this.pumpState == PumpDriverState.Suspended)) {
scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, -1);
// scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, -1);
this.pumpState = PumpDriverState.Suspended;
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "isPumpSuspended: true");
@ -1002,53 +1003,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
LOG.debug(getLogPrefix() + "isPumpSuspended: false");
}
List<PumpHistoryEntry> tdds = medtronicHistoryData.getTDDs();
if (tdds.size() > 0) {
processTDDs(tdds);
}
// List<PumpHistoryEntry> tdds2 = medtronicHistoryData.getTDDs2();
//
// // FIXME
// LOG.debug("TDDs2: {}", gsonInstancePretty.toJson(tdds2));
List<PumpHistoryEntry> treatments = medtronicHistoryData.getTreatments();
if (treatments.size() > 0) {
processTreatments(treatments);
}
medtronicHistoryData.processNewHistoryData();
this.medtronicHistoryData.finalizeNewHistoryRecords();
}
private void processTreatments(List<PumpHistoryEntry> treatments) {
// FIXME bolus and tbr
LOG.error(getLogPrefix() + "Treatments found: {}. Not processed.\n", treatments.size());
MedtronicHistoryData.showLogs(null, gsonInstancePretty.toJson(treatments));
}
private void processTDDs(List<PumpHistoryEntry> tdds) {
LOG.error(getLogPrefix() + "TDDs found: {}. Not processed.\n{}", tdds.size(), gsonInstancePretty.toJson(tdds));
// FIXME tdd
List<TDD> tdDsForLastXDays = MainApp.getDbHelper().getTDDs();
for (TDD tdDsForLastXDay : tdDsForLastXDays) {
LOG.debug("TDD: " + tdDsForLastXDay);
}
}
private void readPumpHistoryLogic() {
LocalDateTime targetDate = null;
@ -1067,14 +1028,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (lastPumpHistoryEntryTime == 0L) {
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: 0L - targetDate: "
+ targetDate);
+ targetDate);
targetDate = timeMinus36h;
} else {
// LocalDateTime lastHistoryRecordTime = DateTimeUtil.toLocalDateTime(lastPumpHistoryEntryTime);
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntryTime: {} - targetDate: {}",
lastPumpHistoryEntryTime, targetDate);
lastPumpHistoryEntryTime, targetDate);
medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntryTime);
@ -1096,7 +1057,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
} else {
if (isLoggingEnabled())
LOG.debug(getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - {}",
gsonInstancePretty.toJson(lastPumpHistoryEntry));
gsonInstancePretty.toJson(lastPumpHistoryEntry));
medtronicHistoryData.setIsInInit(false);
medtronicHistoryData.setLastHistoryRecordTime(null);
@ -1106,11 +1067,11 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
LOG.debug("HST: Target Date: {}", targetDate);
MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.GetHistoryData,
lastPumpHistoryEntry, targetDate);
lastPumpHistoryEntry, targetDate);
LOG.debug("HST: After task");
PumpHistoryResult historyResult = (PumpHistoryResult) responseTask2.returnData;
PumpHistoryResult historyResult = (PumpHistoryResult)responseTask2.returnData;
LOG.debug("HST: History Result: {}", historyResult.toString());
@ -1126,7 +1087,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
SP.putLong(MedtronicConst.Statistics.LastPumpHistoryEntry, latestEntry.atechDateTime);
LOG.debug("HST: History: valid={}, unprocessed={}", historyResult.validEntries.size(),
historyResult.unprocessedEntries.size());
historyResult.unprocessedEntries.size());
this.medtronicHistoryData.addNewHistory(historyResult);
this.medtronicHistoryData.filterNewEntries();
@ -1174,15 +1135,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
workWithStatusRefresh(StatusRefreshAction.Add, refreshType, getTimeInFutureFromMinutes(min));
}
break;
break;
case PumpTime:
case Configuration:
case PumpHistory: {
workWithStatusRefresh(StatusRefreshAction.Add, refreshType,
getTimeInFutureFromMinutes(refreshType.getRefreshTime() + additionalTimeInMinutes));
getTimeInFutureFromMinutes(refreshType.getRefreshTime() + additionalTimeInMinutes));
}
break;
break;
}
}
@ -1193,7 +1154,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private synchronized Map<MedtronicStatusRefreshType, Long> workWithStatusRefresh(StatusRefreshAction action,
MedtronicStatusRefreshType statusRefreshType, Long time) {
MedtronicStatusRefreshType statusRefreshType, Long time) {
switch (action) {
@ -1231,7 +1192,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.ReadTemporaryBasal);
if (responseTask.hasData()) {
TempBasalPair tbr = (TempBasalPair) responseTask.returnData;
TempBasalPair tbr = (TempBasalPair)responseTask.returnData;
// we sometimes get rate returned even if TBR is no longer running
if (tbr.getDurationMinutes() == 0) {
@ -1256,9 +1217,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
setRefreshButtonEnabled(true);
return new PumpEnactResult() //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
}
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable);
@ -1278,12 +1239,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
LOG.warn(getLogPrefix() + "cancelTempBasal - Could not read currect TBR, canceling operation.");
finishAction("TBR");
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr));
.comment(MainApp.gs(R.string.medtronic_cmd_cant_read_tbr));
}
MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR);
Boolean response = (Boolean) responseTask2.returnData;
Boolean response = (Boolean)responseTask2.returnData;
finishAction("TBR");
@ -1292,20 +1253,20 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
LOG.info(getLogPrefix() + "cancelTempBasal - Cancel TBR successful.");
TemporaryBasal tempBasal = new TemporaryBasal() //
.date(System.currentTimeMillis()) //
.duration(0) //
.source(Source.USER);
.date(System.currentTimeMillis()) //
.duration(0) //
.source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
return new PumpEnactResult().success(response).enacted(response) //
.isTempCancel(true);
.isTempCancel(true);
} else {
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "cancelTempBasal - Cancel TBR failed.");
return new PumpEnactResult().success(response).enacted(response) //
.comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr));
.comment(MainApp.gs(R.string.medtronic_cmd_cant_cancel_tbr));
}
}
@ -1318,9 +1279,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// this shouldn't be needed, but let's do check if profile setting we are setting is same as current one
if (isProfileSame(profile)) {
return new PumpEnactResult() //
.success(true) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_not_set_is_same));
.success(true) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_not_set_is_same));
}
setRefreshButtonEnabled(false);
@ -1330,9 +1291,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
setRefreshButtonEnabled(true);
return new PumpEnactResult() //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_pump_status_pump_unreachable));
}
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable);
@ -1343,15 +1304,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (profileInvalid != null) {
return new PumpEnactResult() //
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid));
.success(false) //
.enacted(false) //
.comment(MainApp.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid));
}
MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetBasalProfileSTD,
basalProfile);
basalProfile);
Boolean response = (Boolean) responseTask.returnData;
Boolean response = (Boolean)responseTask.returnData;
if (isLoggingEnabled())
LOG.info(getLogPrefix() + "Basal Profile was set: " + response);
@ -1361,7 +1322,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return new PumpEnactResult().success(response).enacted(response);
} else {
return new PumpEnactResult().success(response).enacted(response) //
.comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_could_not_be_set));
.comment(MainApp.gs(R.string.medtronic_cmd_basal_profile_could_not_be_set));
}
}
@ -1446,7 +1407,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
this.customActions = new ArrayList<>();
CustomAction ca = new CustomAction(R.string.medtronic_custom_action_wake_and_tune,
MedtronicCustomActionType.WakeUpAndTune);
MedtronicCustomActionType.WakeUpAndTune);
this.customActions.add(ca);
}
@ -1457,7 +1418,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override
public PumpEnactResult executeCustomAction(CustomActionType customActionType) {
MedtronicCustomActionType mcat = (MedtronicCustomActionType) customActionType;
MedtronicCustomActionType mcat = (MedtronicCustomActionType)customActionType;
switch (mcat) {

View file

@ -37,13 +37,14 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.comm.message.PumpAckMess
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.message.PumpMessage;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.BasalProfile;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.BatteryStatusDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.ClockDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.PumpSettingDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.TempBasalPair;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicCommandType;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicDeviceType;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
/**
* Original file created by geoff on 5/30/16.
@ -693,19 +694,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
// See ButtonPressCarelinkMessageBody
// public void pressButton(int which) {
// if (doWakeUpBeforeCommand)
// wakeUp(receiverDeviceAwakeForMinutes, false);
//
// PumpMessage pressButtonMessage = makePumpMessage(MedtronicCommandType.PushButton,
// new ButtonPressCarelinkMessageBody(which));
// PumpMessage resp = sendAndListen(pressButtonMessage);
// if (resp.commandType != MedtronicCommandType.CommandACK) {
// LOG.error("Pump did not ack button press.");
// }
// }
@Override
public byte[] createPumpMessageContent(RLMessageType type) {
switch (type) {
@ -1001,11 +989,19 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
public LocalDateTime getPumpTime() {
public ClockDTO getPumpTime() {
ClockDTO clockDTO = new ClockDTO();
clockDTO.localDeviceTime = new LocalDateTime();
Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.RealTimeClock);
return responseObject == null ? null : (LocalDateTime)responseObject;
if (responseObject != null) {
clockDTO.pumpTime = (LocalDateTime)responseObject;
return clockDTO;
}
return null;
}

View file

@ -5,12 +5,14 @@ import static info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUti
import java.util.Date;
import java.util.Map;
import org.joda.time.LocalDateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.BasalProfile;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.BatteryStatusDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.ClockDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.PumpSettingDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.BasalProfileStatus;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicNotificationType;
@ -130,21 +132,25 @@ public class MedtronicUIPostprocessor {
private void processTime(MedtronicUITask uiTask) {
LocalDateTime ldt = (LocalDateTime)uiTask.returnData;
ClockDTO clockDTO = (ClockDTO)uiTask.returnData;
Date d1 = ldt.toDate();
Duration dur = new Duration(clockDTO.localDeviceTime.toDateTime(DateTimeZone.UTC),
clockDTO.pumpTime.toDateTime(DateTimeZone.UTC));
long currentTimeMillis = System.currentTimeMillis();
long diff = Math.abs(d1.getTime() - currentTimeMillis);
clockDTO.timeDifference = dur.getStandardSeconds();
LOG.debug("Pump Time: " + ldt + ", DeviceTime=" + d1 + //
", diff: " + diff / 1000 + " s");
MedtronicUtil.setPumpTime(clockDTO);
if (diff >= 10 * 60 * 1000) {
LOG.warn("Pump clock needs update, pump time: " + ldt + " (" + ldt + ")");
LOG.debug("Pump Time: " + clockDTO.localDeviceTime + ", DeviceTime=" + clockDTO.pumpTime + //
", diff: " + dur.getStandardSeconds() + " s");
if (dur.getStandardMinutes() >= 10) {
LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: "
+ dur.getStandardSeconds() + " s)");
sendNotification(MedtronicNotificationType.PumpWrongTimeUrgent);
} else if (diff >= 4 * 60 * 1000) {
LOG.warn("Pump clock needs update, pump time: " + ldt + " (" + ldt + ")");
} else if (dur.getStandardMinutes() >= 4) {
LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: "
+ dur.getStandardSeconds() + " s)");
sendNotification(MedtronicNotificationType.PumpWrongTimeNormal);
}

View file

@ -1,10 +1,5 @@
package info.nightscout.androidaps.plugins.PumpMedtronic.data;
import com.google.common.base.Splitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
@ -12,6 +7,14 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.plugins.PumpCommon.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.PumpMedtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.history.pump.MedtronicPumpHistoryDecoder;
@ -19,8 +22,10 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.comm.history.pump.PumpHi
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.history.pump.PumpHistoryEntryType;
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.history.pump.PumpHistoryResult;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.BasalProfile;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.DailyTotalsDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
//import info.nightscout.androidaps.plugins.PumpMedtronic.MedtronicPumpPlugin;
@ -43,9 +48,12 @@ public class MedtronicHistoryData {
private int basalProfileChangedInternally = 0;
private Gson gsonPretty;
public MedtronicHistoryData() {
this.allHistory = new ArrayList<>();
this.gsonPretty = MedtronicPumpPlugin.gsonInstancePretty;
}
@ -129,7 +137,7 @@ public class MedtronicHistoryData {
// FIXME not just 50 records, last 24 hours
public void finalizeNewHistoryRecords() {
List<PumpHistoryEntry> filteredListByLastRecord = getFilteredListByLastRecord((PumpHistoryEntryType) null);
List<PumpHistoryEntry> filteredListByLastRecord = getFilteredListByLastRecord((PumpHistoryEntryType)null);
LOG.debug("New records: " + filteredListByLastRecord.size());
@ -174,114 +182,260 @@ public class MedtronicHistoryData {
public boolean hasRelevantConfigurationChanged() {
return getStateFromFilteredList( //
PumpHistoryEntryType.ChangeBasalPattern, //
PumpHistoryEntryType.ClearSettings, //
PumpHistoryEntryType.SaveSettings, //
PumpHistoryEntryType.ChangeMaxBolus, //
PumpHistoryEntryType.ChangeMaxBasal, //
PumpHistoryEntryType.ChangeTempBasalType);
PumpHistoryEntryType.ChangeBasalPattern, //
PumpHistoryEntryType.ClearSettings, //
PumpHistoryEntryType.SaveSettings, //
PumpHistoryEntryType.ChangeMaxBolus, //
PumpHistoryEntryType.ChangeMaxBasal, //
PumpHistoryEntryType.ChangeTempBasalType);
}
private boolean isCollectionEmpty(List col) {
if (col == null)
return true;
return col.isEmpty();
}
// TODO This logic might not be working correctly
public boolean isPumpSuspended(Boolean wasPumpSuspended) {
if (true)
return false;
// if (true)
// return false;
List<PumpHistoryEntry> newAndAll = new ArrayList<>();
newAndAll.addAll(this.allHistory);
newAndAll.addAll(this.newHistory);
if (!isCollectionEmpty(this.allHistory)) {
newAndAll.addAll(this.allHistory);
}
if (!isCollectionEmpty(this.newHistory)) {
newAndAll.addAll(this.newHistory);
}
if (newAndAll.isEmpty())
return false;
this.sort(newAndAll);
if (wasPumpSuspended == null) { // suspension status not known
List<PumpHistoryEntry> items = getFilteredItems(newAndAll, //
PumpHistoryEntryType.Bolus, //
PumpHistoryEntryType.TempBasalCombined, //
PumpHistoryEntryType.Prime, //
PumpHistoryEntryType.PumpSuspend, //
PumpHistoryEntryType.PumpResume, //
PumpHistoryEntryType.Rewind, //
PumpHistoryEntryType.NoDeliveryAlarm, //
PumpHistoryEntryType.BasalProfileStart);
List<PumpHistoryEntry> items = getFilteredItems(PumpHistoryEntryType.Bolus, //
PumpHistoryEntryType.TempBasalCombined, //
PumpHistoryEntryType.Prime, //
PumpHistoryEntryType.PumpSuspend, //
PumpHistoryEntryType.PumpResume, //
PumpHistoryEntryType.Rewind, //
PumpHistoryEntryType.NoDeliveryAlarm, //
PumpHistoryEntryType.BasalProfileStart);
showLogs("isPumpSuspendCheck: ", MedtronicPumpPlugin.gsonInstancePretty.toJson(items));
if (items.size() == 0)
return wasPumpSuspended == null ? false : wasPumpSuspended;
PumpHistoryEntryType pumpHistoryEntryType = items.get(0).getEntryType();
PumpHistoryEntry pumpHistoryEntry = items.get(0);
LOG.debug("Last entry type: {}", pumpHistoryEntryType);
return !(pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.TempBasalCombined || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.BasalProfileStart || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Bolus || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpResume);
return !(pumpHistoryEntryType == PumpHistoryEntryType.TempBasalCombined || //
pumpHistoryEntryType == PumpHistoryEntryType.BasalProfileStart || //
pumpHistoryEntryType == PumpHistoryEntryType.Bolus || //
pumpHistoryEntryType == PumpHistoryEntryType.PumpResume || //
pumpHistoryEntryType == PumpHistoryEntryType.Prime);
} else {
// if (wasPumpSuspended == null) { // suspension status not known
//
// List<PumpHistoryEntry> items = getFilteredItems(PumpHistoryEntryType.Bolus, //
// PumpHistoryEntryType.TempBasalCombined, //
// PumpHistoryEntryType.Prime, //
// PumpHistoryEntryType.PumpSuspend, //
// PumpHistoryEntryType.PumpResume, //
// PumpHistoryEntryType.Rewind, //
// PumpHistoryEntryType.NoDeliveryAlarm, //
// PumpHistoryEntryType.BasalProfileStart);
//
// if (items.size() == 0)
// return wasPumpSuspended == null ? false : wasPumpSuspended;
//
// PumpHistoryEntry pumpHistoryEntry = items.get(0);
//
// return !(pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.TempBasalCombined || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.BasalProfileStart || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Bolus || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpResume);
//
// } else {
//
// List<PumpHistoryEntry> items = getFilteredItems(PumpHistoryEntryType.Bolus, //
// PumpHistoryEntryType.TempBasalCombined, //
// PumpHistoryEntryType.Prime, //
// PumpHistoryEntryType.PumpSuspend, //
// PumpHistoryEntryType.PumpResume, //
// PumpHistoryEntryType.Rewind, //
// PumpHistoryEntryType.NoDeliveryAlarm, //
// PumpHistoryEntryType.BasalProfileStart);
//
// if (wasPumpSuspended) {
//
// if (items.size() == 0)
// return wasPumpSuspended == null ? false : wasPumpSuspended;
//
// PumpHistoryEntry pumpHistoryEntry = items.get(0);
//
// if (pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.TempBasalCombined || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.BasalProfileStart || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Bolus || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpResume)
// return false;
// else
// return true;
//
// } else {
//
// if (items.size() == 0)
// return wasPumpSuspended == null ? false : wasPumpSuspended;
//
// PumpHistoryEntry pumpHistoryEntry = items.get(0);
//
// if (pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.NoDeliveryAlarm || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpSuspend || //
// pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Prime)
// return true;
//
// }
//
// }
List<PumpHistoryEntry> items = getFilteredItems(PumpHistoryEntryType.Bolus, //
PumpHistoryEntryType.TempBasalCombined, //
PumpHistoryEntryType.Prime, //
PumpHistoryEntryType.PumpSuspend, //
PumpHistoryEntryType.PumpResume, //
PumpHistoryEntryType.Rewind, //
PumpHistoryEntryType.NoDeliveryAlarm, //
PumpHistoryEntryType.BasalProfileStart);
// FIXME
// return false;
if (wasPumpSuspended) {
}
if (items.size() == 0)
return wasPumpSuspended == null ? false : wasPumpSuspended;
PumpHistoryEntry pumpHistoryEntry = items.get(0);
/**
* Process History Data: Boluses(Treatments), TDD, TBRs, Suspend-Resume (or other pump stops: battery, prime)
*/
if (pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.TempBasalCombined || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.BasalProfileStart || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Bolus || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpResume)
return false;
else
return true;
public void processNewHistoryData() {
// TDD
List<PumpHistoryEntry> tdds = getFilteredListByLastRecord(getTDDType());
LOG.debug("ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gsonPretty.toJson(tdds));
if (!isCollectionEmpty(tdds)) {
processTDDs(tdds);
}
// Bolus
List<PumpHistoryEntry> treatments = getFilteredListByLastRecord(PumpHistoryEntryType.Bolus);
LOG.debug("ProcessHistoryData: Bolus [count={}, items=", treatments.size());
showLogs(null, gsonPretty.toJson(treatments));
if (treatments.size() > 0) {
// processTreatments(treatments);
}
// TBR
List<PumpHistoryEntry> tbrs = getFilteredListByLastRecord(PumpHistoryEntryType.TempBasalCombined);
LOG.debug("ProcessHistoryData: TBRs [count={}, items=", tbrs.size());
showLogs(null, gsonPretty.toJson(tbrs));
if (tbrs.size() > 0) {
// processTreatments(treatments);
}
// Fake TBR
}
public void processTDDs(List<PumpHistoryEntry> tdds) {
LOG.error(getLogPrefix() + "TDDs found: {}. Not processed.\n{}", tdds.size(), gsonPretty.toJson(tdds));
// FIXME tdd
List<TDD> tddsDb = MainApp.getDbHelper().getTDDs(); // .getTDDsForLastXDays(3);
for (PumpHistoryEntry tdd : tdds) {
TDD tddDbEntry = findTDD(tdd.atechDateTime, tddsDb);
DailyTotalsDTO totalsDTO = (DailyTotalsDTO)tdd.getDecodedData().get("Object");
LOG.debug("DailtyTotals: {}", totalsDTO);
if (tddDbEntry == null) {
TDD tddNew = new TDD();
totalsDTO.setTDD(tddNew);
LOG.debug("TDD-Add: {}", tddNew);
MainApp.getDbHelper().createOrUpdateTDD(tddNew);
} else {
if (items.size() == 0)
return wasPumpSuspended == null ? false : wasPumpSuspended;
if (!totalsDTO.doesEqual(tddDbEntry)) {
totalsDTO.setTDD(tddDbEntry);
PumpHistoryEntry pumpHistoryEntry = items.get(0);
if (pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.NoDeliveryAlarm || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpSuspend || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Prime)
return true;
LOG.debug("TDD-Edit: {}", tddDbEntry);
MainApp.getDbHelper().createOrUpdateTDD(tddDbEntry);
}
}
}
// FIXME
return false;
}
private TDD findTDD(long atechDateTime, List<TDD> tddsDb) {
for (TDD tdd : tddsDb) {
if (DateTimeUtil.isSameDayATDAndMillis(atechDateTime, tdd.date)) {
return tdd;
}
}
return null;
}
private void processTreatments(List<PumpHistoryEntry> treatments) {
TreatmentsPlugin.getPlugin().getTreatmentsFromHistory();
}
public List<PumpHistoryEntry> getTDDs() {
return getFilteredListByLastRecord(getTDDType());
}
// private void processTreatments(List<PumpHistoryEntry> treatments) {
//
// // FIXME bolus and tbr
//
// LOG.error(getLogPrefix() + "Treatments found: {}. Not processed.\n", treatments.size());
//
// //MainApp.getDbHelper().getTDDsForLastXDays()
//
// MedtronicHistoryData.showLogs(null, gsonInstancePretty.toJson(treatments));
//
// }
// public List<PumpHistoryEntry> getTDDs() {
//
// return getFilteredListByLastRecord(getTDDType());
//
// }
private PumpHistoryEntryType getTDDType() {
switch (MedtronicUtil.getMedtronicPumpModel()) {
case Medtronic_515:
case Medtronic_715:
return PumpHistoryEntryType.DailyTotals515;
case Medtronic_522:
case Medtronic_722:
return PumpHistoryEntryType.DailyTotals522;
@ -303,8 +457,8 @@ public class MedtronicHistoryData {
public List<PumpHistoryEntry> getTreatments() {
return getFilteredListByLastRecord( //
PumpHistoryEntryType.Bolus, //
PumpHistoryEntryType.TempBasalCombined);
PumpHistoryEntryType.Bolus, //
PumpHistoryEntryType.TempBasalCombined);
}
@ -393,7 +547,7 @@ public class MedtronicHistoryData {
if (newProfile != null) {
LOG.debug("processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile);
BasalProfile basalProfile = (BasalProfile) newProfile.getDecodedData().get("Object");
BasalProfile basalProfile = (BasalProfile)newProfile.getDecodedData().get("Object");
mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour();
}
@ -411,7 +565,7 @@ public class MedtronicHistoryData {
public boolean hasPumpTimeChanged() {
return getStateFromFilteredList(PumpHistoryEntryType.NewTimeSet, //
PumpHistoryEntryType.ChangeTime);
PumpHistoryEntryType.ChangeTime);
}
@ -543,4 +697,10 @@ public class MedtronicHistoryData {
public void setBasalProfileChanged() {
this.basalProfileChangedInternally++;
}
private String getLogPrefix() {
return "MedtronicHistoryData::";
}
}

View file

@ -9,10 +9,10 @@ import org.slf4j.LoggerFactory;
import com.google.gson.annotations.Expose;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
import info.nightscout.androidaps.plugins.PumpCommon.utils.ByteUtil;
import info.nightscout.androidaps.plugins.PumpCommon.utils.FabricUtil;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
/**
* Created by geoff on 6/1/15.

View file

@ -0,0 +1,16 @@
package info.nightscout.androidaps.plugins.PumpMedtronic.data.dto;
import org.joda.time.LocalDateTime;
/**
* Created by andy on 2/27/19.
*/
public class ClockDTO {
public LocalDateTime localDeviceTime;
public LocalDateTime pumpTime;
public long timeDifference; // s
}

View file

@ -5,7 +5,9 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.plugins.PumpCommon.utils.ByteUtil;
import info.nightscout.androidaps.plugins.PumpCommon.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.PumpCommon.utils.StringUtil;
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.history.pump.PumpHistoryEntry;
@ -38,8 +40,8 @@ public class DailyTotalsDTO {
private Integer sensorDataCount;
private Double insulinTotal;
private Double insulinBasal;
private Double insulinBolus;
private Double insulinBasal = 0.0d;
private Double insulinBolus = 0.0d;
private Double insulinCarbs;
private Double bolusTotal;
@ -237,4 +239,18 @@ public class DailyTotalsDTO {
.omitNullValues() //
.toString();
}
public void setTDD(TDD tdd) {
tdd.date = DateTimeUtil.toMillisFromATD(this.entry.atechDateTime);
tdd.basal = insulinBasal;
tdd.bolus = insulinBolus;
tdd.total = insulinTotal;
}
public boolean doesEqual(TDD tdd) {
return tdd.total == this.insulinTotal && tdd.bolus == this.insulinBolus && tdd.basal == this.insulinBasal;
}
}

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.PumpMedtronic.defs;
import info.nightscout.androidaps.plugins.Actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
/**
* Created by andy on 11/3/18.

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.plugins.PumpMedtronic.defs;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
/**
* Created by andy on 10/15/18.

View file

@ -13,8 +13,6 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.PumpCommon.data.PumpStatus;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.ble.defs.RileyLinkTargetFrequency;
@ -25,7 +23,9 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicDeviceType
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.utils.SP;
/**
* Created by andy on 4/28/18.

View file

@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.PumpMedtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicUtil;
import info.nightscout.utils.SP;
import info.nightscout.androidaps.utils.SP;
/**
* RileyLinkMedtronicService is intended to stay running when the gui-app is closed.

View file

@ -1,12 +1,12 @@
package info.nightscout.androidaps.plugins.PumpMedtronic.service.tasks;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.data.ServiceTransport;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.service.tasks.PumpTask;
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.MedtronicCommunicationManager;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.ClockDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicCommandType;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicDeviceType;
import info.nightscout.androidaps.plugins.PumpMedtronic.service.RileyLinkMedtronicService;
@ -62,10 +62,10 @@ public class MedtronicPumpTask extends PumpTask {
break;
case RealTimeClock: {
LocalDateTime pumpResponse = communicationManager.getPumpTime();
ClockDTO pumpResponse = communicationManager.getPumpTime();
if (pumpResponse != null) {
LOG.info("ReadPumpClock: " + pumpResponse.toString("HH:mm:ss"));
medtronicPumpResult.addParameter("PumpTime", pumpResponse);
LOG.info("ReadPumpClock: " + pumpResponse.pumpTime.toString("HH:mm:ss"));
medtronicPumpResult.addParameter("PumpTime", pumpResponse.pumpTime);
} else {
LOG.warn("handleServiceCommand(" + mTransport.getOriginalCommandName() + ") pumpResponse is null");
medtronicPumpResult.setError();

View file

@ -1,19 +1,16 @@
package info.nightscout.androidaps.plugins.PumpMedtronic.util;
import org.joda.time.LocalTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.joda.time.LocalTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.data.RLHistoryItem;
import info.nightscout.androidaps.plugins.PumpCommon.hw.rileylink.defs.RileyLinkTargetDevice;
@ -21,6 +18,7 @@ import info.nightscout.androidaps.plugins.PumpCommon.utils.ByteUtil;
import info.nightscout.androidaps.plugins.PumpCommon.utils.HexDump;
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.MedtronicCommunicationManager;
import info.nightscout.androidaps.plugins.PumpMedtronic.comm.message.MessageType;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.ClockDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.data.dto.PumpSettingDTO;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicCommandType;
import info.nightscout.androidaps.plugins.PumpMedtronic.defs.MedtronicDeviceType;
@ -29,6 +27,9 @@ import info.nightscout.androidaps.plugins.PumpMedtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.PumpMedtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.PumpMedtronic.events.EventMedtronicDeviceStatusChange;
import info.nightscout.androidaps.plugins.PumpMedtronic.service.RileyLinkMedtronicService;
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 andy on 5/9/18.
@ -48,6 +49,7 @@ public class MedtronicUtil extends RileyLinkUtil {
private static Map<String, PumpSettingDTO> settings;
private static int BIG_FRAME_LENGTH = 65;
private static int doneBit = 1 << 7;
private static ClockDTO pumpTime;
public static LocalTime getTimeFrom30MinInterval(int interval) {
@ -71,8 +73,8 @@ public class MedtronicUtil extends RileyLinkUtil {
public static byte[] getByteArrayFromUnsignedShort(int shortValue, boolean returnFixedSize) {
byte highByte = (byte) (shortValue >> 8 & 0xFF);
byte lowByte = (byte) (shortValue & 0xFF);
byte highByte = (byte)(shortValue >> 8 & 0xFF);
byte lowByte = (byte)(shortValue & 0xFF);
if (highByte > 0) {
return createByteArray(highByte, lowByte);
@ -106,7 +108,7 @@ public class MedtronicUtil extends RileyLinkUtil {
public static double decodeBasalInsulin(int i) {
return (double) i / 40.0d;
return (double)i / 40.0d;
}
@ -149,7 +151,7 @@ public class MedtronicUtil extends RileyLinkUtil {
scrollRate = 1;
}
int strokes = (int) (amount * ((strokesPerUnit * 1.0d) / (scrollRate * 1.0d))) * scrollRate;
int strokes = (int)(amount * ((strokesPerUnit * 1.0d) / (scrollRate * 1.0d))) * scrollRate;
byte[] body = ByteUtil.fromHexString(String.format("%02x%0" + (2 * length) + "x", length, strokes));
@ -159,7 +161,7 @@ public class MedtronicUtil extends RileyLinkUtil {
public static byte[] createCommandBody(byte[] input) {
return ByteUtil.concat((byte) input.length, input);
return ByteUtil.concat((byte)input.length, input);
}
@ -187,7 +189,7 @@ public class MedtronicUtil extends RileyLinkUtil {
scrollRate = 2;
}
int strokes = (int) (amount * (strokesPerUnit / (scrollRate * 1.0d)));
int strokes = (int)(amount * (strokesPerUnit / (scrollRate * 1.0d)));
strokes *= scrollRate;
@ -198,18 +200,18 @@ public class MedtronicUtil extends RileyLinkUtil {
public static void sendNotification(MedtronicNotificationType notificationType) {
Notification notification = new Notification( //
notificationType.getNotificationType(), //
MainApp.gs(notificationType.getResourceId()), //
notificationType.getNotificationUrgency());
notificationType.getNotificationType(), //
MainApp.gs(notificationType.getResourceId()), //
notificationType.getNotificationUrgency());
MainApp.bus().post(new EventNewNotification(notification));
}
public static void sendNotification(MedtronicNotificationType notificationType, Object... parameters) {
Notification notification = new Notification( //
notificationType.getNotificationType(), //
MainApp.gs(notificationType.getResourceId(), parameters), //
notificationType.getNotificationUrgency());
notificationType.getNotificationType(), //
MainApp.gs(notificationType.getResourceId(), parameters), //
notificationType.getNotificationUrgency());
MainApp.bus().post(new EventNewNotification(notification));
}
@ -225,21 +227,21 @@ public class MedtronicUtil extends RileyLinkUtil {
public static byte[] buildCommandPayload(MedtronicCommandType commandType, byte[] parameters) {
return buildCommandPayload((byte) commandType.commandCode, parameters);
return buildCommandPayload((byte)commandType.commandCode, parameters);
}
public static byte[] buildCommandPayload(byte commandType, byte[] parameters) {
// A7 31 65 51 C0 00 52
byte commandLength = (byte) (parameters == null ? 2 : 2 + parameters.length);
byte commandLength = (byte)(parameters == null ? 2 : 2 + parameters.length);
ByteBuffer sendPayloadBuffer = ByteBuffer.allocate(ENVELOPE_SIZE + commandLength); // + CRC_SIZE
sendPayloadBuffer.order(ByteOrder.BIG_ENDIAN);
byte[] serialNumberBCD = RileyLinkUtil.getRileyLinkServiceData().pumpIDBytes;
sendPayloadBuffer.put((byte) 0xA7);
sendPayloadBuffer.put((byte)0xA7);
sendPayloadBuffer.put(serialNumberBCD[0]);
sendPayloadBuffer.put(serialNumberBCD[1]);
sendPayloadBuffer.put(serialNumberBCD[2]);
@ -247,9 +249,9 @@ public class MedtronicUtil extends RileyLinkUtil {
sendPayloadBuffer.put(commandType);
if (parameters == null) {
sendPayloadBuffer.put((byte) 0x00);
sendPayloadBuffer.put((byte)0x00);
} else {
sendPayloadBuffer.put((byte) parameters.length); // size
sendPayloadBuffer.put((byte)parameters.length); // size
for (byte val : parameters) {
sendPayloadBuffer.put(val);
@ -298,7 +300,7 @@ public class MedtronicUtil extends RileyLinkUtil {
List<Byte> frameData = ByteUtil.getListFromByteArray(substring);
if (isEmptyFrame(frameData)) {
byte b = (byte) frame;
byte b = (byte)frame;
// b |= 0x80;
b |= 0b1000_0000;
// b |= doneBit;
@ -311,7 +313,7 @@ public class MedtronicUtil extends RileyLinkUtil {
done = true;
} else {
frameData.add(0, (byte) frame);
frameData.add(0, (byte)frame);
}
// System.out.println("Subarray: " + ByteUtil.getCompactString(substring));
@ -330,7 +332,7 @@ public class MedtronicUtil extends RileyLinkUtil {
if (!lastFrame) {
List<Byte> frameData = new ArrayList<>();
byte b = (byte) frame;
byte b = (byte)frame;
b |= 0b1000_0000;
// b |= doneBit;
@ -352,7 +354,7 @@ public class MedtronicUtil extends RileyLinkUtil {
int missing = BIG_FRAME_LENGTH - frameData.size();
for (int i = 0; i < missing; i++) {
frameData.add((byte) 0x00);
frameData.add((byte)0x00);
}
}
@ -411,7 +413,7 @@ public class MedtronicUtil extends RileyLinkUtil {
public static MedtronicCommunicationManager getMedtronicCommunicationManager() {
return (MedtronicCommunicationManager) RileyLinkUtil.rileyLinkCommunicationManager;
return (MedtronicCommunicationManager)RileyLinkUtil.rileyLinkCommunicationManager;
}
@ -480,4 +482,13 @@ public class MedtronicUtil extends RileyLinkUtil {
MedtronicUtil.settings = settings;
}
public static void setPumpTime(ClockDTO pumpTime) {
MedtronicUtil.pumpTime = pumpTime;
}
public static ClockDTO getPumpTime() {
return pumpTime;
}
}

View file

@ -1,22 +1,28 @@
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;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
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;
@ -25,15 +31,16 @@ import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventTempBasalChange;
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.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.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
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.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SingleClickButton;
@ -45,6 +52,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
static ActionsPlugin actionsPlugin = new ActionsPlugin();
static public ActionsPlugin getPlugin() {
return actionsPlugin;
}
@ -60,24 +68,24 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
SingleClickButton tddStats;
SingleClickButton history;
public ActionsFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.actions_fragment, container, false);
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);
@ -102,34 +110,41 @@ 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();
}
@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);
@ -147,34 +162,37 @@ 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);
@ -195,8 +213,12 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
else
tempTarget.setVisibility(View.VISIBLE);
if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().supportsTDDs) tddStats.setVisibility(View.GONE);
else tddStats.setVisibility(View.VISIBLE);
if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().supportsTDDs)
tddStats.setVisibility(View.GONE);
else
tddStats.setVisibility(View.VISIBLE);
checkCustomActions();
}
});
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Actions.defs;
package info.nightscout.androidaps.plugins.general.actions.defs;
/**
* Created by andy on 9/20/18.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Actions.defs;
package info.nightscout.androidaps.plugins.general.actions.defs;
/**
* Created by andy on 9/20/18.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Overview.Dialogs;
package info.nightscout.androidaps.plugins.general.overview.Dialogs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View file

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

View file

@ -0,0 +1,49 @@
package info.nightscout.androidaps.plugins.general.overview;
import info.nightscout.androidaps.R;
/**
* Created by andy on 3/2/19.
*/
public enum OverviewColorScheme {
TempTargetNotSet(R.color.ribbonDefault, R.color.ribbonTextDefault, R.color.tempTargetDisabledBackground, R.color.white),
TempTargetSet(R.color.ribbonWarning, R.color.ribbonTextWarning, R.color.tempTargetBackground, R.color.black),
APS_Loop_Enabled(R.color.ribbonDefault, R.color.ribbonTextDefault, R.color.loopenabled, R.color.black),
APS_SuperBolus(R.color.ribbonWarning, R.color.ribbonTextWarning, R.color.looppumpsuspended, R.color.white),
APS_Loop_Disconnected(R.color.ribbonCritical, R.color.ribbonTextCritical, R.color.looppumpsuspended, R.color.white),
APS_Loop_Suspended(R.color.ribbonWarning, R.color.ribbonTextWarning, R.color.looppumpsuspended, R.color.white),
APS_Pump_Suspended(R.color.ribbonWarning, R.color.ribbonTextWarning, R.color.loopenabled, R.color.white),
APS_Loop_Disabled(R.color.ribbonCritical, R.color.ribbonTextCritical, R.color.loopdisabled, R.color.white),
ProfileNormal(R.color.ribbonDefault, R.color.ribbonTextDefault, R.color.gray, R.color.white),
ProfileChanged(R.color.ribbonWarning, R.color.ribbonTextWarning, R.color.gray, R.color.white),
;
int newBackground;
int newTextColor;
int oldBackground;
int oldTextColor;
OverviewColorScheme(int newBackground, int newTextColor, int oldBackground, int oldTextColor) {
this.newBackground = newBackground;
this.newTextColor = newTextColor;
this.oldBackground = oldBackground;
this.oldTextColor = oldTextColor;
}
public int getBackground(boolean isNew) {
return isNew ? this.newBackground : this.oldBackground;
}
public int getTextColor(boolean isNew) {
return isNew ? this.newTextColor : this.oldTextColor;
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.PumpCommon.data;
package info.nightscout.androidaps.plugins.pump.common.data;
import java.util.Date;
@ -7,7 +7,7 @@ import org.joda.time.LocalDateTime;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpStatusType;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
/**
* Created by andy on 4/28/18.

View file

@ -1,13 +1,14 @@
package info.nightscout.androidaps.plugins.pump.danaR;
import android.support.annotation.Nullable;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import android.support.annotation.Nullable;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
@ -27,6 +28,8 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -44,6 +47,7 @@ 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;
@ -52,17 +56,14 @@ 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
@ -73,17 +74,21 @@ 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) {
@ -96,7 +101,8 @@ 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;
@ -104,14 +110,16 @@ 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;
@ -120,6 +128,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
}
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
@ -132,7 +141,8 @@ 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);
@ -142,21 +152,30 @@ 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 int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; }
public double getReservoirLevel() {
return DanaRPump.getInstance().reservoirRemainingUnits;
}
@Override
public int getBatteryLevel() {
return DanaRPump.getInstance().batteryRemaining;
}
@Override
public void stopBolusDelivering() {
@ -167,11 +186,14 @@ 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;
@ -217,6 +239,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
DanaRPump pump = DanaRPump.getInstance();
@ -236,11 +259,13 @@ 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);
@ -261,6 +286,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult();
@ -284,6 +310,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
}
}
@Override
public void connect(String from) {
if (sExecutionService != null) {
@ -293,26 +320,33 @@ 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) {
@ -322,6 +356,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
}
}
@Override
public JSONObject getJSONStatus(Profile profile, String profilename) {
DanaRPump pump = DanaRPump.getInstance();
@ -364,7 +399,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);
@ -372,16 +407,19 @@ 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
*/
@ -391,35 +429,51 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
return sExecutionService.loadHistory(type);
}
/**
* Constraint interface
*/
@Override
public Constraint<Double> applyBasalConstraints(Constraint<Double> 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<Integer> applyBasalPercentConstraints(Constraint<Integer> 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<Double> applyBolusConstraints(Constraint<Double> 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<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
return applyBolusConstraints(insulin);
}
@Nullable
@Override
public ProfileStore getProfile() {
@ -428,49 +482,69 @@ 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<CustomAction> getCustomActions() {
return null;
}
@Override
public PumpEnactResult executeCustomAction(CustomActionType customActionType) {
return null;
}
}

View file

@ -1,5 +1,12 @@
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;
@ -11,11 +18,6 @@ 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 info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -39,6 +41,8 @@ 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.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.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -63,9 +67,11 @@ 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();
@ -79,19 +85,16 @@ 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
@ -102,6 +105,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
@Override
protected void onStart() {
Context context = MainApp.instance().getApplicationContext();
@ -113,6 +117,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
super.onStart();
}
@Override
protected void onStop() {
Context context = MainApp.instance().getApplicationContext();
@ -121,25 +126,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();
}
}
@ -152,26 +157,30 @@ 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))
@ -183,37 +192,46 @@ 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) {
@ -223,6 +241,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
// DanaR interface
@Override
@ -230,28 +249,40 @@ 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<Double> applyBasalConstraints(Constraint<Double> 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<Integer> applyBasalPercentConstraints(Constraint<Integer> 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;
}
@ -259,15 +290,20 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
@Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> 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<Double> applyExtendedBolusConstraints(Constraint<Double> insulin) {
return applyBolusConstraints(insulin);
}
// Profile interface
@Nullable
@ -278,16 +314,19 @@ 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
@ -295,17 +334,21 @@ 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();
@ -317,7 +360,8 @@ 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;
@ -325,14 +369,16 @@ 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;
@ -341,6 +387,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
@ -352,8 +399,9 @@ 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);
@ -363,25 +411,35 @@ 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 int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; }
public double getReservoirLevel() {
return DanaRPump.getInstance().reservoirRemainingUnits;
}
@Override
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;
@ -398,13 +456,14 @@ 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
@ -413,15 +472,17 @@ 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;
@ -435,11 +496,13 @@ 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();
@ -452,6 +515,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
@Override
public void stopBolusDelivering() {
if (danaRSService == null) {
@ -461,19 +525,22 @@ 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();
@ -498,12 +565,15 @@ 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());
@ -524,7 +594,8 @@ 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 {
@ -546,11 +617,14 @@ 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;
@ -601,6 +675,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
return result;
}
private synchronized PumpEnactResult setHighTempBasalPercent(Integer percent) {
DanaRPump pump = DanaRPump.getInstance();
PumpEnactResult result = new PumpEnactResult();
@ -624,6 +699,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
return result;
}
@Override
public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
DanaRPump pump = DanaRPump.getInstance();
@ -642,11 +718,13 @@ 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);
@ -666,6 +744,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
return result;
}
@Override
public synchronized PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult();
@ -691,6 +770,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
@Override
public synchronized PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult();
@ -714,6 +794,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
@Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
DanaRPump pump = DanaRPump.getInstance();
@ -756,7 +837,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);
@ -764,38 +845,45 @@ 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";
@ -803,14 +891,27 @@ 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<CustomAction> getCustomActions() {
return null;
}
@Override
public PumpEnactResult executeCustomAction(CustomActionType customActionType) {
return null;
}
}

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.mdi;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@ -17,6 +19,8 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
@ -24,10 +28,12 @@ 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();
@ -36,12 +42,10 @@ 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;
@ -51,68 +55,82 @@ 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();
@ -121,31 +139,37 @@ 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 int getBatteryLevel() {
return -1;
}
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
PumpEnactResult result = new PumpEnactResult();
@ -157,12 +181,15 @@ 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);
@ -171,8 +198,10 @@ 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);
@ -181,6 +210,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
PumpEnactResult result = new PumpEnactResult();
@ -191,6 +221,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult();
@ -201,6 +232,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult();
@ -211,6 +243,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis();
@ -234,19 +267,33 @@ 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<CustomAction> getCustomActions() {
return null;
}
@Override
public PumpEnactResult executeCustomAction(CustomActionType customActionType) {
return null;
}
}

View file

@ -1,14 +1,16 @@
package info.nightscout.androidaps.plugins.pump.virtual;
import android.os.SystemClock;
import com.squareup.otto.Subscribe;
import java.util.List;
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 info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
@ -27,6 +29,8 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
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.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
@ -41,6 +45,7 @@ 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;
@ -51,16 +56,12 @@ 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;
@ -80,7 +81,6 @@ 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,6 +91,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
pumpDescription.is30minBasalRatesCapable = true;
}
public static VirtualPumpPlugin getPlugin() {
if (plugin == null)
plugin = new VirtualPumpPlugin();
@ -98,19 +99,23 @@ 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();
@ -118,62 +123,74 @@ 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 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)
@ -181,40 +198,48 @@ 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();
@ -226,10 +251,16 @@ 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) {
@ -247,7 +278,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;
}
@ -258,25 +289,26 @@ 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) {
TemporaryBasal tempBasal = new TemporaryBasal()
.date(System.currentTimeMillis())
.absolute(absoluteRate)
.duration(durationInMinutes)
.source(Source.USER);
@Override
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);
PumpEnactResult result = new PumpEnactResult();
result.success = true;
result.enacted = true;
@ -292,13 +324,12 @@ 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;
@ -315,17 +346,15 @@ 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;
@ -340,6 +369,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult();
@ -350,7 +380,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());
@ -359,6 +389,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult();
@ -378,6 +409,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return result;
}
@Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis();
@ -421,21 +453,25 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return pump;
}
@Override
public String deviceID() {
return "VirtualPump";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return "Virtual Pump";
}
public PumpType getPumpType() {
return pumpType;
}
@ -461,4 +497,15 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
}
@Override
public List<CustomAction> getCustomActions() {
return null;
}
@Override
public PumpEnactResult executeCustomAction(CustomActionType customActionType) {
return null;
}
}

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.plugins.PumpVirtual;
package info.nightscout.androidaps.plugins.pump.virtual;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.PumpCommon.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
/**
* Created by andy on 4/28/18.
@ -13,16 +13,19 @@ public class VirtualPumpStatus extends PumpStatus {
super(pumpDescription);
}
@Override
public void initSettings() {
}
@Override
public String getErrorInfo() {
return null;
}
@Override
public void refreshConfiguration() {

View file

@ -3,7 +3,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="info.nightscout.androidaps.plugins.Overview.Dialogs.MessageDialog"
tools:context="info.nightscout.androidaps.plugins.general.overview.Dialogs.MessageDialog"
android:paddingTop="15dp"
android:paddingBottom="15dp">

View file

@ -136,6 +136,33 @@
android:text=" " />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="16pt"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/rls_t1_tv13"
android:layout_width="58dp"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:layout_weight="35"
android:gravity="center_vertical"
android:text="@string/rileylink_firmware_version" />
<TextView
android:id="@+id/rls_t1_firmware_version"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_weight="65"
android:textAlignment="center"
android:gravity="center_vertical"
android:text=" " />
</LinearLayout>
<!-- Group - Device -->
<LinearLayout
android:layout_width="match_parent"

View file

@ -83,5 +83,9 @@
<color name="ribbonTextWarning">#303030</color>
<color name="ribbonTextCritical">#FFFFFF</color>
<color name="white">#FFFFFF</color>
<color name="black">#000000</color>
<color name="gray">#BBBBBB</color>
<color name="ic_launcher_background">#424242</color>
</resources>

View file

@ -1374,6 +1374,8 @@
<string name="rileylink_device_model">Device Model</string>
<string name="rileylink_last_used_frequency">Last used frequency</string>
<string name="rileylink_last_device_contact">Last device contact</string>
<string name="rileylink_firmware_version">RL Firmware</string>
<!-- RL State -->
<string name="rileylink_state_bt_init">Bluetooth Initializing…</string>