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() + '"'

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));
@ -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,6 +461,7 @@ public class MainApp extends Application {
return newList;
}
@Nullable
public static <T extends PluginBase> T getSpecificPlugin(Class<T> pluginClass) {
if (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));
@ -73,12 +77,15 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
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;
@ -93,12 +100,14 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
} else if (editTextPref.getText() != null) {
((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;
@ -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);
@ -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 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
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
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.
@ -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;
@ -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;

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;
}
@ -184,21 +192,38 @@ public class MedtronicHistoryData {
}
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<>();
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(PumpHistoryEntryType.Bolus, //
List<PumpHistoryEntry> items = getFilteredItems(newAndAll, //
PumpHistoryEntryType.Bolus, //
PumpHistoryEntryType.TempBasalCombined, //
PumpHistoryEntryType.Prime, //
PumpHistoryEntryType.PumpSuspend, //
@ -207,81 +232,210 @@ public class MedtronicHistoryData {
PumpHistoryEntryType.NoDeliveryAlarm, //
PumpHistoryEntryType.BasalProfileStart);
if (items.size() == 0)
return wasPumpSuspended == null ? false : wasPumpSuspended;
showLogs("isPumpSuspendCheck: ", MedtronicPumpPlugin.gsonInstancePretty.toJson(items));
PumpHistoryEntry pumpHistoryEntry = items.get(0);
PumpHistoryEntryType pumpHistoryEntryType = items.get(0).getEntryType();
return !(pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.TempBasalCombined || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.BasalProfileStart || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.Bolus || //
pumpHistoryEntry.getEntryType() == PumpHistoryEntryType.PumpResume);
LOG.debug("Last entry type: {}", pumpHistoryEntryType);
} else {
return !(pumpHistoryEntryType == PumpHistoryEntryType.TempBasalCombined || //
pumpHistoryEntryType == PumpHistoryEntryType.BasalProfileStart || //
pumpHistoryEntryType == PumpHistoryEntryType.Bolus || //
pumpHistoryEntryType == PumpHistoryEntryType.PumpResume || //
pumpHistoryEntryType == PumpHistoryEntryType.Prime);
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;
}
}
// 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;
//
// }
//
// }
// FIXME
return false;
// return false;
}
public List<PumpHistoryEntry> getTDDs() {
/**
* Process History Data: Boluses(Treatments), TDD, TBRs, Suspend-Resume (or other pump stops: battery, prime)
*/
return getFilteredListByLastRecord(getTDDType());
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 (!totalsDTO.doesEqual(tddDbEntry)) {
totalsDTO.setTDD(tddDbEntry);
LOG.debug("TDD-Edit: {}", tddDbEntry);
MainApp.getDbHelper().createOrUpdateTDD(tddDbEntry);
}
}
}
}
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();
}
// 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;
@ -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) {
@ -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,14 +68,14 @@ 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);
@ -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);
@ -154,27 +169,30 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
else
profileSwitch.setVisibility(View.VISIBLE);
if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized()
|| pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE);
} else {
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(
System.currentTimeMillis());
if (activeExtendedBolus != null) {
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.VISIBLE);
extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " "
+ activeExtendedBolus.toString());
} else {
extendedBolus.setVisibility(View.VISIBLE);
extendedBolusCancel.setVisibility(View.GONE);
}
}
if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) {
tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.GONE);
} else {
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(
System.currentTimeMillis());
if (activeTemp != null) {
tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.VISIBLE);
@ -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,5 +1,20 @@
package info.nightscout.androidaps.plugins.general.overview;
import static info.nightscout.androidaps.utils.DateUtil.now;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
@ -38,19 +53,6 @@ import com.crashlytics.android.answers.CustomEvent;
import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
@ -83,19 +85,14 @@ 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.careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
@ -109,12 +106,17 @@ import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizar
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationRecyclerViewAdapter;
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomG6Plugin;
import info.nightscout.androidaps.plugins.source.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.treatments.fragments.ProfileViewerDialog;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.BolusWizard;
import info.nightscout.androidaps.utils.DateUtil;
@ -128,9 +130,8 @@ import info.nightscout.androidaps.utils.SingleClickButton;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils;
import static info.nightscout.androidaps.utils.DateUtil.now;
public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
TextView timeView;
@ -198,18 +199,27 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
Handler sLoopHandler = new Handler();
Runnable sRefreshLoop = null;
public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN, DEVSLOPE}
public enum CHARTTYPE {
PRE,
BAS,
IOB,
COB,
DEV,
SEN,
DEVSLOPE
}
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledUpdate = null;
public OverviewFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// check screen width
final DisplayMetrics dm = new DisplayMetrics();
@ -347,6 +357,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return view;
}
private void setupChartMenu(View view) {
chartButton = (ImageButton)view.findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(v -> {
@ -368,48 +379,59 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.PRE.ordinal(), Menu.NONE, "Predictions");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)),
0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showprediction", true));
}
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.BAS.ordinal(), Menu.NONE,
MainApp.gs(R.string.overview_show_basals));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showbasals", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.IOB.ordinal(), Menu.NONE,
MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showiob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.COB.ordinal(), Menu.NONE,
MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showcob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEV.ordinal(), Menu.NONE,
MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdeviations", false));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.SEN.ordinal(), Menu.NONE,
MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0,
s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showratios", false));
@ -418,13 +440,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)),
0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdevslope", false));
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == CHARTTYPE.PRE.ordinal()) {
@ -448,6 +472,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
});
chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
@ -463,8 +488,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
super.onCreateContextMenu(menu, v, menuInfo);
if (v == apsModeView) {
final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
final PumpDescription pumpDescription =
ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription();
final PumpDescription pumpDescription = ConfigBuilderPlugin.getPlugin().getActivePump()
.getPumpDescription();
if (!ProfileFunctions.getInstance().isProfileValid("ContexMenuCreation"))
return;
menu.setHeaderTitle(MainApp.gs(R.string.loop));
@ -495,7 +520,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
} else if (v == activeProfileView) {
menu.setHeaderTitle(MainApp.gs(R.string.profile));
menu.add(MainApp.gs(R.string.danar_viewprofile));
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null
&& ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
menu.add(MainApp.gs(R.string.careportal_profileswitch));
}
} else if (v == tempTargetView) {
@ -510,8 +536,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
private void showSuspendtPump(ContextMenu menu,
PumpDescription pumpDescription) {
private void showSuspendtPump(ContextMenu menu, PumpDescription pumpDescription) {
if (pumpDescription.tempDurationStep15mAllowed)
menu.add(MainApp.gs(R.string.disconnectpumpfor15m));
if (pumpDescription.tempDurationStep30mAllowed)
@ -521,6 +547,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
menu.add(MainApp.gs(R.string.disconnectpumpfor3h));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final Profile profile = ProfileFunctions.getInstance().getProfile();
@ -533,10 +560,12 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
ConfigBuilderPlugin.getPlugin().storeSettings("DisablingLoop");
updateGUI("suspendmenu");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),
MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
@ -549,15 +578,17 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
updateGUI("suspendmenu");
NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.gs(R.string.resume)) ||
item.getTitle().equals(MainApp.gs(R.string.reconnect))) {
} else if (item.getTitle().equals(MainApp.gs(R.string.resume))
|| item.getTitle().equals(MainApp.gs(R.string.reconnect))) {
loopPlugin.suspendTo(0L);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),
MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
@ -612,34 +643,23 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
} else if (item.getTitle().equals(MainApp.gs(R.string.eatingsoon))) {
DefaultValueHelper defHelper = new DefaultValueHelper();
double target = defHelper.determineEatingSoonTT(profile.getUnits());
TempTarget tempTarget = new TempTarget()
.date(System.currentTimeMillis())
.duration(defHelper.determineEatingSoonTTDuration())
.reason(MainApp.gs(R.string.eatingsoon))
.source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits()))
TempTarget tempTarget = new TempTarget().date(System.currentTimeMillis())
.duration(defHelper.determineEatingSoonTTDuration()).reason(MainApp.gs(R.string.eatingsoon))
.source(Source.USER).low(Profile.toMgdl(target, profile.getUnits()))
.high(Profile.toMgdl(target, profile.getUnits()));
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
} else if (item.getTitle().equals(MainApp.gs(R.string.activity))) {
DefaultValueHelper defHelper = new DefaultValueHelper();
double target = defHelper.determineActivityTT(profile.getUnits());
TempTarget tempTarget = new TempTarget()
.date(now())
.duration(defHelper.determineActivityTTDuration())
.reason(MainApp.gs(R.string.activity))
.source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits()))
.high(Profile.toMgdl(target, profile.getUnits()));
TempTarget tempTarget = new TempTarget().date(now()).duration(defHelper.determineActivityTTDuration())
.reason(MainApp.gs(R.string.activity)).source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits())).high(Profile.toMgdl(target, profile.getUnits()));
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
} else if (item.getTitle().equals(MainApp.gs(R.string.hypo))) {
DefaultValueHelper defHelper = new DefaultValueHelper();
double target = defHelper.determineHypoTT(profile.getUnits());
TempTarget tempTarget = new TempTarget()
.date(now())
.duration(defHelper.determineHypoTTDuration())
.reason(MainApp.gs(R.string.hypo))
.source(Source.USER)
.low(Profile.toMgdl(target, profile.getUnits()))
TempTarget tempTarget = new TempTarget().date(now()).duration(defHelper.determineHypoTTDuration())
.reason(MainApp.gs(R.string.hypo)).source(Source.USER).low(Profile.toMgdl(target, profile.getUnits()))
.high(Profile.toMgdl(target, profile.getUnits()));
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
} else if (item.getTitle().equals(MainApp.gs(R.string.custom))) {
@ -649,18 +669,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
newTTDialog.show(getFragmentManager(), "NewNSTreatmentDialog");
} else if (item.getTitle().equals(MainApp.gs(R.string.cancel))) {
TempTarget tempTarget = new TempTarget()
.source(Source.USER)
.date(now())
.duration(0)
.low(0)
.high(0);
TempTarget tempTarget = new TempTarget().source(Source.USER).date(now()).duration(0).low(0).high(0);
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
}
return super.onContextItemSelected(item);
}
@Override
public void onClick(View v) {
boolean xdrip = SourceXdripPlugin.getPlugin().isEnabled(PluginType.BGSOURCE);
@ -669,7 +685,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
String units = ProfileFunctions.getInstance().getProfileUnits();
FragmentManager manager = getFragmentManager();
// try to fix https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days
// try to fix
// https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days
// https://stackoverflow.com/questions/14860239/checking-if-state-is-saved-before-committing-a-fragmenttransaction
if (manager.isStateSaved())
return;
@ -720,13 +737,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
new NewCarbsDialog().show(manager, "CarbsDialog");
break;
case R.id.overview_pumpstatus:
if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized())
if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended()
|| !ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized())
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("RefreshClicked", null);
break;
}
}
public boolean openCgmApp(String packageName) {
PackageManager packageManager = getContext().getPackageManager();
try {
@ -738,14 +757,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
getContext().startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
new AlertDialog.Builder(getContext())
.setMessage(R.string.error_starting_cgm)
.setPositiveButton("OK", null)
new AlertDialog.Builder(getContext()).setMessage(R.string.error_starting_cgm).setPositiveButton("OK", null)
.show();
return false;
}
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
@ -757,16 +775,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return false;
}
private void onClickAcceptTemp() {
Profile profile = ProfileFunctions.getInstance().getProfile();
Context context = getContext();
if (context == null) return;
if (context == null)
return;
if (LoopPlugin.getPlugin().isEnabled(PluginType.LOOP) && profile != null) {
LoopPlugin.getPlugin().invoke("Accept temp button", false);
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.isChangeRequested()) {
if (finalLastRun != null && finalLastRun.lastAPSRun != null
&& finalLastRun.constraintsProcessed.isChangeRequested()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(MainApp.gs(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
@ -781,6 +802,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
void onClickQuickwizard() {
final BgReading actualBg = DatabaseHelper.actualBg();
final Profile profile = ProfileFunctions.getInstance().getProfile();
@ -817,16 +839,21 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
String confirmMessage = MainApp.gs(R.string.entertreatmentquestion);
Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value();
Double insulinAfterConstraints = MainApp.getConstraintChecker()
.applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker()
.applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value();
confirmMessage += "\n" + MainApp.gs(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + MainApp.gs(R.string.bolus) + ": "
+ formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01 || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01
|| !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.gs(R.string.treatmentdeliveryerror));
builder.setMessage(MainApp.gs(R.string.constraints_violation) + "\n" + MainApp.gs(R.string.changeyourinput));
builder.setMessage(MainApp.gs(R.string.constraints_violation) + "\n"
+ MainApp.gs(R.string.changeyourinput));
builder.setPositiveButton(MainApp.gs(R.string.ok), null);
builder.show();
return;
@ -839,7 +866,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
accepted = false;
builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage);
builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
builder.setPositiveButton(
MainApp.gs(R.string.ok),
(dialog, id) -> {
synchronized (builder) {
if (accepted) {
if (L.isEnabled(L.OVERVIEW))
@ -847,14 +876,17 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return;
}
accepted = true;
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01 || finalCarbsAfterConstraints > 0) {
if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01
|| finalCarbsAfterConstraints > 0) {
if (wizard.superBolus) {
final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
if (loopPlugin.isEnabled(PluginType.LOOP)) {
loopPlugin.superBolusTo(System.currentTimeMillis() + T.hours(2).msecs());
MainApp.bus().post(new EventRefreshOverview("WizardDialog"));
}
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, 120, true, profile, new Callback() {
ConfigBuilderPlugin.getPlugin().getCommandQueue()
.tempBasalPercent(0, 120, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
@ -875,8 +907,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
detailedBolusInfo.context = context;
detailedBolusInfo.boluscalc = boluscalcJSON;
detailedBolusInfo.source = Source.USER;
if (finalInsulinAfterConstraints > 0 || ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() {
if (finalInsulinAfterConstraints > 0
|| ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo) {
ConfigBuilderPlugin.getPlugin().getCommandQueue()
.bolus(detailedBolusInfo, new Callback() {
@Override
public void run() {
if (!result.success) {
@ -903,6 +938,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
@Override
public void onPause() {
super.onPause();
@ -913,6 +949,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
unregisterForContextMenu(tempTargetView);
}
@Override
public void onResume() {
super.onResume();
@ -928,66 +965,79 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
updateGUI("onResume");
}
@Subscribe
public void onStatusEvent(final EventInitializationChanged ev) {
scheduleUpdateGUI("EventInitializationChanged");
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange ev) {
scheduleUpdateGUI("EventPreferenceChange");
}
@Subscribe
public void onStatusEvent(final EventRefreshOverview ev) {
scheduleUpdateGUI(ev.from);
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
scheduleUpdateGUI("EventAutosensCalculationFinished");
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
scheduleUpdateGUI("EventTreatmentChange");
}
@Subscribe
public void onStatusEvent(final EventCareportalEventChange ev) {
scheduleUpdateGUI("EventCareportalEventChange");
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
scheduleUpdateGUI("EventTempBasalChange");
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
scheduleUpdateGUI("EventExtendedBolusChange");
}
@Subscribe
public void onStatusEvent(final EventNewOpenLoopNotification ev) {
scheduleUpdateGUI("EventNewOpenLoopNotification");
}
@Subscribe
public void onStatusEvent(final EventAcceptOpenLoopChange ev) {
scheduleUpdateGUI("EventAcceptOpenLoopChange");
}
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
scheduleUpdateGUI("EventTempTargetChange");
}
@Subscribe
public void onStatusEvent(final EventProfileSwitchChange ev) {
scheduleUpdateGUI("EventProfileSwitchChange");
}
@Subscribe
public void onStatusEvent(final EventPumpStatusChanged s) {
Activity activity = getActivity();
@ -995,6 +1045,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
activity.runOnUiThread(() -> updatePumpStatus(s.textStatus()));
}
@Subscribe
public void onStatusEvent(final EventIobCalculationProgress e) {
Activity activity = getActivity();
@ -1005,6 +1056,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
});
}
private void hideTempRecommendation() {
Activity activity = getActivity();
if (activity != null)
@ -1014,14 +1066,16 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
});
}
private void clearNotification() {
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager notificationManager = (NotificationManager)MainApp.instance().getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
ActionStringHandler.handleInitiate("cancelChangeRequest");
}
private void updatePumpStatus(String status) {
if (!status.equals("")) {
pumpStatusView.setText(status);
@ -1033,8 +1087,10 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
public void scheduleUpdateGUI(final String from) {
class UpdateRunnable implements Runnable {
public void run() {
Activity activity = getActivity();
if (activity != null)
@ -1053,6 +1109,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
scheduledUpdate = worker.schedule(task, msec, TimeUnit.MILLISECONDS);
}
@SuppressLint("SetTextI18n")
public void updateGUI(final String from) {
if (L.isEnabled(L.OVERVIEW))
@ -1105,12 +1162,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null) {
if (deltaView != null)
deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
deltaView.setText("Δ "
+ Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL,
units) + " " + units);
if (deltaShortView != null)
deltaShortView.setText(Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units));
deltaShortView.setText(Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta
* Constants.MGDL_TO_MMOLL, units));
if (avgdeltaView != null)
avgdeltaView.setText("øΔ15m: " + Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
" øΔ40m: " + Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
avgdeltaView.setText("øΔ15m: "
+ Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta
* Constants.MGDL_TO_MMOLL, units)
+ " øΔ40m: "
+ Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta
* Constants.MGDL_TO_MMOLL, units));
} else {
if (deltaView != null)
deltaView.setText("Δ " + MainApp.gs(R.string.notavailable));
@ -1127,25 +1191,28 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (Config.APS && pump.getPumpDescription().isTempBasalCapable) {
apsModeView.setVisibility(View.VISIBLE);
apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonDefault));
apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextDefault));
apsModeView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.APS_Loop_Enabled));
apsModeView.setTextColor(getTextColor(OverviewColorScheme.APS_Loop_Enabled));
final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
if (loopPlugin.isEnabled(PluginType.LOOP) && loopPlugin.isSuperBolus()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
apsModeView.setText(String.format(MainApp.gs(R.string.loopsuperbolusfor), loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
apsModeView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.APS_SuperBolus));
apsModeView.setText(String.format(MainApp.gs(R.string.loopsuperbolusfor),
loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(getTextColor(OverviewColorScheme.APS_SuperBolus));
} else if (loopPlugin.isDisconnected()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonCritical));
apsModeView.setText(String.format(MainApp.gs(R.string.loopdisconnectedfor), loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextCritical));
apsModeView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.APS_Loop_Disconnected));
apsModeView.setText(String.format(MainApp.gs(R.string.loopdisconnectedfor),
loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(getTextColor(OverviewColorScheme.APS_Loop_Disconnected));
} else if (loopPlugin.isEnabled(PluginType.LOOP) && loopPlugin.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
apsModeView.setText(String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
apsModeView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.APS_Loop_Suspended));
apsModeView.setText(String.format(MainApp.gs(R.string.loopsuspendedfor),
loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(getTextColor(OverviewColorScheme.APS_Loop_Suspended));
} else if (pump.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
apsModeView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.APS_Pump_Suspended));
apsModeView.setText(MainApp.gs(R.string.pumpsuspended));
apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
apsModeView.setTextColor(getTextColor(OverviewColorScheme.APS_Pump_Suspended));
} else if (loopPlugin.isEnabled(PluginType.LOOP)) {
if (closedLoopEnabled.value()) {
apsModeView.setText(MainApp.gs(R.string.closedloop));
@ -1153,9 +1220,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
apsModeView.setText(MainApp.gs(R.string.openloop));
}
} else {
apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonCritical));
apsModeView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.APS_Loop_Disabled));
apsModeView.setText(MainApp.gs(R.string.disabledloop));
apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextCritical));
apsModeView.setTextColor(getTextColor(OverviewColorScheme.APS_Loop_Disabled));
}
} else {
apsModeView.setVisibility(View.GONE);
@ -1164,38 +1231,51 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// temp target
TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory();
if (tempTarget != null) {
tempTargetView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
tempTargetView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
tempTargetView.setTextColor(getTextColor(OverviewColorScheme.TempTargetSet));
tempTargetView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.TempTargetSet));
tempTargetView.setVisibility(View.VISIBLE);
tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end()));
tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units)
+ " " + DateUtil.untilString(tempTarget.end()));
} else {
tempTargetView.setTextColor(MainApp.gc(R.color.ribbonTextDefault));
tempTargetView.setBackgroundColor(MainApp.gc(R.color.ribbonDefault));
tempTargetView.setText(Profile.toTargetRangeString(profile.getTargetLow(), profile.getTargetHigh(), units, units));
tempTargetView.setTextColor(getTextColor(OverviewColorScheme.TempTargetNotSet));
tempTargetView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.TempTargetNotSet));
tempTargetView.setText(Profile.toTargetRangeString(profile.getTargetLow(), profile.getTargetHigh(), units,
units));
tempTargetView.setVisibility(View.VISIBLE);
}
// **** Temp button ****
if (acceptTempLayout != null) {
boolean showAcceptButton = !closedLoopEnabled.value(); // Open mode needed
showAcceptButton = showAcceptButton && finalLastRun != null && finalLastRun.lastAPSRun != null; // aps result must exist
showAcceptButton = showAcceptButton && (finalLastRun.lastOpenModeAccept == null || finalLastRun.lastOpenModeAccept.getTime() < finalLastRun.lastAPSRun.getTime()); // never accepted or before last result
showAcceptButton = showAcceptButton && finalLastRun.constraintsProcessed.isChangeRequested(); // change is requested
showAcceptButton = showAcceptButton && finalLastRun != null && finalLastRun.lastAPSRun != null; // aps
// result
// must
// exist
showAcceptButton = showAcceptButton
&& (finalLastRun.lastOpenModeAccept == null || finalLastRun.lastOpenModeAccept.getTime() < finalLastRun.lastAPSRun
.getTime()); // never accepted or before last result
showAcceptButton = showAcceptButton && finalLastRun.constraintsProcessed.isChangeRequested(); // change is
// requested
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended()
&& LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
acceptTempLayout.setVisibility(View.VISIBLE);
acceptTempButton.setText(MainApp.gs(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
acceptTempButton.setText(MainApp.gs(R.string.setbasalquestion) + "\n"
+ finalLastRun.constraintsProcessed);
} else {
acceptTempLayout.setVisibility(View.GONE);
}
}
// **** Calibration & CGM buttons ****
boolean xDripIsBgSource = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE);
boolean g5IsBgSource = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null && MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginType.BGSOURCE);
boolean xDripIsBgSource = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null
&& MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE);
boolean g5IsBgSource = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null
&& MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginType.BGSOURCE);
boolean bgAvailable = DatabaseHelper.actualBg() != null;
if (calibrationButton != null) {
if ((xDripIsBgSource || g5IsBgSource) && bgAvailable && SP.getBoolean(R.string.key_show_calibration_button, true)) {
if ((xDripIsBgSource || g5IsBgSource) && bgAvailable
&& SP.getBoolean(R.string.key_show_calibration_button, true)) {
calibrationButton.setVisibility(View.VISIBLE);
} else {
calibrationButton.setVisibility(View.GONE);
@ -1211,7 +1291,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(
System.currentTimeMillis());
String basalText = "";
if (shorttextmode) {
if (activeTemp != null) {
@ -1220,7 +1301,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
basalText = DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h";
}
baseBasalView.setOnClickListener(v -> {
String fullText = MainApp.gs(R.string.pump_basebasalrate_label) + ": " + DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h\n";
String fullText = MainApp.gs(R.string.pump_basebasalrate_label) + ": "
+ DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h\n";
if (activeTemp != null) {
fullText += MainApp.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull();
}
@ -1246,7 +1328,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
baseBasalView.setText(basalText);
final ExtendedBolus extendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
final ExtendedBolus extendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(
System.currentTimeMillis());
String extendedBolusText = "";
if (extendedBolusView != null) { // must not exists in all layouts
if (shorttextmode) {
@ -1260,7 +1343,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
extendedBolusView.setText(extendedBolusText);
if (Config.NSCLIENT) {
extendedBolusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.extendedbolus), extendedBolus.toString(), null));
extendedBolusView.setOnClickListener(v -> OKDialog.show(getActivity(),
MainApp.gs(R.string.extendedbolus), extendedBolus.toString(), null));
}
if (extendedBolusText.equals(""))
extendedBolusView.setVisibility(Config.NSCLIENT ? View.INVISIBLE : View.GONE);
@ -1270,18 +1354,19 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
activeProfileView.setText(ProfileFunctions.getInstance().getProfileName());
if (profile.getPercentage() != 100 || profile.getTimeshift() != 0) {
activeProfileView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
activeProfileView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
activeProfileView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.ProfileChanged));
activeProfileView.setTextColor(getTextColor(OverviewColorScheme.ProfileChanged));
} else {
activeProfileView.setBackgroundColor(MainApp.gc(R.color.ribbonDefault));
activeProfileView.setTextColor(MainApp.gc(R.color.ribbonTextDefault));
activeProfileView.setBackgroundColor(getBackgroundColor(OverviewColorScheme.ProfileNormal));
activeProfileView.setTextColor(getTextColor(OverviewColorScheme.ProfileNormal));
}
// QuickWizard button
QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && lastBG != null && pump.isInitialized() && !pump.isSuspended()) {
quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs())
+ "g";
BolusWizard wizard = quickWizardEntry.doCalc(profile, tempTarget, lastBG, false);
text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.calculatedTotalInsulin) + "U";
quickWizardButton.setText(text);
@ -1293,8 +1378,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// **** Various treatment buttons ****
if (carbsButton != null) {
if (SP.getBoolean(R.string.key_show_carbs_button, true)
&& (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo ||
(pump.isInitialized() && !pump.isSuspended()))) {
&& (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo || (pump
.isInitialized() && !pump.isSuspended()))) {
carbsButton.setVisibility(View.VISIBLE);
} else {
carbsButton.setVisibility(View.GONE);
@ -1363,8 +1448,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
iobView.setText(iobtext);
} else {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "/"
+ DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "/" + DecimalFormatter.to2Decimal(basalIob.basaliob)
+ ")";
iobView.setText(iobtext);
}
@ -1405,7 +1490,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
if (iageView != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
double insulinAge = careportalEvent != null ? careportalEvent.getHoursFromStart() : Double.MAX_VALUE;
double insulinAge = careportalEvent != null ? careportalEvent.getHoursFromStart()
: Double.MAX_VALUE;
applyStatuslight(iageView, "INS", insulinAge, iageWarn, iageUrgent, Double.MAX_VALUE, true);
}
@ -1442,19 +1528,22 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// pump status from ns
if (pumpDeviceStatusView != null) {
pumpDeviceStatusView.setText(NSDeviceStatus.getInstance().getPumpStatus());
pumpDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.pump), NSDeviceStatus.getInstance().getExtendedPumpStatus(), null));
pumpDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.pump),
NSDeviceStatus.getInstance().getExtendedPumpStatus(), null));
}
// OpenAPS status from ns
if (openapsDeviceStatusView != null) {
openapsDeviceStatusView.setText(NSDeviceStatus.getInstance().getOpenApsStatus());
openapsDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.openaps), NSDeviceStatus.getInstance().getExtendedOpenApsStatus(), null));
openapsDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.openaps),
NSDeviceStatus.getInstance().getExtendedOpenApsStatus(), null));
}
// Uploader status from ns
if (uploaderDeviceStatusView != null) {
uploaderDeviceStatusView.setText(NSDeviceStatus.getInstance().getUploaderStatusSpanned());
uploaderDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null));
uploaderDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(),
MainApp.gs(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null));
}
// Sensitivity
@ -1493,17 +1582,18 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
predHours = Math.min(2, predHours);
predHours = Math.max(0, predHours);
hoursToFetch = rangeToDisplay - predHours;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview
// specific
fromTime = toTime - T.hours(hoursToFetch).msecs();
endTime = toTime + T.hours(predHours).msecs();
} else {
hoursToFetch = rangeToDisplay;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview
// specific
fromTime = toTime - T.hours(hoursToFetch).msecs();
endTime = toTime;
}
final long now = System.currentTimeMillis();
// ------------------ 1st graph
@ -1517,8 +1607,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// **** BG ****
if (finalPredictionsAvailable && SP.getBoolean("showprediction", false))
graphData.addBgReadings(fromTime, toTime, lowLine, highLine,
apsResult.getPredictions());
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, apsResult.getPredictions());
else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
@ -1583,10 +1672,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
FragmentActivity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(() -> {
if (SP.getBoolean("showiob", true)
|| SP.getBoolean("showcob", true)
|| SP.getBoolean("showdeviations", false)
|| SP.getBoolean("showratios", false)
if (SP.getBoolean("showiob", true) || SP.getBoolean("showcob", true)
|| SP.getBoolean("showdeviations", false) || SP.getBoolean("showratios", false)
|| SP.getBoolean("showdevslope", false)) {
iobGraph.setVisibility(View.VISIBLE);
} else {
@ -1605,6 +1692,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
Profiler.log(log, from, updateGUIStart);
}
// Notifications
void updateNotifications() {
@ -1620,8 +1708,23 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
public static void applyStatuslight(TextView view, String text, double value, double warnThreshold, double urgentThreshold, double invalid, boolean checkAscending) {
Function<Double, Boolean> check = checkAscending ? (Double threshold) -> value >= threshold : (Double threshold) -> value <= threshold;
boolean isNewColor = false;
public int getBackgroundColor(OverviewColorScheme scheme) {
return MainApp.gc(scheme.getBackground(isNewColor));
}
public int getTextColor(OverviewColorScheme scheme) {
return MainApp.gc(scheme.getTextColor(isNewColor));
}
public static void applyStatuslight(TextView view, String text, double value, double warnThreshold,
double urgentThreshold, double invalid, boolean checkAscending) {
Function<Double, Boolean> check = checkAscending ? (Double threshold) -> value >= threshold
: (Double threshold) -> value <= threshold;
if (value != invalid) {
view.setText(text);
if (check.apply(urgentThreshold)) {

View file

@ -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();
@ -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,21 +482,25 @@ 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();
@ -453,24 +511,40 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
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,21 +126,21 @@ 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) -> {
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) -> {
}).setNegativeButton(R.string.cancel, (dialog, id) -> {
pluginSwitcher.cancel();
if (L.isEnabled(L.PUMP))
log.debug("User does not allow switching to HW pump!");
@ -152,6 +157,7 @@ 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");
@ -160,18 +166,21 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
};
@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())
@ -353,7 +400,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
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;
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;
@ -404,7 +462,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
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,9 +472,11 @@ 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) {
@ -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,9 +525,11 @@ 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
@ -473,7 +539,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
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();
@ -764,16 +845,19 @@ 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();
@ -784,18 +868,22 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
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,11 +55,13 @@ 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?
@ -63,56 +69,68 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
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?
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) {
@ -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();
@ -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>