Merge branch 'dev' into medtronic_andy

This commit is contained in:
Andy Rozman 2019-02-16 20:50:36 +00:00
commit 5aa5d9f749
439 changed files with 12425 additions and 772 deletions

View file

@ -64,12 +64,13 @@ android {
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
// dev_version: 2.0 // dev_version: 2.0
version "medtronic-0.7.0-SNAPSHOT" version "medtronic-0.7.1-SNAPSHOT"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"' buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
buildConfigField "String", "DEV_VERSION", '"2.0"' buildConfigField "String", "DEV_VERSION", '"2.0"'
buildConfigField "String", "DEV_DATE", '"4.1.2019"' buildConfigField "String", "DEV_DATE", '"13.2.2019"'
buildConfigField "String", "DEV_CHECKIN", '"65c5aebbdadf7872e9358c019702bdb964faaed7"'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk { ndk {
@ -200,6 +201,7 @@ dependencies {
implementation "com.google.android.gms:play-services-wearable:7.5.0" implementation "com.google.android.gms:play-services-wearable:7.5.0"
implementation(name: "android-edittext-validator-v1.3.4-mod", ext: "aar") implementation(name: "android-edittext-validator-v1.3.4-mod", ext: "aar")
implementation(name: "sightparser-release", ext: "aar") implementation(name: "sightparser-release", ext: "aar")
implementation 'com.madgag.spongycastle:core:1.58.0.0'
implementation("com.google.android:flexbox:0.3.0") { implementation("com.google.android:flexbox:0.3.0") {
exclude group: "com.android.support" exclude group: "com.android.support"

View file

@ -31,8 +31,8 @@
android:name=".MainApp" android:name=".MainApp"
android:allowBackup="true" android:allowBackup="true"
android:icon="${appIcon}" android:icon="${appIcon}"
android:roundIcon="${appIconRound}"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="${appIconRound}"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar"> android:theme="@style/AppTheme.NoActionBar">
<meta-data <meta-data
@ -51,10 +51,6 @@
<activity <activity
android:name=".plugins.Overview.Dialogs.ErrorHelperActivity" android:name=".plugins.Overview.Dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".plugins.Overview.Dialogs.MessageHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".activities.AgreementActivity" /> <activity android:name=".activities.AgreementActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" />
@ -74,17 +70,8 @@
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" /> <activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" />
<activity android:name=".activities.HistoryBrowseActivity" /> <activity android:name=".activities.HistoryBrowseActivity" />
<activity android:name=".plugins.PumpCommon.dialog.RileyLinkBLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpCommon.dialog.RileyLinkBLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver <receiver
android:name=".receivers.DataReceiver" android:name=".receivers.DataReceiver"
android:enabled="true" android:enabled="true"
@ -101,6 +88,8 @@
<action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" /> <action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" />
<!-- Receiver from DexcomG5 --> <!-- Receiver from DexcomG5 -->
<action android:name="com.dexcom.cgm.DATA" /> <action android:name="com.dexcom.cgm.DATA" />
<action android:name="com.dexcom.cgm.AndroidAPSEVGCallback.BROADCAST" />
<action android:name="com.dexcom.cgm.g5.AndroidAPSEVGCallback.BROADCAST" />
<!-- Receiver from Poctech --> <!-- Receiver from Poctech -->
<action android:name="com.china.poctech.data" /> <action android:name="com.china.poctech.data" />
</intent-filter> </intent-filter>
@ -194,12 +183,8 @@
android:exported="false" /> android:exported="false" />
<service android:name=".plugins.Persistentnotification.DummyService" /> <service android:name=".plugins.Persistentnotification.DummyService" />
<service android:name=".plugins.PumpInsightLocal.connection_service.InsightConnectionService" />
<service android:name=".plugins.PumpInsightLocal.InsightAlertService" />
<service
android:name=".plugins.PumpMedtronic.service.RileyLinkMedtronicService"
android:enabled="true"
android:exported="true" />
<meta-data <meta-data
android:name="io.fabric.ApiKey" android:name="io.fabric.ApiKey"
@ -208,13 +193,38 @@
<activity <activity
android:name=".setupwizard.SetupWizardActivity" android:name=".setupwizard.SetupWizardActivity"
android:configChanges="orientation|keyboardHidden|screenSize" android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/AppTheme.NoActionBar" android:label="@string/title_activity_setup_wizard"
android:label="@string/title_activity_setup_wizard" /> android:theme="@style/AppTheme.NoActionBar" />
<activity <activity
android:name=".activities.SingleFragmentActivity" android:name=".activities.SingleFragmentActivity"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity android:name=".plugins.Maintenance.activities.LogSettingActivity"></activity> <activity android:name=".plugins.Maintenance.activities.LogSettingActivity"></activity>
<activity
android:name=".plugins.PumpInsightLocal.activities.InsightPairingActivity"
android:theme="@style/AppTheme"
android:label="@string/insight_pairing" />
<activity
android:name=".plugins.PumpInsightLocal.activities.InsightAlertActivity"
android:label="@string/pump_alert"
android:theme="@style/InsightAlertDialog" />
<activity
android:name=".plugins.PumpInsightLocal.activities.InsightPairingInformationActivity"
android:theme="@style/AppTheme"
android:label="@string/pairing_information" />
<service
android:name=".plugins.PumpMedtronic.service.RileyLinkMedtronicService"
android:enabled="true"
android:exported="true" />
<activity android:name=".plugins.PumpCommon.dialog.RileyLinkBLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpCommon.dialog.RileyLinkBLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity <activity
android:name=".plugins.PumpCommon.hw.rileylink.dialog.RileyLinkStatusActivity" android:name=".plugins.PumpCommon.hw.rileylink.dialog.RileyLinkStatusActivity"
@ -225,4 +235,4 @@
</application> </application>
</manifest> </manifest>

View file

@ -1,13 +1,5 @@
package info.nightscout.androidaps; 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.app.Application;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
@ -28,6 +20,14 @@ import com.squareup.otto.Bus;
import com.squareup.otto.LoggingBus; import com.squareup.otto.LoggingBus;
import com.squareup.otto.ThreadEnforcer; 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.data.ConstraintChecker;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -44,9 +44,8 @@ import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Maintenance.LoggerUtils;
import info.nightscout.androidaps.plugins.Maintenance.MaintenancePlugin; import info.nightscout.androidaps.plugins.Maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver; import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
@ -67,8 +66,8 @@ import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin; import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
import info.nightscout.androidaps.plugins.PumpInsightLocal.LocalInsightPlugin;
import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin; import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin;
import info.nightscout.androidaps.plugins.PumpMedtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.PumpMedtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin;
@ -77,6 +76,8 @@ import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG6Plugin;
import info.nightscout.androidaps.plugins.Source.SourceEversensePlugin;
import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin; import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin; import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin; import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin;
@ -90,11 +91,12 @@ import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.androidaps.plugins.Maintenance.LoggerUtils;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Fabric;
public class MainApp extends Application {
public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(L.CORE); private static Logger log = LoggerFactory.getLogger(L.CORE);
private static KeepAliveReceiver keepAliveReceiver; private static KeepAliveReceiver keepAliveReceiver;
@ -117,7 +119,6 @@ public class MainApp extends Application {
public static boolean devBranch; public static boolean devBranch;
public static boolean engineeringMode; public static boolean engineeringMode;
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
@ -159,8 +160,7 @@ public class MainApp extends Application {
// Register all tabs in app here // Register all tabs in app here
pluginsList.add(OverviewPlugin.getPlugin()); pluginsList.add(OverviewPlugin.getPlugin());
pluginsList.add(IobCobCalculatorPlugin.getPlugin()); pluginsList.add(IobCobCalculatorPlugin.getPlugin());
if (Config.ACTION) if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
pluginsList.add(ActionsFragment.getPlugin());
pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin()); pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin());
@ -168,50 +168,36 @@ public class MainApp extends Application {
pluginsList.add(SensitivityAAPSPlugin.getPlugin()); pluginsList.add(SensitivityAAPSPlugin.getPlugin());
pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin()); pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
pluginsList.add(SensitivityOref1Plugin.getPlugin()); pluginsList.add(SensitivityOref1Plugin.getPlugin());
if (Config.PUMPDRIVERS) if (Config.PUMPDRIVERS) pluginsList.add(DanaRPlugin.getPlugin());
pluginsList.add(DanaRPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.PUMPDRIVERS) if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin());
pluginsList.add(DanaRKoreanPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin());
if (Config.PUMPDRIVERS) if (Config.PUMPDRIVERS && engineeringMode) pluginsList.add(LocalInsightPlugin.getInstance());
pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.PUMPDRIVERS)
pluginsList.add(DanaRSPlugin.getPlugin());
pluginsList.add(CareportalPlugin.getPlugin()); pluginsList.add(CareportalPlugin.getPlugin());
if (Config.PUMPDRIVERS && engineeringMode) { /*if (Config.PUMPDRIVERS && engineeringMode)
pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here pluginsList.add(InsightPlugin.getPlugin());*/
pluginsList.add(MedtronicPumpPlugin.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());
pluginsList.add(VirtualPumpPlugin.getPlugin()); pluginsList.add(VirtualPumpPlugin.getPlugin());
if (Config.APS) if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
pluginsList.add(LoopPlugin.getPlugin()); if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin());
if (Config.APS) if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin());
pluginsList.add(OpenAPSMAPlugin.getPlugin()); if (Config.APS) pluginsList.add(OpenAPSSMBPlugin.getPlugin());
if (Config.APS)
pluginsList.add(OpenAPSAMAPlugin.getPlugin());
if (Config.APS)
pluginsList.add(OpenAPSSMBPlugin.getPlugin());
pluginsList.add(NSProfilePlugin.getPlugin()); pluginsList.add(NSProfilePlugin.getPlugin());
if (Config.OTHERPROFILES) if (Config.OTHERPROFILES) pluginsList.add(SimpleProfilePlugin.getPlugin());
pluginsList.add(SimpleProfilePlugin.getPlugin()); if (Config.OTHERPROFILES) pluginsList.add(LocalProfilePlugin.getPlugin());
if (Config.OTHERPROFILES)
pluginsList.add(LocalProfilePlugin.getPlugin());
pluginsList.add(TreatmentsPlugin.getPlugin()); pluginsList.add(TreatmentsPlugin.getPlugin());
if (Config.SAFETY) if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
pluginsList.add(SafetyPlugin.getPlugin()); if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin());
if (Config.APS)
pluginsList.add(ObjectivesPlugin.getPlugin());
pluginsList.add(SourceXdripPlugin.getPlugin()); pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin()); pluginsList.add(SourceNSClientPlugin.getPlugin());
pluginsList.add(SourceMM640gPlugin.getPlugin()); pluginsList.add(SourceMM640gPlugin.getPlugin());
pluginsList.add(SourceGlimpPlugin.getPlugin()); pluginsList.add(SourceGlimpPlugin.getPlugin());
pluginsList.add(SourceDexcomG5Plugin.getPlugin()); pluginsList.add(SourceDexcomG5Plugin.getPlugin());
pluginsList.add(SourceDexcomG6Plugin.getPlugin());
pluginsList.add(SourcePoctechPlugin.getPlugin()); pluginsList.add(SourcePoctechPlugin.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SourceEversensePlugin.getPlugin());
pluginsList.add(SmsCommunicatorPlugin.getPlugin()); if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(FoodPlugin.getPlugin());
pluginsList.add(WearPlugin.initPlugin(this)); pluginsList.add(WearPlugin.initPlugin(this));
@ -253,16 +239,16 @@ public class MainApp extends Application {
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_DEVICESTATUS)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_DEVICESTATUS));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_CAL)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_CAL));
// register alarms //register alarms
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ALARM)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ALARM));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ANNOUNCEMENT)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ANNOUNCEMENT));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_CLEAR_ALARM)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_CLEAR_ALARM));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_URGENT_ALARM)); lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_URGENT_ALARM));
// register ack alarm //register ack alarm
lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM)); lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM));
// register dbaccess //register dbaccess
lbm.registerReceiver(dbAccessReciever, new IntentFilter(Intents.ACTION_DATABASE)); lbm.registerReceiver(dbAccessReciever, new IntentFilter(Intents.ACTION_DATABASE));
} }
@ -312,13 +298,11 @@ public class MainApp extends Application {
} }
} }
public void stopKeepAliveService() { public void stopKeepAliveService() {
if (keepAliveReceiver != null) if (keepAliveReceiver != null)
KeepAliveReceiver.cancelAlarm(this); KeepAliveReceiver.cancelAlarm(this);
} }
public static void subscribe(Object subscriber) { public static void subscribe(Object subscriber) {
try { try {
bus().register(subscriber); bus().register(subscriber);
@ -327,7 +311,6 @@ public class MainApp extends Application {
} }
} }
public static void unsubscribe(Object subscriber) { public static void unsubscribe(Object subscriber) {
try { try {
bus().unregister(subscriber); bus().unregister(subscriber);
@ -336,42 +319,34 @@ public class MainApp extends Application {
} }
} }
public static Bus bus() { public static Bus bus() {
return sBus; return sBus;
} }
public static String gs(int id) { public static String gs(int id) {
return sResources.getString(id); return sResources.getString(id);
} }
public static String gs(int id, Object... args) { public static String gs(int id, Object... args) {
return sResources.getString(id, args); return sResources.getString(id, args);
} }
public static String gq(@PluralsRes int id, int quantity, Object... args) { public static String gq(@PluralsRes int id, int quantity, Object... args) {
return sResources.getQuantityString(id, quantity, args); return sResources.getQuantityString(id, quantity, args);
} }
public static int gc(int id) { public static int gc(int id) {
return sResources.getColor(id); return sResources.getColor(id);
} }
public static MainApp instance() { public static MainApp instance() {
return sInstance; return sInstance;
} }
public static DatabaseHelper getDbHelper() { public static DatabaseHelper getDbHelper() {
return sDatabaseHelper; return sDatabaseHelper;
} }
public static void closeDbHelper() { public static void closeDbHelper() {
if (sDatabaseHelper != null) { if (sDatabaseHelper != null) {
sDatabaseHelper.close(); sDatabaseHelper.close();
@ -379,17 +354,14 @@ public class MainApp extends Application {
} }
} }
public static ConstraintChecker getConstraintChecker() { public static ConstraintChecker getConstraintChecker() {
return sConstraintsChecker; return sConstraintsChecker;
} }
public static ArrayList<PluginBase> getPluginsList() { public static ArrayList<PluginBase> getPluginsList() {
return pluginsList; return pluginsList;
} }
public static ArrayList<PluginBase> getSpecificPluginsList(PluginType type) { public static ArrayList<PluginBase> getSpecificPluginsList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>(); ArrayList<PluginBase> newList = new ArrayList<>();
@ -404,7 +376,6 @@ public class MainApp extends Application {
return newList; return newList;
} }
public static ArrayList<PluginBase> getSpecificPluginsVisibleInList(PluginType type) { public static ArrayList<PluginBase> getSpecificPluginsVisibleInList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>(); ArrayList<PluginBase> newList = new ArrayList<>();
@ -420,7 +391,6 @@ public class MainApp extends Application {
return newList; return newList;
} }
public static ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) { public static ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList<PluginBase> newList = new ArrayList<>(); ArrayList<PluginBase> newList = new ArrayList<>();
@ -435,7 +405,6 @@ public class MainApp extends Application {
return newList; return newList;
} }
public static ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type) { public static ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>(); ArrayList<PluginBase> newList = new ArrayList<>();
@ -451,13 +420,12 @@ public class MainApp extends Application {
return newList; return newList;
} }
@Nullable @Nullable
public static <T extends PluginBase> T getSpecificPlugin(Class<T> pluginClass) { public static <T extends PluginBase> T getSpecificPlugin(Class<T> pluginClass) {
if (pluginsList != null) { if (pluginsList != null) {
for (PluginBase p : pluginsList) { for (PluginBase p : pluginsList) {
if (pluginClass.isAssignableFrom(p.getClass())) if (pluginClass.isAssignableFrom(p.getClass()))
return (T)p; return (T) p;
} }
} else { } else {
log.error("pluginsList=null"); log.error("pluginsList=null");
@ -465,7 +433,6 @@ public class MainApp extends Application {
return null; return null;
} }
public static boolean isEngineeringModeOrRelease() { public static boolean isEngineeringModeOrRelease() {
if (!Config.APS) if (!Config.APS)
return true; return true;
@ -482,7 +449,6 @@ public class MainApp extends Application {
return devBranch; return devBranch;
} }
@Override @Override
public void onTerminate() { public void onTerminate() {
if (L.isEnabled(L.CORE)) if (L.isEnabled(L.CORE))

View file

@ -9,6 +9,7 @@ import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment; import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup; import android.preference.PreferenceGroup;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.text.TextUtils; import android.text.TextUtils;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
@ -168,8 +169,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
} }
addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginType.SENSITIVITY); addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), PluginType.SENSITIVITY);
PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY); addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY); addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY);
@ -183,9 +183,9 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP);
if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE) if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE) || DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE) || DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) { || DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) {
addPreferencesFromResource(R.xml.pref_danarprofile); addPreferencesFromResource(R.xml.pref_danarprofile);
} }
} }
@ -206,6 +206,17 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL);
} }
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_show_statuslights)));
}
}
initSummary(getPreferenceScreen()); initSummary(getPreferenceScreen());
} }

View file

@ -90,8 +90,8 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return System.currentTimeMillis() - date; return System.currentTimeMillis() - date;
} }
public long getHoursFromStart() { public double getHoursFromStart() {
return (System.currentTimeMillis() - date) / (60 * 60 * 1000); return (System.currentTimeMillis() - date) / (60 * 60 * 1000.0);
} }
public String age() { public String age() {

View file

@ -1,9 +1,9 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import java.util.List;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
@ -16,99 +16,57 @@ import info.nightscout.androidaps.plugins.Actions.defs.CustomActionType;
public interface PumpInterface { public interface PumpInterface {
boolean isInitialized(); // true if pump status has been read and is ready to accept commands 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 isSuspended(); // true if suspended (not delivering insulin) boolean isConnected(); // true if BT connection is established
boolean isConnecting(); // true if BT connection is in progress
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 boolean isHandshakeInProgress(); // true if BT is connected but initial handshake is still in progress
void finishHandshaking(); // set initial handshake completed void finishHandshaking(); // set initial handshake completed
void connect(String reason); void connect(String reason);
void disconnect(String reason); void disconnect(String reason);
void stopConnecting(); void stopConnecting();
void getPumpStatus(); void getPumpStatus();
// Upload to pump new basal profile // Upload to pump new basal profile
PumpEnactResult setNewBasalProfile(Profile profile); PumpEnactResult setNewBasalProfile(Profile profile);
boolean isThisProfileSet(Profile profile); boolean isThisProfileSet(Profile profile);
long lastDataTime(); long lastDataTime();
double getBaseBasalRate(); // base basal rate, not temp basal double getBaseBasalRate(); // base basal rate, not temp basal
double getReservoirLevel();
int getBatteryLevel(); // in percent as integer
PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo); PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo);
void stopBolusDelivering(); 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 setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew);
PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes); PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes);
//some pumps might set a very short temp close to 100% as cancelling a temp can be noisy
//when the cancel request is requested by the user (forced), the pump should always do a real cancel
// some pumps might set a very short temp close to 100% as cancelling a temp can be noisy
// when the cancel request is requested by the user (forced), the pump should always do a real cancel
PumpEnactResult cancelTempBasal(boolean enforceNew); PumpEnactResult cancelTempBasal(boolean enforceNew);
PumpEnactResult cancelExtendedBolus(); PumpEnactResult cancelExtendedBolus();
// Status to be passed to NS // Status to be passed to NS
JSONObject getJSONStatus(Profile profile, String profileName); JSONObject getJSONStatus(Profile profile, String profileName);
String deviceID(); String deviceID();
// Pump capabilities // Pump capabilities
PumpDescription getPumpDescription(); PumpDescription getPumpDescription();
// Short info for SMS, Wear etc // Short info for SMS, Wear etc
String shortStatus(boolean veryShort); String shortStatus(boolean veryShort);
boolean isFakingTempsByExtendedBoluses(); boolean isFakingTempsByExtendedBoluses();
PumpEnactResult loadTDDs(); PumpEnactResult loadTDDs();
List<CustomAction> getCustomActions(); List<CustomAction> getCustomActions();
PumpEnactResult executeCustomAction(CustomActionType customActionType); PumpEnactResult executeCustomAction(CustomActionType customActionType);
} }

View file

@ -75,17 +75,18 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try { try {
View view = inflater.inflate(R.layout.actions_fragment, container, false); View view = inflater.inflate(R.layout.actions_fragment, container, false);
profileSwitch = (SingleClickButton)view.findViewById(R.id.actions_profileswitch); profileSwitch = (SingleClickButton) view.findViewById(R.id.actions_profileswitch);
tempTarget = (SingleClickButton)view.findViewById(R.id.actions_temptarget); tempTarget = (SingleClickButton) view.findViewById(R.id.actions_temptarget);
extendedBolus = (SingleClickButton)view.findViewById(R.id.actions_extendedbolus); extendedBolus = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus);
extendedBolusCancel = (SingleClickButton)view.findViewById(R.id.actions_extendedbolus_cancel); extendedBolusCancel = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus_cancel);
tempBasal = (SingleClickButton)view.findViewById(R.id.actions_settempbasal); tempBasal = (SingleClickButton) view.findViewById(R.id.actions_settempbasal);
tempBasalCancel = (SingleClickButton)view.findViewById(R.id.actions_canceltempbasal); tempBasalCancel = (SingleClickButton) view.findViewById(R.id.actions_canceltempbasal);
fill = (SingleClickButton)view.findViewById(R.id.actions_fill); fill = (SingleClickButton) view.findViewById(R.id.actions_fill);
tddStats = view.findViewById(R.id.actions_tddstats); tddStats = view.findViewById(R.id.actions_tddstats);
history = view.findViewById(R.id.actions_historybrowser); history = view.findViewById(R.id.actions_historybrowser);
@ -143,8 +144,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
@Override @Override
public void run() { public void run() {
if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
&& ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
profileSwitch.setVisibility(View.VISIBLE); profileSwitch.setVisibility(View.VISIBLE);
} else { } else {
profileSwitch.setVisibility(View.GONE); profileSwitch.setVisibility(View.GONE);
@ -162,37 +162,34 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease() final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease()
&& pump.getPumpDescription().isSetBasalProfileCapable; && pump.getPumpDescription().isSetBasalProfileCapable;
if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended()) if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended())
profileSwitch.setVisibility(View.GONE); profileSwitch.setVisibility(View.GONE);
else else
profileSwitch.setVisibility(View.VISIBLE); profileSwitch.setVisibility(View.VISIBLE);
if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
|| pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
extendedBolus.setVisibility(View.GONE); extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE); extendedBolusCancel.setVisibility(View.GONE);
} else { } else {
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory( ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
System.currentTimeMillis());
if (activeExtendedBolus != null) { if (activeExtendedBolus != null) {
extendedBolus.setVisibility(View.GONE); extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.VISIBLE); extendedBolusCancel.setVisibility(View.VISIBLE);
extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
+ activeExtendedBolus.toString());
} else { } else {
extendedBolus.setVisibility(View.VISIBLE); extendedBolus.setVisibility(View.VISIBLE);
extendedBolusCancel.setVisibility(View.GONE); extendedBolusCancel.setVisibility(View.GONE);
} }
} }
if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) { if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) {
tempBasal.setVisibility(View.GONE); tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.GONE); tempBasalCancel.setVisibility(View.GONE);
} else { } else {
final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory( final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
System.currentTimeMillis());
if (activeTemp != null) { if (activeTemp != null) {
tempBasal.setVisibility(View.GONE); tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.VISIBLE); tempBasalCancel.setVisibility(View.VISIBLE);
@ -213,12 +210,8 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
else else
tempTarget.setVisibility(View.VISIBLE); tempTarget.setVisibility(View.VISIBLE);
if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().supportsTDDs) if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().supportsTDDs) tddStats.setVisibility(View.GONE);
tddStats.setVisibility(View.GONE); else tddStats.setVisibility(View.VISIBLE);
else
tddStats.setVisibility(View.VISIBLE);
checkCustomActions();
} }
}); });
} }

View file

@ -470,14 +470,14 @@ public class NSUpload {
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
public static void uploadBg(BgReading reading) { public static void uploadBg(BgReading reading, String source) {
Context context = MainApp.instance().getApplicationContext(); Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd"); bundle.putString("action", "dbAdd");
bundle.putString("collection", "entries"); bundle.putString("collection", "entries");
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
try { try {
data.put("device", "AndroidAPS-DexcomG5"); data.put("device", source);
data.put("date", reading.date); data.put("date", reading.date);
data.put("dateString", DateUtil.toISOString(reading.date)); data.put("dateString", DateUtil.toISOString(reading.date));
data.put("sgv", reading.value); data.put("sgv", reading.value);

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.Overview;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.arch.core.util.Function;
import android.content.ActivityNotFoundException; import android.content.ActivityNotFoundException;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -97,6 +98,7 @@ import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewCarbsDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.NewCarbsDialog;
@ -108,6 +110,7 @@ import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationRecyclerViewAdapter; import info.nightscout.androidaps.plugins.Overview.notifications.NotificationRecyclerViewAdapter;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore; import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; 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.Source.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileViewerDialog; import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileViewerDialog;
@ -162,6 +165,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
TextView sage; TextView sage;
TextView pbage; TextView pbage;
TextView iageView;
TextView cageView;
TextView reservoirView;
TextView sageView;
TextView batteryView;
LinearLayout statuslightsLayout;
RecyclerView notificationsView; RecyclerView notificationsView;
LinearLayoutManager llm; LinearLayoutManager llm;
@ -258,8 +268,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
sage = (TextView) view.findViewById(R.id.careportal_sensorage); sage = (TextView) view.findViewById(R.id.careportal_sensorage);
pbage = (TextView) view.findViewById(R.id.careportal_pbage); pbage = (TextView) view.findViewById(R.id.careportal_pbage);
bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); iageView = (TextView) view.findViewById(R.id.overview_insulinage);
iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph); cageView = (TextView) view.findViewById(R.id.overview_canulaage);
reservoirView = (TextView) view.findViewById(R.id.overview_reservoirlevel);
sageView = (TextView) view.findViewById(R.id.overview_sensorage);
batteryView = (TextView) view.findViewById(R.id.overview_batterylevel);
statuslightsLayout = (LinearLayout) view.findViewById(R.id.overview_statuslights);
bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph);
iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph);
treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton); treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton);
treatmentButton.setOnClickListener(this); treatmentButton.setOnClickListener(this);
@ -648,6 +665,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
public void onClick(View v) { public void onClick(View v) {
boolean xdrip = SourceXdripPlugin.getPlugin().isEnabled(PluginType.BGSOURCE); boolean xdrip = SourceXdripPlugin.getPlugin().isEnabled(PluginType.BGSOURCE);
boolean g5 = SourceDexcomG5Plugin.getPlugin().isEnabled(PluginType.BGSOURCE); boolean g5 = SourceDexcomG5Plugin.getPlugin().isEnabled(PluginType.BGSOURCE);
boolean g6 = SourceDexcomG6Plugin.getPlugin().isEnabled(PluginType.BGSOURCE);
String units = ProfileFunctions.getInstance().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
FragmentManager manager = getFragmentManager(); FragmentManager manager = getFragmentManager();
@ -670,7 +688,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
if (xdrip) { if (xdrip) {
CalibrationDialog calibrationDialog = new CalibrationDialog(); CalibrationDialog calibrationDialog = new CalibrationDialog();
calibrationDialog.show(manager, "CalibrationDialog"); calibrationDialog.show(manager, "CalibrationDialog");
} else if (g5) { } else if (g5 || g6) {
try { try {
Intent i = new Intent("com.dexcom.cgm.activities.MeterEntryActivity"); Intent i = new Intent("com.dexcom.cgm.activities.MeterEntryActivity");
startActivity(i); startActivity(i);
@ -686,6 +704,10 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
openCgmApp("com.dexcom.cgm.region5.mgdl"); openCgmApp("com.dexcom.cgm.region5.mgdl");
else if (g5 && units.equals(Constants.MMOL)) else if (g5 && units.equals(Constants.MMOL))
openCgmApp("com.dexcom.cgm.region5.mmol"); openCgmApp("com.dexcom.cgm.region5.mmol");
else if (g6 && units.equals(Constants.MGDL))
openCgmApp("com.dexcom.g6.region3.mgdl");
else if (g6 && units.equals(Constants.MMOL))
openCgmApp("com.dexcom.g6.region3.mmol");
break; break;
case R.id.overview_treatmentbutton: case R.id.overview_treatmentbutton:
NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog(); NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog();
@ -801,7 +823,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
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"; confirmMessage += "\n" + MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (!insulinAfterConstraints.equals(wizard.calculatedTotalInsulin) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) { if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01 || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.gs(R.string.treatmentdeliveryerror)); 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));
@ -825,7 +847,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return; return;
} }
accepted = true; accepted = true;
if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) { if (Math.abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= 0.01 || finalCarbsAfterConstraints > 0) {
if (wizard.superBolus) { if (wizard.superBolus) {
final LoopPlugin loopPlugin = LoopPlugin.getPlugin(); final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
if (loopPlugin.isEnabled(PluginType.LOOP)) { if (loopPlugin.isEnabled(PluginType.LOOP)) {
@ -1105,25 +1127,25 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun; final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (Config.APS && pump.getPumpDescription().isTempBasalCapable) { if (Config.APS && pump.getPumpDescription().isTempBasalCapable) {
apsModeView.setVisibility(View.VISIBLE); apsModeView.setVisibility(View.VISIBLE);
apsModeView.setBackgroundColor(MainApp.gc(R.color.loopenabled)); apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonDefault));
apsModeView.setTextColor(Color.BLACK); apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextDefault));
final LoopPlugin loopPlugin = LoopPlugin.getPlugin(); final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
if (loopPlugin.isEnabled(PluginType.LOOP) && loopPlugin.isSuperBolus()) { if (loopPlugin.isEnabled(PluginType.LOOP) && loopPlugin.isSuperBolus()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.looppumpsuspended)); apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
apsModeView.setText(String.format(MainApp.gs(R.string.loopsuperbolusfor), loopPlugin.minutesToEndOfSuspend())); apsModeView.setText(String.format(MainApp.gs(R.string.loopsuperbolusfor), loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE); apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
} else if (loopPlugin.isDisconnected()) { } else if (loopPlugin.isDisconnected()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.looppumpsuspended)); apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonCritical));
apsModeView.setText(String.format(MainApp.gs(R.string.loopdisconnectedfor), loopPlugin.minutesToEndOfSuspend())); apsModeView.setText(String.format(MainApp.gs(R.string.loopdisconnectedfor), loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE); apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextCritical));
} else if (loopPlugin.isEnabled(PluginType.LOOP) && loopPlugin.isSuspended()) { } else if (loopPlugin.isEnabled(PluginType.LOOP) && loopPlugin.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.looppumpsuspended)); apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
apsModeView.setText(String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend())); apsModeView.setText(String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE); apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
} else if (pump.isSuspended()) { } else if (pump.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.gc(R.color.looppumpsuspended)); apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
apsModeView.setText(MainApp.gs(R.string.pumpsuspended)); apsModeView.setText(MainApp.gs(R.string.pumpsuspended));
apsModeView.setTextColor(Color.WHITE); apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
} else if (loopPlugin.isEnabled(PluginType.LOOP)) { } else if (loopPlugin.isEnabled(PluginType.LOOP)) {
if (closedLoopEnabled.value()) { if (closedLoopEnabled.value()) {
apsModeView.setText(MainApp.gs(R.string.closedloop)); apsModeView.setText(MainApp.gs(R.string.closedloop));
@ -1131,9 +1153,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
apsModeView.setText(MainApp.gs(R.string.openloop)); apsModeView.setText(MainApp.gs(R.string.openloop));
} }
} else { } else {
apsModeView.setBackgroundColor(MainApp.gc(R.color.loopdisabled)); apsModeView.setBackgroundColor(MainApp.gc(R.color.ribbonCritical));
apsModeView.setText(MainApp.gs(R.string.disabledloop)); apsModeView.setText(MainApp.gs(R.string.disabledloop));
apsModeView.setTextColor(Color.WHITE); apsModeView.setTextColor(MainApp.gc(R.color.ribbonTextCritical));
} }
} else { } else {
apsModeView.setVisibility(View.GONE); apsModeView.setVisibility(View.GONE);
@ -1142,13 +1164,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// temp target // temp target
TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(); TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory();
if (tempTarget != null) { if (tempTarget != null) {
tempTargetView.setTextColor(Color.BLACK); tempTargetView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
tempTargetView.setBackgroundColor(MainApp.gc(R.color.tempTargetBackground)); tempTargetView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
tempTargetView.setVisibility(View.VISIBLE); 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 { } else {
tempTargetView.setTextColor(Color.WHITE); tempTargetView.setTextColor(MainApp.gc(R.color.ribbonTextDefault));
tempTargetView.setBackgroundColor(MainApp.gc(R.color.tempTargetDisabledBackground)); tempTargetView.setBackgroundColor(MainApp.gc(R.color.ribbonDefault));
tempTargetView.setText(Profile.toTargetRangeString(profile.getTargetLow(), profile.getTargetHigh(), units, units)); tempTargetView.setText(Profile.toTargetRangeString(profile.getTargetLow(), profile.getTargetHigh(), units, units));
tempTargetView.setVisibility(View.VISIBLE); tempTargetView.setVisibility(View.VISIBLE);
} }
@ -1247,7 +1269,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
} }
activeProfileView.setText(ProfileFunctions.getInstance().getProfileName()); activeProfileView.setText(ProfileFunctions.getInstance().getProfileName());
activeProfileView.setBackgroundColor(Color.GRAY); if (profile.getPercentage() != 100 || profile.getTimeshift() != 0) {
activeProfileView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
activeProfileView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
} else {
activeProfileView.setBackgroundColor(MainApp.gc(R.color.ribbonDefault));
activeProfileView.setTextColor(MainApp.gc(R.color.ribbonTextDefault));
}
// QuickWizard button // QuickWizard button
QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive(); QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
@ -1352,6 +1380,56 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
cobView.setText(cobText); cobView.setText(cobText);
} }
if (statuslightsLayout != null) {
if (SP.getBoolean(R.string.key_show_statuslights, false)) {
CareportalEvent careportalEvent;
NSSettingsStatus nsSettings = new NSSettingsStatus().getInstance();
double iageUrgent = nsSettings.getExtendedWarnValue("iage", "urgent", 96);
double iageWarn = nsSettings.getExtendedWarnValue("iage", "warn", 72);
double cageUrgent = nsSettings.getExtendedWarnValue("cage", "urgent", 72);
double cageWarn = nsSettings.getExtendedWarnValue("cage", "warn", 48);
double sageUrgent = nsSettings.getExtendedWarnValue("sage", "urgent", 166);
double sageWarn = nsSettings.getExtendedWarnValue("sage", "warn", 164);
//double pbageUrgent = nsSettings.getExtendedWarnValue("pgage", "urgent", 360);
//double pbageWarn = nsSettings.getExtendedWarnValue("pgage", "warn", 240);
double batUrgent = SP.getDouble(R.string.key_statuslights_bat_critical, 5.0);
double batWarn = SP.getDouble(R.string.key_statuslights_bat_warning, 25.0);
double resUrgent = SP.getDouble(R.string.key_statuslights_res_critical, 10.0);
double resWarn = SP.getDouble(R.string.key_statuslights_res_warning, 80.0);
if (cageView != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SITECHANGE);
double canAge = careportalEvent != null ? careportalEvent.getHoursFromStart() : Double.MAX_VALUE;
applyStatuslight(cageView, "CAN", canAge, cageWarn, cageUrgent, Double.MAX_VALUE, true);
}
if (iageView != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
double insulinAge = careportalEvent != null ? careportalEvent.getHoursFromStart() : Double.MAX_VALUE;
applyStatuslight(iageView, "INS", insulinAge, iageWarn, iageUrgent, Double.MAX_VALUE, true);
}
if (reservoirView != null) {
double reservoirLevel = pump.isInitialized() ? pump.getReservoirLevel() : -1;
applyStatuslight(reservoirView, "RES", reservoirLevel, resWarn, resUrgent, -1, false);
}
if (sageView != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
double sensorAge = careportalEvent != null ? careportalEvent.getHoursFromStart() : Double.MAX_VALUE;
applyStatuslight(sageView, "SEN", sensorAge, sageWarn, sageUrgent, Double.MAX_VALUE, true);
}
if (batteryView != null) {
double batteryLevel = pump.isInitialized() ? pump.getBatteryLevel() : -1;
applyStatuslight(batteryView, "BAT", batteryLevel, batWarn, batUrgent, -1, false);
}
statuslightsLayout.setVisibility(View.VISIBLE);
} else {
statuslightsLayout.setVisibility(View.GONE);
}
}
boolean predictionsAvailable; boolean predictionsAvailable;
if (Config.APS) if (Config.APS)
predictionsAvailable = finalLastRun != null && finalLastRun.request.hasPredictions; predictionsAvailable = finalLastRun != null && finalLastRun.request.hasPredictions;
@ -1542,4 +1620,21 @@ 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;
if (value != invalid) {
view.setText(text);
if (check.apply(urgentThreshold)) {
view.setTextColor(MainApp.gc(R.color.ribbonCritical));
} else if (check.apply(warnThreshold)) {
view.setTextColor(MainApp.gc(R.color.ribbonWarning));
} else {
view.setTextColor(MainApp.gc(R.color.ribbonDefault));
}
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
}
} }

View file

@ -69,6 +69,7 @@ public class Notification {
public static final int MEDTRONIC_PUMP_ALARM = 44; public static final int MEDTRONIC_PUMP_ALARM = 44;
public static final int RILEYLINK_CONNECTION = 45; public static final int RILEYLINK_CONNECTION = 45;
public static final int PERMISSION_PHONESTATE = 46; public static final int PERMISSION_PHONESTATE = 46;
public static final int INSIGHT_DATE_TIME_UPDATED = 47;
public int id; public int id;
public Date date; public Date date;

View file

@ -466,6 +466,23 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
return pump.basalProfile.hourlyRates[currentHour]; return pump.basalProfile.hourlyRates[currentHour];
} }
@Override
public double getReservoirLevel() {
return pump.reservoirLevel;
}
@Override
public int getBatteryLevel() {
switch (pump.state.batteryState) {
case PumpState.EMPTY:
return 5;
case PumpState.LOW:
return 25;
default:
return 100;
}
}
private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> { private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> {
EventOverviewBolusProgress event = EventOverviewBolusProgress.getInstance(); EventOverviewBolusProgress event = EventOverviewBolusProgress.getInstance();
switch (state) { switch (state) {

View file

@ -21,7 +21,7 @@ public enum PumpCapability {
ComboCapabilities(Bolus, TempBasal, BasalProfileSet, Refill, TDD, ManualTDDLoad), // ComboCapabilities(Bolus, TempBasal, BasalProfileSet, Refill, TDD, ManualTDDLoad), //
DanaCapabilities(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, TDD, ManualTDDLoad), // DanaCapabilities(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, TDD, ManualTDDLoad), //
DanaWithHistoryCapabilities(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, StoreCarbInfo, TDD, ManualTDDLoad), // DanaWithHistoryCapabilities(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, StoreCarbInfo, TDD, ManualTDDLoad), //
InsightCapabilities(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, TDD), // InsightCapabilities(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill,TDD,BasalRate30min), //
MedtronicCapabilities(Bolus, TempBasal, BasalProfileSet, Refill, TDD), // MedtronicCapabilities(Bolus, TempBasal, BasalProfileSet, Refill, TDD), //
// BasalRates (separately grouped) // BasalRates (separately grouped)

View file

@ -165,6 +165,12 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
} }
@Override
public double getReservoirLevel() { return DanaRPump.getInstance().reservoirRemainingUnits; }
@Override
public int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; }
@Override @Override
public void stopBolusDelivering() { public void stopBolusDelivering() {
if (sExecutionService == null) { if (sExecutionService == null) {

View file

@ -424,6 +424,12 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
@Override
public double getReservoirLevel() { return DanaRPump.getInstance().reservoirRemainingUnits; }
@Override
public int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; }
@Override @Override
public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
detailedBolusInfo.insulin = MainApp.getConstraintChecker() detailedBolusInfo.insulin = MainApp.getConstraintChecker()

View file

@ -1,35 +1,18 @@
package info.nightscout.androidaps.plugins.PumpInsight; package info.nightscout.androidaps.plugins.PumpInsight;
import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache.getRecordUniqueID; import android.content.DialogInterface;
import android.os.SystemClock;
import java.text.DecimalFormat; import android.support.v4.app.FragmentActivity;
import java.util.ArrayList; import android.support.v7.app.AlertDialog;
import java.util.List;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import sugar.free.sightparser.applayer.descriptors.ActiveBolus; import java.text.DecimalFormat;
import sugar.free.sightparser.applayer.descriptors.ActiveBolusType; import java.util.ArrayList;
import sugar.free.sightparser.applayer.descriptors.MessagePriority; import java.util.List;
import sugar.free.sightparser.applayer.descriptors.PumpStatus;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.remote_control.BolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.CancelBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.ExtendedBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.StandardBolusMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
import sugar.free.sightparser.handling.SingleMessageTaskRunner;
import sugar.free.sightparser.handling.TaskRunner;
import sugar.free.sightparser.pipeline.Status;
import android.content.DialogInterface;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
@ -75,6 +58,23 @@ import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import sugar.free.sightparser.applayer.descriptors.ActiveBolus;
import sugar.free.sightparser.applayer.descriptors.ActiveBolusType;
import sugar.free.sightparser.applayer.descriptors.MessagePriority;
import sugar.free.sightparser.applayer.descriptors.PumpStatus;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.remote_control.BolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.CancelBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.ExtendedBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.StandardBolusMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
import sugar.free.sightparser.handling.SingleMessageTaskRunner;
import sugar.free.sightparser.handling.TaskRunner;
import sugar.free.sightparser.pipeline.Status;
import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache.getRecordUniqueID;
/** /**
* Created by jamorham on 23/01/2018. * Created by jamorham on 23/01/2018.
@ -88,12 +88,10 @@ import info.nightscout.utils.SP;
@SuppressWarnings("AccessStaticViaInstance") @SuppressWarnings("AccessStaticViaInstance")
public class InsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface { public class InsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface {
private Logger log = LoggerFactory.getLogger(L.PUMP); private Logger log = LoggerFactory.getLogger(L.PUMP);
private static volatile InsightPlugin plugin; private static volatile InsightPlugin plugin;
public static InsightPlugin getPlugin() { public static InsightPlugin getPlugin() {
if (plugin == null) { if (plugin == null) {
plugin = new InsightPlugin(); plugin = new InsightPlugin();
@ -116,11 +114,15 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
private volatile boolean connector_enabled = false; private volatile boolean connector_enabled = false;
private List<BRProfileBlock.ProfileBlock> profileBlocks; private List<BRProfileBlock.ProfileBlock> profileBlocks;
private InsightPlugin() { private InsightPlugin() {
super(new PluginDescription().mainType(PluginType.PUMP).fragmentClass(InsightFragment.class.getName()) super(new PluginDescription()
.pluginName(R.string.insightpump).shortName(R.string.insightpump_shortname) .mainType(PluginType.PUMP)
.preferencesId(R.xml.pref_insightpump).description(R.string.description_pump_insight)); .fragmentClass(InsightFragment.class.getName())
.pluginName(R.string.insightpump)
.shortName(R.string.insightpump_shortname)
.preferencesId(R.xml.pref_insightpump)
.description(R.string.description_pump_insight)
);
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin instantiated"); log.debug("InsightPlugin instantiated");
pumpDescription.setPumpDescription(PumpType.AccuChekInsight); pumpDescription.setPumpDescription(PumpType.AccuChekInsight);
@ -132,12 +134,10 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
MainApp.bus().post(new EventInsightUpdateGui()); MainApp.bus().post(new EventInsightUpdateGui());
} }
private static void pushCallbackEvent(EventInsightCallback e) { private static void pushCallbackEvent(EventInsightCallback e) {
MainApp.bus().post(e); MainApp.bus().post(e);
} }
@Override @Override
protected void onStart() { protected void onStart() {
if (!connector_enabled) { if (!connector_enabled) {
@ -154,7 +154,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
super.onStart(); super.onStart();
} }
protected void onStop() { protected void onStop() {
if (connector_enabled) { if (connector_enabled) {
synchronized (this) { synchronized (this) {
@ -168,13 +167,11 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
@Override @Override
public boolean isFakingTempsByExtendedBoluses() { public boolean isFakingTempsByExtendedBoluses() {
return true; return true;
} }
@Override @Override
public PumpEnactResult loadTDDs() { public PumpEnactResult loadTDDs() {
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
@ -182,76 +179,65 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
return result; return result;
} }
@Override @Override
public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) {
FragmentActivity context) {
boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);
if (allowHardwarePump || context == null) { if (allowHardwarePump || context == null) {
pluginSwitcher.invoke(); pluginSwitcher.invoke();
} else { } else {
AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.allow_hardware_pump_text) builder.setMessage(R.string.allow_hardware_pump_text)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
public void onClick(DialogInterface dialog, int id) { pluginSwitcher.invoke();
pluginSwitcher.invoke(); SP.putBoolean("allow_hardware_pump", true);
SP.putBoolean("allow_hardware_pump", true); log.debug("First time HW pump allowed!");
log.debug("First time HW pump allowed!"); }
} })
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
public void onClick(DialogInterface dialog, int id) { pluginSwitcher.cancel();
pluginSwitcher.cancel(); log.debug("User does not allow switching to HW pump!");
log.debug("User does not allow switching to HW pump!"); }
} });
});
builder.create().show(); builder.create().show();
} }
} }
@Override @Override
public boolean isInitialized() { public boolean isInitialized() {
return initialized; return initialized;
} }
@Override @Override
public boolean isSuspended() { public boolean isSuspended() {
return !isPumpRunning(); return !isPumpRunning();
} }
@Override @Override
public boolean isBusy() { public boolean isBusy() {
return false; return false;
} }
@Override @Override
public boolean isConnected() { public boolean isConnected() {
return Connector.get().isPumpConnected(); return Connector.get().isPumpConnected();
} }
@Override @Override
public boolean isConnecting() { public boolean isConnecting() {
return Connector.get().isPumpConnecting(); return Connector.get().isPumpConnecting();
} }
@Override @Override
public boolean isHandshakeInProgress() { public boolean isHandshakeInProgress() {
return false; return false;
} }
@Override @Override
public void finishHandshaking() { public void finishHandshaking() {
} }
@Override @Override
public void connect(String reason) { public void connect(String reason) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -276,7 +262,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
} }
@Override @Override
public void disconnect(String reason) { public void disconnect(String reason) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -295,7 +280,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
@Override @Override
public void stopConnecting() { public void stopConnecting() {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -319,7 +303,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
@Override @Override
public void getPumpStatus() { public void getPumpStatus() {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -328,8 +311,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("is connected.. requesting status"); log.debug("is connected.. requesting status");
try { try {
setStatusResult(fetchTaskRunner(new StatusTaskRunner(connector.getServiceConnector()), setStatusResult(fetchTaskRunner(new StatusTaskRunner(connector.getServiceConnector()), StatusTaskRunner.Result.class));
StatusTaskRunner.Result.class));
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("GOT STATUS RESULT!!! PARTY WOOHOO!!!"); log.debug("GOT STATUS RESULT!!! PARTY WOOHOO!!!");
statusResultTime = Helpers.tsl(); statusResultTime = Helpers.tsl();
@ -339,8 +321,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
connector.requestHistorySync(); connector.requestHistorySync();
} catch (Exception e) { } catch (Exception e) {
log.error("StatusTaskRunner wasn't successful."); log.error("StatusTaskRunner wasn't successful.");
if (connector.getServiceConnector().isConnectedToService() if (connector.getServiceConnector().isConnectedToService() && connector.getServiceConnector().getStatus() != Status.CONNECTED) {
&& connector.getServiceConnector().getStatus() != Status.CONNECTED) {
if (Helpers.ratelimit("insight-reconnect", 2)) { if (Helpers.ratelimit("insight-reconnect", 2)) {
Connector.connectToPump(); Connector.connectToPump();
updateGui(); updateGui();
@ -353,21 +334,18 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
public void setStatusResult(StatusTaskRunner.Result result) { public void setStatusResult(StatusTaskRunner.Result result) {
this.statusResult = result; this.statusResult = result;
this.pumpDescription.basalMinimumRate = result.minimumBasalAmount; this.pumpDescription.basalMinimumRate = result.minimumBasalAmount;
this.pumpDescription.basalMaximumRate = result.maximumBasalAmount; this.pumpDescription.basalMaximumRate = result.maximumBasalAmount;
} }
@Override @Override
public PumpEnactResult setNewBasalProfile(Profile profile) { public PumpEnactResult setNewBasalProfile(Profile profile) {
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
if (!isInitialized()) { if (!isInitialized()) {
log.error("setNewBasalProfile not initialized"); log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet); result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
return result; return result;
@ -379,41 +357,31 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
Profile.BasalValue nextValue = null; Profile.BasalValue nextValue = null;
if (profile.getBasalValues().length > i + 1) if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1]; nextValue = profile.getBasalValues()[i + 1];
profileBlocks.add(new BRProfileBlock.ProfileBlock((((nextValue != null ? nextValue.timeAsSeconds profileBlocks.add(new BRProfileBlock.ProfileBlock((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60), Helpers.roundDouble(basalValue.value, 2)));
: 24 * 60 * 60) - basalValue.timeAsSeconds) / 60), Helpers.roundDouble(basalValue.value, 2)));
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("setNewBasalProfile: " log.debug("setNewBasalProfile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
+ basalValue.value
+ " for "
+ Integer
.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
} }
try { try {
fetchTaskRunner(new WriteBasalProfileTaskRunner(connector.getServiceConnector(), profileBlocks)); fetchTaskRunner(new WriteBasalProfileTaskRunner(connector.getServiceConnector(), profileBlocks));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.success = true; result.success = true;
result.enacted = true; result.enacted = true;
result.comment = "OK"; result.comment = "OK";
this.profileBlocks = profileBlocks; this.profileBlocks = profileBlocks;
} catch (Exception e) { } catch (Exception e) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.failedupdatebasalprofile); result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
} }
return result; return result;
} }
@Override @Override
public boolean isThisProfileSet(Profile profile) { public boolean isThisProfileSet(Profile profile) {
if (!isInitialized() || profileBlocks == null) if (!isInitialized() || profileBlocks == null) return true;
return true; if (profile.getBasalValues().length != profileBlocks.size()) return false;
if (profile.getBasalValues().length != profileBlocks.size())
return false;
for (int i = 0; i < profileBlocks.size(); i++) { for (int i = 0; i < profileBlocks.size(); i++) {
BRProfileBlock.ProfileBlock profileBlock = profileBlocks.get(i); BRProfileBlock.ProfileBlock profileBlock = profileBlocks.get(i);
Profile.BasalValue basalValue = profile.getBasalValues()[i]; Profile.BasalValue basalValue = profile.getBasalValues()[i];
@ -421,44 +389,38 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (profile.getBasalValues().length > i + 1) if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1]; nextValue = profile.getBasalValues()[i + 1];
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("isThisProfileSet - Comparing block: Pump: " log.debug("isThisProfileSet - Comparing block: Pump: " + profileBlock.getAmount() + " for " + profileBlock.getDuration()
+ profileBlock.getAmount() + " Profile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
+ " for " if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds)
+ profileBlock.getDuration()
+ " Profile: "
+ basalValue.value
+ " for "
+ Integer
.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60)
- basalValue.timeAsSeconds)
return false; return false;
// Allow a little imprecision due to rounding errors //Allow a little imprecision due to rounding errors
if (Math.abs(profileBlock.getAmount() - Helpers.roundDouble(basalValue.value, 2)) >= 0.01D) if (Math.abs(profileBlock.getAmount() - Helpers.roundDouble(basalValue.value, 2)) >= 0.01D)
return false; return false;
} }
return true; return true;
} }
@Override @Override
public long lastDataTime() { public long lastDataTime() {
return lastDataTime; return lastDataTime;
} }
@Override @Override
public double getBaseBasalRate() { public double getBaseBasalRate() {
return basalRate; return basalRate;
} }
@Override
public double getReservoirLevel() { return reservoirInUnits; }
@Override
public int getBatteryLevel() { return batteryPercent; }
public String getBaseBasalRateString() { public String getBaseBasalRateString() {
final DecimalFormat df = new DecimalFormat("#.##"); final DecimalFormat df = new DecimalFormat("#.##");
return df.format(basalRate); return df.format(basalRate);
} }
@Override @Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
final PumpEnactResult result = new PumpEnactResult(); final PumpEnactResult result = new PumpEnactResult();
@ -503,50 +465,39 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
+ detailedBolusInfo.carbs + "g " + result);
updateGui(); updateGui();
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
if (result.success) if (result.success) while (true) {
while (true) { try {
try { Thread.sleep(500);
Thread.sleep(500); final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); ActiveBolusesMessage activeBolusesMessage = fetchSingleMessage(new ActiveBolusesMessage(), ActiveBolusesMessage.class);
ActiveBolusesMessage activeBolusesMessage = fetchSingleMessage(new ActiveBolusesMessage(), ActiveBolus activeBolus = null;
ActiveBolusesMessage.class); if (activeBolusesMessage.getBolus1() != null && activeBolusesMessage.getBolus1().getBolusID() == bolusingEvent.bolusId)
ActiveBolus activeBolus = null; activeBolus = activeBolusesMessage.getBolus1();
if (activeBolusesMessage.getBolus1() != null else if (activeBolusesMessage.getBolus2() != null && activeBolusesMessage.getBolus2().getBolusID() == bolusingEvent.bolusId)
&& activeBolusesMessage.getBolus1().getBolusID() == bolusingEvent.bolusId) activeBolus = activeBolusesMessage.getBolus2();
activeBolus = activeBolusesMessage.getBolus1(); else if (activeBolusesMessage.getBolus3() != null && activeBolusesMessage.getBolus3().getBolusID() == bolusingEvent.bolusId)
else if (activeBolusesMessage.getBolus2() != null activeBolus = activeBolusesMessage.getBolus3();
&& activeBolusesMessage.getBolus2().getBolusID() == bolusingEvent.bolusId) if (activeBolus == null) break;
activeBolus = activeBolusesMessage.getBolus2(); else {
else if (activeBolusesMessage.getBolus3() != null int percentBefore = bolusingEvent.percent;
&& activeBolusesMessage.getBolus3().getBolusID() == bolusingEvent.bolusId) bolusingEvent.percent = (int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount()));
activeBolus = activeBolusesMessage.getBolus3(); bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount());
if (activeBolus == null) if (percentBefore != bolusingEvent.percent) MainApp.bus().post(bolusingEvent);
break;
else {
int percentBefore = bolusingEvent.percent;
bolusingEvent.percent = (int)(100D / activeBolus.getInitialAmount() * (activeBolus
.getInitialAmount() - activeBolus.getLeftoverAmount()));
bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering),
activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount());
if (percentBefore != bolusingEvent.percent)
MainApp.bus().post(bolusingEvent);
}
} catch (Exception e) {
break;
} }
} catch (Exception e) {
break;
} }
}
connector.requestHistorySync(2000); connector.requestHistorySync(2000);
return result; return result;
} }
@Override @Override
public void stopBolusDelivering() { public void stopBolusDelivering() {
CancelBolusMessage cancelBolusMessage = new CancelBolusMessage(); CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
@ -558,12 +509,10 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
// Temporary Basals // Temporary Basals
@Override @Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
boolean enforceNew) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Set TBR absolute: " + absoluteRate); log.debug("Set TBR absolute: " + absoluteRate);
if (getBaseBasalRate() == 0) { if (getBaseBasalRate() == 0) {
@ -573,27 +522,24 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
double percent = 100D / getBaseBasalRate() * absoluteRate; double percent = 100D / getBaseBasalRate() * absoluteRate;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Calculated requested rate: " + absoluteRate + " base rate: " + getBaseBasalRate() log.debug("Calculated requested rate: " + absoluteRate + " base rate: " + getBaseBasalRate() + " percentage: " + percent + "%");
+ " percentage: " + percent + "%");
try { try {
if (percent > 250) { if (percent > 250) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Calculated rate is above 250%, switching to emulation using extended boluses"); log.debug("Calculated rate is above 250%, switching to emulation using extended boluses");
cancelTempBasal(true); cancelTempBasal(true);
if (!setExtendedBolus((absoluteRate - getBaseBasalRate()) / 60D * ((double)durationInMinutes), if (!setExtendedBolus((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes).success) {
durationInMinutes).success) { //Fallback to TBR if setting an extended bolus didn't work
// Fallback to TBR if setting an extended bolus didn't work
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Setting an extended bolus didn't work, falling back to normal TBR"); log.debug("Setting an extended bolus didn't work, falling back to normal TBR");
return setTempBasalPercent((int)percent, durationInMinutes, profile, true); return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
} }
return new PumpEnactResult().success(true).enacted(true).absolute(absoluteRate) return new PumpEnactResult().success(true).enacted(true).absolute(absoluteRate).duration(durationInMinutes);
.duration(durationInMinutes);
} else { } else {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Calculated rate is below or equal to 250%, using normal TBRs"); log.debug("Calculated rate is below or equal to 250%, using normal TBRs");
cancelExtendedBolus(); cancelExtendedBolus();
return setTempBasalPercent((int)percent, durationInMinutes, profile, true); return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
} }
} catch (Exception e) { } catch (Exception e) {
return pumpEnactFailure(); return pumpEnactFailure();
@ -602,22 +548,23 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
boolean enforceNew) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Set TBR %"); log.debug("Set TBR %");
percent = (int)Math.round(((double)percent) / 10d) * 10; percent = (int) Math.round(((double) percent) / 10d) * 10;
if (percent == 100) { if (percent == 100) {
// This would cause a cancel if a tbr is in progress so treat as a cancel // This would cause a cancel if a tbr is in progress so treat as a cancel
return cancelTempBasal(false); return cancelTempBasal(false);
} else if (percent > 250) } else if (percent > 250) percent = 250;
percent = 250;
try { try {
fetchTaskRunner(new SetTBRTaskRunner(connector.getServiceConnector(), percent, durationInMinutes)); fetchTaskRunner(new SetTBRTaskRunner(connector.getServiceConnector(), percent, durationInMinutes));
final TemporaryBasal tempBasal = new TemporaryBasal().date(System.currentTimeMillis()).percent(percent) final TemporaryBasal tempBasal = new TemporaryBasal()
.duration(durationInMinutes).source(Source.USER); .date(System.currentTimeMillis())
.percent(percent)
.duration(durationInMinutes)
.source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
updateGui(); updateGui();
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -650,10 +597,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
private void realTBRCancel() throws Exception { private void realTBRCancel() throws Exception {
if (fetchTaskRunner(new CancelTBRSilentlyTaskRunner(connector.getServiceConnector()), Boolean.class) if (fetchTaskRunner(new CancelTBRSilentlyTaskRunner(connector.getServiceConnector()), Boolean.class) && TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
&& TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
TemporaryBasal tempStop = new TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER); TemporaryBasal tempStop = new TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop);
} }
@ -671,21 +616,22 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
extendedBolusMessage.setAmount(insulin); extendedBolusMessage.setAmount(insulin);
extendedBolusMessage.setDuration(durationInMinutes); extendedBolusMessage.setDuration(durationInMinutes);
BolusMessage bolusMessage = fetchSingleMessage(extendedBolusMessage, BolusMessage.class); BolusMessage bolusMessage = fetchSingleMessage(extendedBolusMessage, BolusMessage.class);
final ExtendedBolus extendedBolus = new ExtendedBolus().date(System.currentTimeMillis()).insulin(insulin) final ExtendedBolus extendedBolus = new ExtendedBolus()
.durationInMinutes(durationInMinutes).source(Source.USER) .date(System.currentTimeMillis())
.pumpId(getRecordUniqueID(bolusMessage.getBolusId())); .insulin(insulin)
.durationInMinutes(durationInMinutes)
.source(Source.USER)
.pumpId(getRecordUniqueID(bolusMessage.getBolusId()));
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
updateGui(); updateGui();
connector.requestHistorySync(30000); connector.requestHistorySync(30000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes) return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin);
.bolusDelivered(insulin);
} catch (Exception e) { } catch (Exception e) {
return pumpEnactFailure(); return pumpEnactFailure();
} }
} }
@Override @Override
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -694,15 +640,13 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
Integer bolusId = null; Integer bolusId = null;
try { try {
bolusId = fetchTaskRunner(new CancelBolusSilentlyTaskRunner(connector.getServiceConnector(), bolusId = fetchTaskRunner(new CancelBolusSilentlyTaskRunner(connector.getServiceConnector(), ActiveBolusType.EXTENDED), Integer.class);
ActiveBolusType.EXTENDED), Integer.class);
if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
ExtendedBolus exStop = new ExtendedBolus(System.currentTimeMillis()); ExtendedBolus exStop = new ExtendedBolus(System.currentTimeMillis());
exStop.source = Source.USER; exStop.source = Source.USER;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop);
} }
if (bolusId != null) if (bolusId != null) connector.requestHistorySync(5000);
connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
updateGui(); updateGui();
return new PumpEnactResult().success(true).enacted(bolusId != null); return new PumpEnactResult().success(true).enacted(bolusId != null);
@ -722,7 +666,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
return fetchSingleMessage(message, BolusMessage.class).getBolusId(); return fetchSingleMessage(message, BolusMessage.class).getBolusId();
} }
@Override @Override
public JSONObject getJSONStatus(Profile profile, String profileName) { public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@ -771,53 +714,44 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
return pump; return pump;
} }
@Override @Override
public String deviceID() { public String deviceID() {
return "InsightPump"; return "InsightPump";
} }
@Override @Override
public PumpDescription getPumpDescription() { public PumpDescription getPumpDescription() {
return pumpDescription; return pumpDescription;
} }
@Override @Override
public String shortStatus(boolean veryShort) { public String shortStatus(boolean veryShort) {
String msg = gs(R.string.insightpump_shortname) + " Batt: " + batteryPercent + " Reserv: " + reservoirInUnits String msg = gs(R.string.insightpump_shortname) + " Batt: " + batteryPercent + " Reserv: " + reservoirInUnits + " Basal: " + basalRate;
+ " Basal: " + basalRate;
if (LiveHistory.getStatus().length() > 0) { if (LiveHistory.getStatus().length() > 0) {
msg += LiveHistory.getStatus(); msg += LiveHistory.getStatus();
} }
return msg; return msg;
} }
private void processStatusResult() { private void processStatusResult() {
if (statusResult != null) { if (statusResult != null) {
batteryPercent = statusResult.battery; batteryPercent = statusResult.battery;
reservoirInUnits = (int)statusResult.cartridge; reservoirInUnits = (int) statusResult.cartridge;
basalRate = statusResult.baseBasalRate; basalRate = statusResult.baseBasalRate;
profileBlocks = statusResult.basalProfile; profileBlocks = statusResult.basalProfile;
initialized = true; // basic communication test initialized = true; // basic communication test
} }
} }
private String gs(int id) { private String gs(int id) {
return MainApp.gs(id); return MainApp.gs(id);
} }
private boolean isPumpRunning() { private boolean isPumpRunning() {
if (statusResult == null) if (statusResult == null) return true; // assume running if we have no information
return true; // assume running if we have no information
return statusResult.pumpStatus == PumpStatus.STARTED; return statusResult.pumpStatus == PumpStatus.STARTED;
} }
List<StatusItem> getStatusItems(boolean refresh) { List<StatusItem> getStatusItems(boolean refresh) {
final List<StatusItem> l = new ArrayList<>(); final List<StatusItem> l = new ArrayList<>();
@ -834,8 +768,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (pumpRunning) { if (pumpRunning) {
l.add(new StatusItem(gs(R.string.pump_basebasalrate_label), getBaseBasalRateString() + "U")); l.add(new StatusItem(gs(R.string.pump_basebasalrate_label), getBaseBasalRateString() + "U"));
} else { } else {
l.add(new StatusItem(gs(R.string.combo_warning), gs(R.string.pump_stopped_uppercase), l.add(new StatusItem(gs(R.string.combo_warning), gs(R.string.pump_stopped_uppercase), StatusItem.Highlight.CRITICAL));
StatusItem.Highlight.CRITICAL));
} }
} }
@ -843,17 +776,17 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
final long offset_minutes = offset_ms / 60000; final long offset_minutes = offset_ms / 60000;
if (statusResult != null) { if (statusResult != null) {
l.add(new StatusItem(gs(R.string.status_updated), Helpers.niceTimeScalar(Helpers.msSince(statusResultTime)) l.add(new StatusItem(gs(R.string.status_updated), Helpers.niceTimeScalar(Helpers.msSince(statusResultTime)) + " " + gs(R.string.ago)));
+ " " + gs(R.string.ago))); l.add(new StatusItem(gs(R.string.pump_battery_label), batteryPercent + "%", batteryPercent < 100 ?
l.add(new StatusItem(gs(R.string.pump_battery_label), batteryPercent + "%", (batteryPercent < 90 ?
batteryPercent < 100 ? (batteryPercent < 90 ? (batteryPercent < 70 ? (StatusItem.Highlight.BAD) (batteryPercent < 70 ?
: StatusItem.Highlight.NOTICE) : StatusItem.Highlight.NORMAL) : StatusItem.Highlight.GOOD)); (StatusItem.Highlight.BAD) : StatusItem.Highlight.NOTICE) : StatusItem.Highlight.NORMAL) : StatusItem.Highlight.GOOD));
l.add(new StatusItem(gs(R.string.pump_reservoir_label), reservoirInUnits + "U")); l.add(new StatusItem(gs(R.string.pump_reservoir_label), reservoirInUnits + "U"));
try { try {
if (statusResult.tbrAmount != 100) { if (statusResult.tbrAmount != 100) {
l.add(new StatusItem(gs(R.string.insight_active_tbr), statusResult.tbrAmount + "% " l.add(new StatusItem(gs(R.string.insight_active_tbr), statusResult.tbrAmount + "% " + gs(R.string.with) + " "
+ gs(R.string.with) + " " + Helpers.qs(statusResult.tbrLeftoverDuration - offset_minutes, 0) + Helpers.qs(statusResult.tbrLeftoverDuration - offset_minutes, 0)
+ " " + gs(R.string.insight_min_left), StatusItem.Highlight.NOTICE)); + " " + gs(R.string.insight_min_left), StatusItem.Highlight.NOTICE));
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
// currentTBRMessage may be null // currentTBRMessage may be null
@ -863,8 +796,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) { if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
try { try {
l.add(new StatusItem(gs(R.string.pump_tempbasal_label), TreatmentsPlugin.getPlugin() l.add(new StatusItem(gs(R.string.pump_tempbasal_label), TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()).toStringFull()));
.getTempBasalFromHistory(System.currentTimeMillis()).toStringFull()));
} catch (NullPointerException e) { } catch (NullPointerException e) {
// //
} }
@ -883,8 +815,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
try { try {
l.add(new StatusItem(gs(R.string.virtualpump_extendedbolus_label), TreatmentsPlugin.getPlugin() l.add(new StatusItem(gs(R.string.virtualpump_extendedbolus_label), TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()).toString()));
.getExtendedBolusFromHistory(System.currentTimeMillis()).toString()));
} catch (NullPointerException e) { } catch (NullPointerException e) {
// //
} }
@ -910,18 +841,15 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
} }
connector.requestHistorySync(); connector.requestHistorySync();
if (refresh) if (refresh) scheduleGUIUpdate();
scheduleGUIUpdate();
return l; return l;
} }
private synchronized void scheduleGUIUpdate() { private synchronized void scheduleGUIUpdate() {
if (!update_pending && connector.uiFresh()) { if (!update_pending && connector.uiFresh()) {
update_pending = true; update_pending = true;
Helpers.runOnUiThreadDelayed(new Runnable() { Helpers.runOnUiThreadDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
updateGui(); updateGui();
@ -930,41 +858,20 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
private void statusActiveBolus(ActiveBolus activeBolus, long offset_mins, List<StatusItem> l) { private void statusActiveBolus(ActiveBolus activeBolus, long offset_mins, List<StatusItem> l) {
if (activeBolus == null) if (activeBolus == null) return;
return;
switch (activeBolus.getBolusType()) { switch (activeBolus.getBolusType()) {
case STANDARD: case STANDARD:
l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U", StatusItem.Highlight.NOTICE));
.getInitialAmount() + "U", StatusItem.Highlight.NOTICE));
break; break;
case EXTENDED: case EXTENDED:
l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U " + gs(R.string.insight_total_with) + " "
.getInitialAmount() + activeBolus.getLeftoverAmount() + "U " + gs(R.string.insight_remaining_over) + " " + (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min), StatusItem.Highlight.NOTICE));
+ "U "
+ gs(R.string.insight_total_with)
+ " "
+ activeBolus.getLeftoverAmount()
+ "U "
+ gs(R.string.insight_remaining_over)
+ " "
+ (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min),
StatusItem.Highlight.NOTICE));
break; break;
case MULTIWAVE: case MULTIWAVE:
l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U " + gs(R.string.insight_upfront_with) + " "
.getInitialAmount() + activeBolus.getLeftoverAmount() + "U " + gs(R.string.insight_remaining_over) + " " + (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min), StatusItem.Highlight.NOTICE));
+ "U "
+ gs(R.string.insight_upfront_with)
+ " "
+ activeBolus.getLeftoverAmount()
+ "U "
+ gs(R.string.insight_remaining_over)
+ " "
+ (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min),
StatusItem.Highlight.NOTICE));
break; break;
default: default:
@ -972,40 +879,32 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
private void fetchTaskRunner(TaskRunner taskRunner) throws Exception { private void fetchTaskRunner(TaskRunner taskRunner) throws Exception {
fetchTaskRunner(taskRunner, Object.class); fetchTaskRunner(taskRunner, Object.class);
} }
private void fetchSingleMessage(AppLayerMessage message) throws Exception { private void fetchSingleMessage(AppLayerMessage message) throws Exception {
fetchSingleMessage(message, AppLayerMessage.class); fetchSingleMessage(message, AppLayerMessage.class);
} }
private <T> T fetchTaskRunner(TaskRunner taskRunner, Class<T> resultType) throws Exception { private <T> T fetchTaskRunner(TaskRunner taskRunner, Class<T> resultType) throws Exception {
try { try {
T result = (T)taskRunner.fetchAndWaitUsingLatch(BUSY_WAIT_TIME); T result = (T) taskRunner.fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
lastDataTime = System.currentTimeMillis(); lastDataTime = System.currentTimeMillis();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
log.error("Error while fetching " + taskRunner.getClass().getSimpleName() + ": " log.error("Error while fetching " + taskRunner.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
+ e.getClass().getSimpleName());
throw e; throw e;
} }
} }
private <T extends AppLayerMessage> T fetchSingleMessage(AppLayerMessage message, Class<T> resultType) throws Exception {
private <T extends AppLayerMessage> T fetchSingleMessage(AppLayerMessage message, Class<T> resultType)
throws Exception {
try { try {
T result = (T)new SingleMessageTaskRunner(connector.getServiceConnector(), message) T result = (T) new SingleMessageTaskRunner(connector.getServiceConnector(), message).fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
.fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
lastDataTime = System.currentTimeMillis(); lastDataTime = System.currentTimeMillis();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
log.error("Error while fetching " + message.getClass().getSimpleName() + ": " log.error("Error while fetching " + message.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
+ e.getClass().getSimpleName());
throw e; throw e;
} }
} }
@ -1015,40 +914,27 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
return new PumpEnactResult().success(false).enacted(false); return new PumpEnactResult().success(false).enacted(false);
} }
// Constraints // Constraints
@Override @Override
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) { public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) {
percentRate.setIfGreater(0, percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this);
String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this);
this);
percentRate.setIfSmaller(
getPumpDescription().maxTempPercent,
String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent,
MainApp.gs(R.string.pumplimit)), this);
return percentRate; return percentRate;
} }
@Override @Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) { public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) {
if (statusResult != null) { if (statusResult != null) {
insulin.setIfSmaller( insulin.setIfSmaller(statusResult.maximumBolusAmount, String.format(MainApp.gs(R.string.limitingbolus), statusResult.maximumBolusAmount, MainApp.gs(R.string.pumplimit)), this);
statusResult.maximumBolusAmount,
String.format(MainApp.gs(R.string.limitingbolus), statusResult.maximumBolusAmount,
MainApp.gs(R.string.pumplimit)), this);
if (insulin.value() < statusResult.minimumBolusAmount) { if (insulin.value() < statusResult.minimumBolusAmount) {
// TODO: Add function to Constraints or use different approach //TODO: Add function to Constraints or use different approach
// This only works if the interface of the InsightPlugin is called last. // This only works if the interface of the InsightPlugin is called last.
// If not, another contraint could theoretically set the value between 0 and minimumBolusAmount // If not, another contraint could theoretically set the value between 0 and minimumBolusAmount
insulin.set( insulin.set(0d, String.format(MainApp.gs(R.string.limitingbolus), statusResult.minimumBolusAmount, MainApp.gs(R.string.pumplimit)), this);
0d,
String.format(MainApp.gs(R.string.limitingbolus), statusResult.minimumBolusAmount,
MainApp.gs(R.string.pumplimit)), this);
} }
} }
return insulin; return insulin;

View file

@ -0,0 +1,6 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal;
import info.nightscout.androidaps.events.EventUpdateGui;
public class EventLocalInsightUpdateGUI extends EventUpdateGui {
}

View file

@ -0,0 +1,260 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpInsightLocal.activities.InsightAlertActivity;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control.ConfirmAlertMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control.SnoozeAlertMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status.GetActiveAlertMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.connection_service.InsightConnectionService;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.Alert;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.AlertStatus;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.AlertType;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.InsightState;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.InsightException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.app_layer_errors.AppLayerErrorException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ExceptionTranslator;
public class InsightAlertService extends Service implements InsightConnectionService.StateCallback {
private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
private LocalBinder localBinder = new LocalBinder();
private boolean connectionRequested;
private final Object $alertLock = new Object[0];
private Alert alert;
private Thread thread;
private InsightAlertActivity alertActivity;
private Ringtone ringtone;
private Vibrator vibrator;
private boolean vibrating;
private InsightConnectionService connectionService;
private long ignoreTimestamp;
private AlertType ignoreType;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
connectionService = ((InsightConnectionService.LocalBinder) binder).getService();
connectionService.registerStateCallback(InsightAlertService.this);
onStateChanged(connectionService.getState());
}
@Override
public void onServiceDisconnected(ComponentName name) {
connectionService = null;
}
};
private void retrieveRingtone() {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
ringtone = RingtoneManager.getRingtone(this, uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ringtone.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.setLegacyStreamType(AudioManager.STREAM_RING).build());
} else ringtone.setStreamType(AudioManager.STREAM_RING);
}
public Alert getAlert() {
synchronized ($alertLock) {
return alert;
}
}
public void setAlertActivity(InsightAlertActivity alertActivity) {
this.alertActivity = alertActivity;
}
public void ignore(AlertType alertType) {
synchronized ($alertLock) {
if (alertType == null) {
ignoreTimestamp = 0;
ignoreType = null;
} else {
ignoreTimestamp = System.currentTimeMillis();
ignoreType = alertType;
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return localBinder;
}
@Override
public void onCreate() {
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
bindService(new Intent(this, InsightConnectionService.class), serviceConnection, BIND_AUTO_CREATE);
}
@Override
public void onDestroy() {
if (thread != null) thread.interrupt();
unbindService(serviceConnection);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onStateChanged(InsightState state) {
if (state == InsightState.CONNECTED) {
thread = new Thread(this::queryActiveAlert);
thread.start();
} else if (thread != null) thread.interrupt();
}
private void queryActiveAlert() {
while (!Thread.currentThread().isInterrupted()) {
try {
Alert alert = connectionService.requestMessage(new GetActiveAlertMessage()).await().getAlert();
if (Thread.currentThread().isInterrupted()) {
connectionService.withdrawConnectionRequest(thread);
break;
}
synchronized ($alertLock) {
if ((this.alert == null && alert != null)
|| (this.alert != null && alert == null)
|| (this.alert != null && alert != null && !this.alert.equals(alert))) {
if (this.alert != null && (alert == null || this.alert.getAlertId() != alert.getAlertId())) stopAlerting();
this.alert = alert;
if (alertActivity != null && alert != null)
new Handler(Looper.getMainLooper()).post(() -> alertActivity.update(alert));
}
if (alert == null) {
stopAlerting();
if (connectionRequested) {
connectionService.withdrawConnectionRequest(this);
connectionRequested = false;
}
if (alertActivity != null)
new Handler(Looper.getMainLooper()).post(() -> alertActivity.finish());
} else if (!(alert.getAlertType() == ignoreType && System.currentTimeMillis() - ignoreTimestamp < 10000)) {
if (alert.getAlertStatus() == AlertStatus.ACTIVE) alert();
else stopAlerting();
if (!connectionRequested) {
connectionService.requestConnection(this);
connectionRequested = true;
}
if (alertActivity == null) {
Intent intent = new Intent(InsightAlertService.this, InsightAlertActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
new Handler(Looper.getMainLooper()).post(() -> startActivity(intent));
}
}
}
} catch (InterruptedException ignored) {
connectionService.withdrawConnectionRequest(thread);
break;
} catch (AppLayerErrorException e) {
log.info("Exception while fetching alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
} catch (InsightException e) {
log.info("Exception while fetching alert: " + e.getClass().getSimpleName());
} catch (Exception e) {
log.error("Exception while fetching alert", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
if (connectionRequested) {
connectionService.withdrawConnectionRequest(thread);
connectionRequested = false;
}
if (alertActivity != null)
new Handler(Looper.getMainLooper()).post(() -> alertActivity.finish());
stopAlerting();
thread = null;
}
private void alert() {
if (!vibrating) {
vibrator.vibrate(new long[] {0, 1000, 1000}, 0);
vibrating = true;
}
if (ringtone == null || !ringtone.isPlaying()) {
retrieveRingtone();
ringtone.play();
}
}
private void stopAlerting() {
if (vibrating) {
vibrator.cancel();
vibrating = false;
}
if (ringtone != null && ringtone.isPlaying()) ringtone.stop();
}
public void mute() {
new Thread(() -> {
try {
SnoozeAlertMessage snoozeAlertMessage = new SnoozeAlertMessage();
snoozeAlertMessage.setAlertID(alert.getAlertId());
connectionService.requestMessage(snoozeAlertMessage).await();
} catch (AppLayerErrorException e) {
log.info("Exception while muting alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
ExceptionTranslator.makeToast(InsightAlertService.this, e);
} catch (InsightException e) {
log.info("Exception while muting alert: " + e.getClass().getSimpleName());
ExceptionTranslator.makeToast(InsightAlertService.this, e);
} catch (Exception e) {
log.error("Exception while muting alert", e);
ExceptionTranslator.makeToast(InsightAlertService.this, e);
}
}).start();
}
public void confirm() {
new Thread(() -> {
try {
ConfirmAlertMessage confirmAlertMessage = new ConfirmAlertMessage();
confirmAlertMessage.setAlertID(alert.getAlertId());
connectionService.requestMessage(confirmAlertMessage).await();
} catch (AppLayerErrorException e) {
log.info("Exception while confirming alert: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
ExceptionTranslator.makeToast(InsightAlertService.this, e);
} catch (InsightException e) {
log.info("Exception while confirming alert: " + e.getClass().getSimpleName());
ExceptionTranslator.makeToast(InsightAlertService.this, e);
} catch (Exception e) {
log.error("Exception while confirming alert", e);
ExceptionTranslator.makeToast(InsightAlertService.this, e);
}
}).start();
}
public class LocalBinder extends Binder {
public InsightAlertService getService() {
return InsightAlertService.this;
}
}
}

View file

@ -0,0 +1,302 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.otto.Subscribe;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks.TBROverNotificationBlock;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.ActiveBasalRate;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.ActiveBolus;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.ActiveTBR;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.CartridgeStatus;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.InsightState;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.TotalDailyDose;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
public class LocalInsightFragment extends SubscriberFragment implements View.OnClickListener {
private static final boolean ENABLE_OPERATING_MODE_BUTTON = false;
private boolean viewsCreated;
private Button operatingMode;
private Button tbrOverNotification;
private Button refresh;
private LinearLayout statusItemContainer = null;
private Callback operatingModeCallback;
private Callback tbrOverNotificationCallback;
private Callback refreshCallback;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.local_insight_fragment, container, false);
statusItemContainer = view.findViewById(R.id.status_item_container);
tbrOverNotification = view.findViewById(R.id.tbr_over_notification);
tbrOverNotification.setOnClickListener(this);
operatingMode = view.findViewById(R.id.operating_mode);
operatingMode.setOnClickListener(this);
refresh = view.findViewById(R.id.refresh);
refresh.setOnClickListener(this);
viewsCreated = true;
return view;
}
@Override
public synchronized void onDestroyView() {
super.onDestroyView();
viewsCreated = false;
}
@Override
public void onClick(View v) {
if (v == operatingMode) {
if (LocalInsightPlugin.getInstance().getOperatingMode() != null) {
operatingMode.setEnabled(false);
operatingModeCallback = new Callback() {
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(() -> {
operatingModeCallback = null;
updateGUI();
});
}
};
switch (LocalInsightPlugin.getInstance().getOperatingMode()) {
case PAUSED:
case STOPPED:
ConfigBuilderPlugin.getPlugin().getCommandQueue().startPump(operatingModeCallback);
break;
case STARTED:
ConfigBuilderPlugin.getPlugin().getCommandQueue().stopPump(operatingModeCallback);
}
}
} else if (v == tbrOverNotification) {
TBROverNotificationBlock notificationBlock = LocalInsightPlugin.getInstance().getTBROverNotificationBlock();
if (notificationBlock != null) {
tbrOverNotification.setEnabled(false);
tbrOverNotificationCallback = new Callback() {
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(() -> {
tbrOverNotificationCallback = null;
updateGUI();
});
}
};
ConfigBuilderPlugin.getPlugin().getCommandQueue()
.setTBROverNotification(tbrOverNotificationCallback, !notificationBlock.isEnabled());
}
} else if (v == refresh) {
refresh.setEnabled(false);
refreshCallback = new Callback() {
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(() -> {
refreshCallback = null;
updateGUI();
});
}
};
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("InsightRefreshButton", refreshCallback);
}
}
@Subscribe
public void onUpdateGUIEvent(EventLocalInsightUpdateGUI event) {
updateGUI();
}
@Override
protected void updateGUI() {
if (!viewsCreated) return;
statusItemContainer.removeAllViews();
if (!LocalInsightPlugin.getInstance().isInitialized()) {
operatingMode.setVisibility(View.GONE);
tbrOverNotification.setVisibility(View.GONE);
refresh.setVisibility(View.GONE);
return;
}
refresh.setVisibility(View.VISIBLE);
refresh.setEnabled(refreshCallback == null);
TBROverNotificationBlock notificationBlock = LocalInsightPlugin.getInstance().getTBROverNotificationBlock();
tbrOverNotification.setVisibility(notificationBlock == null ? View.GONE : View.VISIBLE);
if (notificationBlock != null)
tbrOverNotification.setText(notificationBlock.isEnabled() ? R.string.disable_tbr_over_notification : R.string.enable_tbr_over_notification);
tbrOverNotification.setEnabled(tbrOverNotificationCallback == null);
List<View> statusItems = new ArrayList<>();
getConnectionStatusItem(statusItems);
getLastConnectedItem(statusItems);
getOperatingModeItem(statusItems);
getBatteryStatusItem(statusItems);
getCartridgeStatusItem(statusItems);
getTDDItems(statusItems);
getBaseBasalRateItem(statusItems);
getTBRItem(statusItems);
getBolusItems(statusItems);
for (int i = 0; i < statusItems.size(); i++) {
statusItemContainer.addView(statusItems.get(i));
if (i != statusItems.size() - 1)
getLayoutInflater().inflate(R.layout.local_insight_status_delimitter, statusItemContainer);
}
}
private View getStatusItem(String label, String value) {
View statusItem = getLayoutInflater().inflate(R.layout.local_insight_status_item, null);
((TextView) statusItem.findViewById(R.id.label)).setText(label);
((TextView) statusItem.findViewById(R.id.value)).setText(value);
return statusItem;
}
private void getConnectionStatusItem(List<View> statusItems) {
int string = 0;
InsightState state = LocalInsightPlugin.getInstance().getConnectionService().getState();
switch (state) {
case NOT_PAIRED:
string = R.string.not_paired;
break;
case DISCONNECTED:
string = R.string.disconnected;
break;
case CONNECTING:
case SATL_CONNECTION_REQUEST:
case SATL_KEY_REQUEST:
case SATL_SYN_REQUEST:
case SATL_VERIFY_CONFIRM_REQUEST:
case SATL_VERIFY_DISPLAY_REQUEST:
case APP_ACTIVATE_PARAMETER_SERVICE:
case APP_ACTIVATE_STATUS_SERVICE:
case APP_BIND_MESSAGE:
case APP_CONNECT_MESSAGE:
case APP_FIRMWARE_VERSIONS:
case APP_SYSTEM_IDENTIFICATION:
case AWAITING_CODE_CONFIRMATION:
string = R.string.connecting;
break;
case CONNECTED:
string = R.string.connected;
break;
case RECOVERING:
string = R.string.recovering;
break;
}
statusItems.add(getStatusItem(MainApp.gs(R.string.insight_status), MainApp.gs(string)));
if (state == InsightState.RECOVERING) {
statusItems.add(getStatusItem(MainApp.gs(R.string.recovery_duration), LocalInsightPlugin.getInstance().getConnectionService().getRecoveryDuration() / 1000 + "s"));
}
}
private void getLastConnectedItem(List<View> statusItems) {
switch (LocalInsightPlugin.getInstance().getConnectionService().getState()) {
case CONNECTED:
case NOT_PAIRED:
return;
default:
long lastConnection = LocalInsightPlugin.getInstance().getConnectionService().getLastConnected();
if (lastConnection == 0) return;
int min = (int) ((System.currentTimeMillis() - lastConnection) / 60000);
statusItems.add(getStatusItem(MainApp.gs(R.string.last_connected), DateUtil.timeString(lastConnection)));
}
}
private void getOperatingModeItem(List<View> statusItems) {
if (LocalInsightPlugin.getInstance().getOperatingMode() == null) {
operatingMode.setVisibility(View.GONE);
return;
}
int string = 0;
if (ENABLE_OPERATING_MODE_BUTTON) operatingMode.setVisibility(View.VISIBLE);
operatingMode.setEnabled(operatingModeCallback == null);
switch (LocalInsightPlugin.getInstance().getOperatingMode()) {
case STARTED:
operatingMode.setText(R.string.stop_pump);
string = R.string.started;
break;
case STOPPED:
operatingMode.setText(R.string.start_pump);
string = R.string.stopped;
break;
case PAUSED:
operatingMode.setText(R.string.start_pump);
string = R.string.paused;
break;
}
statusItems.add(getStatusItem(MainApp.gs(R.string.operating_mode), MainApp.gs(string)));
}
private void getBatteryStatusItem(List<View> statusItems) {
if (LocalInsightPlugin.getInstance().getBatteryStatus() == null) return;
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_battery_label),
LocalInsightPlugin.getInstance().getBatteryStatus().getBatteryAmount() + "%"));
}
private void getCartridgeStatusItem(List<View> statusItems) {
CartridgeStatus cartridgeStatus = LocalInsightPlugin.getInstance().getCartridgeStatus();
if (cartridgeStatus == null) return;
String status;
if (cartridgeStatus.isInserted())
status = DecimalFormatter.to2Decimal(LocalInsightPlugin.getInstance().getCartridgeStatus().getRemainingAmount()) + "U";
else status = MainApp.gs(R.string.not_inserted);
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_reservoir_label), status));
}
private void getTDDItems(List<View> statusItems) {
if (LocalInsightPlugin.getInstance().getTotalDailyDose() == null) return;
TotalDailyDose tdd = LocalInsightPlugin.getInstance().getTotalDailyDose();
statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_bolus), DecimalFormatter.to2Decimal(tdd.getBolus())));
statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_basal), DecimalFormatter.to2Decimal(tdd.getBasal())));
statusItems.add(getStatusItem(MainApp.gs(R.string.tdd_total), DecimalFormatter.to2Decimal(tdd.getBolusAndBasal())));
}
private void getBaseBasalRateItem(List<View> statusItems) {
if (LocalInsightPlugin.getInstance().getActiveBasalRate() == null) return;
ActiveBasalRate activeBasalRate = LocalInsightPlugin.getInstance().getActiveBasalRate();
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_basebasalrate_label),
DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")"));
}
private void getTBRItem(List<View> statusItems) {
if (LocalInsightPlugin.getInstance().getActiveTBR() == null) return;
ActiveTBR activeTBR = LocalInsightPlugin.getInstance().getActiveTBR();
statusItems.add(getStatusItem(MainApp.gs(R.string.pump_tempbasal_label),
MainApp.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration())));
}
private void getBolusItems(List<View> statusItems) {
if (LocalInsightPlugin.getInstance().getActiveBoluses() == null) return;
for (ActiveBolus activeBolus : LocalInsightPlugin.getInstance().getActiveBoluses()) {
String label;
switch (activeBolus.getBolusType()) {
case MULTIWAVE:
label = MainApp.gs(R.string.multiwave_bolus);
break;
case EXTENDED:
label = MainApp.gs(R.string.extended_bolus);
break;
default:
continue;
}
statusItems.add(getStatusItem(label, MainApp.gs(R.string.eb_formatter, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration())));
}
}
}

View file

@ -0,0 +1,257 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.activities;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DecimalFormat;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpInsightLocal.InsightAlertService;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.Alert;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.AlertStatus;
public class InsightAlertActivity extends AppCompatActivity {
private Alert alert;
private InsightAlertService alertService;
private ImageView icon;
private TextView errorCode;
private TextView errorTitle;
private TextView errorDescription;
private Button mute;
private Button confirm;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
alertService = ((InsightAlertService.LocalBinder) binder).getService();
alertService.setAlertActivity(InsightAlertActivity.this);
alert = alertService.getAlert();
if (alert == null) finish();
update(alert);
}
@Override
public void onServiceDisconnected(ComponentName name) {
alertService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insight_alert);
bindService(new Intent(this, InsightAlertService.class), serviceConnection, BIND_AUTO_CREATE);
icon = findViewById(R.id.icon);
errorCode = findViewById(R.id.error_code);
errorTitle = findViewById(R.id.error_title);
errorDescription = findViewById(R.id.error_description);
mute = findViewById(R.id.mute);
confirm = findViewById(R.id.confirm);
setFinishOnTouchOutside(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = 1.0F;
getWindow().setAttributes(layoutParams);
}
@Override
protected void onDestroy() {
alertService.setAlertActivity(null);
unbindService(serviceConnection);
super.onDestroy();
}
public void update(Alert alert) {
this.alert = alert;
mute.setEnabled(true);
mute.setVisibility(alert.getAlertStatus() == AlertStatus.SNOOZED ? View.GONE : View.VISIBLE);
confirm.setEnabled(true);
int icon = 0;
int code = 0;
int title = 0;
String description = null;
switch (alert.getAlertCategory()) {
case ERROR:
icon = R.drawable.ic_error;
break;
case MAINTENANCE:
icon = R.drawable.ic_maintenance;
break;
case WARNING:
icon = R.drawable.ic_warning;
break;
case REMINDER:
icon = R.drawable.ic_reminder;
break;
}
DecimalFormat decimalFormat = new DecimalFormat("##0.00");
int hours = alert.getTBRDuration() / 60;
int minutes = alert.getTBRDuration() - hours * 60;
switch (alert.getAlertType()) {
case REMINDER_01:
code = R.string.alert_r1_code;
title = R.string.alert_r1_title;
break;
case REMINDER_02:
code = R.string.alert_r2_code;
title = R.string.alert_r2_title;
break;
case REMINDER_03:
code = R.string.alert_r3_code;
title = R.string.alert_r3_title;
break;
case REMINDER_04:
code = R.string.alert_r4_code;
title = R.string.alert_r4_title;
break;
case REMINDER_07:
code = R.string.alert_r7_code;
title = R.string.alert_r7_title;
description = getString(R.string.alert_r7_description, alert.getTBRAmount(), new DecimalFormat("#0").format(hours) + ":" + new DecimalFormat("00").format(minutes));
break;
case WARNING_31:
code = R.string.alert_w31_code;
title = R.string.alert_w31_title;
description = getString(R.string.alert_w31_description, decimalFormat.format(alert.getCartridgeAmount()));
break;
case WARNING_32:
code = R.string.alert_w32_code;
title = R.string.alert_w32_title;
description = getString(R.string.alert_w32_description);
break;
case WARNING_33:
code = R.string.alert_w33_code;
title = R.string.alert_w33_title;
description = getString(R.string.alert_w33_description);
break;
case WARNING_34:
code = R.string.alert_w34_code;
title = R.string.alert_w34_title;
description = getString(R.string.alert_w34_description);
break;
case WARNING_36:
code = R.string.alert_w36_code;
title = R.string.alert_w36_title;
description = getString(R.string.alert_w36_description, alert.getTBRAmount(), new DecimalFormat("#0").format(hours) + ":" + new DecimalFormat("00").format(minutes));
break;
case WARNING_38:
code = R.string.alert_w38_code;
title = R.string.alert_w38_title;
description = getString(R.string.alert_w38_description, decimalFormat.format(alert.getProgrammedBolusAmount()), decimalFormat.format(alert.getDeliveredBolusAmount()));
break;
case WARNING_39:
code = R.string.alert_w39_code;
title = R.string.alert_w39_title;
break;
case MAINTENANCE_20:
code = R.string.alert_m20_code;
title = R.string.alert_m20_title;
description = getString(R.string.alert_m20_description);
break;
case MAINTENANCE_21:
code = R.string.alert_m21_code;
title = R.string.alert_m21_title;
description = getString(R.string.alert_m21_description);
break;
case MAINTENANCE_22:
code = R.string.alert_m22_code;
title = R.string.alert_m22_title;
description = getString(R.string.alert_m22_description);
break;
case MAINTENANCE_23:
code = R.string.alert_m23_code;
title = R.string.alert_m23_title;
description = getString(R.string.alert_m23_description);
break;
case MAINTENANCE_24:
code = R.string.alert_m24_code;
title = R.string.alert_m24_title;
description = getString(R.string.alert_m24_description);
break;
case MAINTENANCE_25:
code = R.string.alert_m25_code;
title = R.string.alert_m25_title;
description = getString(R.string.alert_m25_description);
break;
case MAINTENANCE_26:
code = R.string.alert_m26_code;
title = R.string.alert_m26_title;
description = getString(R.string.alert_m26_description);
break;
case MAINTENANCE_27:
code = R.string.alert_m27_code;
title = R.string.alert_m27_title;
description = getString(R.string.alert_m27_description);
break;
case MAINTENANCE_28:
code = R.string.alert_m28_code;
title = R.string.alert_m28_title;
description = getString(R.string.alert_m28_description);
break;
case MAINTENANCE_29:
code = R.string.alert_m29_code;
title = R.string.alert_m29_title;
description = getString(R.string.alert_m29_description);
break;
case MAINTENANCE_30:
code = R.string.alert_m30_code;
title = R.string.alert_m30_title;
description = getString(R.string.alert_m30_description);
break;
case ERROR_6:
code = R.string.alert_e6_code;
title = R.string.alert_e6_title;
description = getString(R.string.alert_e6_description);
break;
case ERROR_10:
code = R.string.alert_e10_code;
title = R.string.alert_e10_title;
description = getString(R.string.alert_e10_description);
break;
case ERROR_13:
code = R.string.alert_e13_code;
title = R.string.alert_e13_title;
description = getString(R.string.alert_e13_description);
break;
}
this.icon.setImageDrawable(ContextCompat.getDrawable(this, icon));
this.errorCode.setText(code);
this.errorTitle.setText(title);
if (description == null) this.errorDescription.setVisibility(View.GONE);
else {
this.errorDescription.setVisibility(View.VISIBLE);
this.errorDescription.setText(Html.fromHtml(description));
}
}
public void muteClicked(View view) {
mute.setEnabled(false);
alertService.mute();
}
public void confirmClicked(View view) {
mute.setEnabled(false);
confirm.setEnabled(false);
alertService.confirm();
}
}

View file

@ -0,0 +1,254 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.activities;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpInsightLocal.connection_service.InsightConnectionService;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.InsightState;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ExceptionTranslator;
public class InsightPairingActivity extends AppCompatActivity implements InsightConnectionService.StateCallback, View.OnClickListener, InsightConnectionService.ExceptionCallback {
private boolean scanning;
private LinearLayout deviceSearchSection;
private TextView pleaseWaitSection;
private LinearLayout codeCompareSection;
private LinearLayout pairingCompletedSection;
private Button yes;
private Button no;
private TextView code;
private Button exit;
private RecyclerView deviceList;
private DeviceAdapter deviceAdapter = new DeviceAdapter();
private InsightConnectionService service;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((InsightConnectionService.LocalBinder) binder).getService();
if (service.isPaired()) return;
else {
service.requestConnection(InsightPairingActivity.this);
service.registerStateCallback(InsightPairingActivity.this);
service.registerExceptionCallback(InsightPairingActivity.this);
onStateChanged(service.getState());
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insight_pairing);
deviceSearchSection = findViewById(R.id.device_search_section);
pleaseWaitSection = findViewById(R.id.please_wait_section);
codeCompareSection = findViewById(R.id.code_compare_section);
pairingCompletedSection = findViewById(R.id.pairing_completed_section);
yes = findViewById(R.id.yes);
no = findViewById(R.id.no);
code = findViewById(R.id.code);
exit = findViewById(R.id.exit);
deviceList = findViewById(R.id.device_list);
yes.setOnClickListener(this);
no.setOnClickListener(this);
exit.setOnClickListener(this);
deviceList.setLayoutManager(new LinearLayoutManager(this));
deviceList.setAdapter(deviceAdapter);
bindService(new Intent(this, InsightConnectionService.class), serviceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
if (service != null) {
service.withdrawConnectionRequest(InsightPairingActivity.this);
service.unregisterStateCallback(InsightPairingActivity.this);
service.unregisterExceptionCallback(InsightPairingActivity.this);
}
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onStart() {
super.onStart();
if (service != null && service.getState() == InsightState.NOT_PAIRED) startBLScan();
}
@Override
protected void onStop() {
stopBLScan();
super.onStop();
}
@Override
public void onStateChanged(InsightState state) {
runOnUiThread(() -> {
switch (state) {
case NOT_PAIRED:
startBLScan();
deviceSearchSection.setVisibility(View.VISIBLE);
pleaseWaitSection.setVisibility(View.GONE);
codeCompareSection.setVisibility(View.GONE);
pairingCompletedSection.setVisibility(View.GONE);
break;
case CONNECTING:
case SATL_CONNECTION_REQUEST:
case SATL_KEY_REQUEST:
case SATL_VERIFY_DISPLAY_REQUEST:
case SATL_VERIFY_CONFIRM_REQUEST:
case APP_BIND_MESSAGE:
stopBLScan();
deviceSearchSection.setVisibility(View.GONE);
pleaseWaitSection.setVisibility(View.VISIBLE);
codeCompareSection.setVisibility(View.GONE);
pairingCompletedSection.setVisibility(View.GONE);
break;
case AWAITING_CODE_CONFIRMATION:
stopBLScan();
deviceSearchSection.setVisibility(View.GONE);
pleaseWaitSection.setVisibility(View.GONE);
codeCompareSection.setVisibility(View.VISIBLE);
pairingCompletedSection.setVisibility(View.GONE);
code.setText(service.getVerificationString());
break;
case DISCONNECTED:
case CONNECTED:
stopBLScan();
deviceSearchSection.setVisibility(View.GONE);
pleaseWaitSection.setVisibility(View.GONE);
codeCompareSection.setVisibility(View.GONE);
pairingCompletedSection.setVisibility(View.VISIBLE);
break;
}
});
}
private void startBLScan() {
if (!scanning) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) bluetoothAdapter.enable();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
scanning = true;
}
}
private void stopBLScan() {
if (scanning) {
unregisterReceiver(broadcastReceiver);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
scanning = false;
}
}
@Override
public void onClick(View v) {
if (v == exit) finish();
else if (v == yes) service.confirmVerificationString();
else if (v == no) service.rejectVerificationString();
}
@Override
public void onExceptionOccur(Exception e) {
ExceptionTranslator.makeToast(this, e);
}
private void deviceSelected(BluetoothDevice device) {
service.pair(device.getAddress());
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
BluetoothAdapter.getDefaultAdapter().startDiscovery();
else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceAdapter.addDevice(bluetoothDevice);
}
}
};
private class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.ViewHolder> {
private List<BluetoothDevice> bluetoothDevices = new ArrayList<>();
public void addDevice(BluetoothDevice bluetoothDevice) {
if (!bluetoothDevices.contains(bluetoothDevice)) {
bluetoothDevices.add(bluetoothDevice);
notifyDataSetChanged();
}
}
public void clear() {
bluetoothDevices.clear();
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.bluetooth_device, parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
BluetoothDevice bluetoothDevice = bluetoothDevices.get(position);
holder.deviceName.setText(bluetoothDevice.getName() == null ? bluetoothDevice.getAddress() : bluetoothDevice.getName());
holder.deviceName.setOnClickListener((v) -> deviceSelected(bluetoothDevice));
}
@Override
public int getItemCount() {
return bluetoothDevices.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView deviceName;
public ViewHolder(View itemView) {
super(itemView);
deviceName = (TextView) itemView;
}
}
}
}

View file

@ -0,0 +1,88 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.activities;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpInsightLocal.connection_service.InsightConnectionService;
public class InsightPairingInformationActivity extends AppCompatActivity {
private InsightConnectionService connectionService;
private TextView serialNumber;
private TextView releaseSWVersion;
private TextView uiProcSWVersion;
private TextView pcProcSWVersion;
private TextView mdTelSWVersion;
private TextView safetyProcSWVersion;
private TextView btInfoPageVersion;
private TextView bluetoothAddress;
private TextView systemIdAppendix;
private TextView manufacturingDate;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
connectionService = ((InsightConnectionService.LocalBinder) binder).getService();
if (!connectionService.isPaired()) {
overridePendingTransition(0, 0);
finish();
startActivity(new Intent(InsightPairingInformationActivity.this, InsightPairingActivity.class));
} else {
serialNumber.setText(connectionService.getPumpSystemIdentification().getSerialNumber());
manufacturingDate.setText(connectionService.getPumpSystemIdentification().getManufacturingDate());
systemIdAppendix.setText(connectionService.getPumpSystemIdentification().getSystemIdAppendix() + "");
releaseSWVersion.setText(connectionService.getPumpFirmwareVersions().getReleaseSWVersion());
uiProcSWVersion.setText(connectionService.getPumpFirmwareVersions().getUiProcSWVersion());
pcProcSWVersion.setText(connectionService.getPumpFirmwareVersions().getPcProcSWVersion());
mdTelSWVersion.setText(connectionService.getPumpFirmwareVersions().getMdTelProcSWVersion());
safetyProcSWVersion.setText(connectionService.getPumpFirmwareVersions().getSafetyProcSWVersion());
btInfoPageVersion.setText(connectionService.getPumpFirmwareVersions().getBtInfoPageVersion());
bluetoothAddress.setText(connectionService.getBluetoothAddress());
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
connectionService = null;
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insight_pairing_information);
serialNumber = findViewById(R.id.serial_number);
releaseSWVersion = findViewById(R.id.release_sw_version);
uiProcSWVersion = findViewById(R.id.ui_proc_sw_version);
pcProcSWVersion = findViewById(R.id.pc_proc_sw_version);
mdTelSWVersion = findViewById(R.id.md_tel_sw_version);
safetyProcSWVersion = findViewById(R.id.safety_proc_sw_version);
btInfoPageVersion = findViewById(R.id.bt_info_page_version);
bluetoothAddress = findViewById(R.id.bluetooth_address);
systemIdAppendix = findViewById(R.id.system_id_appendix);
manufacturingDate = findViewById(R.id.manufacturing_date);
bindService(new Intent(this, InsightConnectionService.class), serviceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
unbindService(serviceConnection);
super.onDestroy();
}
public void deletePairing(View view) {
if (connectionService != null) {
connectionService.reset();
finish();
}
}
}

View file

@ -0,0 +1,91 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.IncompatibleAppVersionException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.InvalidAppCRCException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.UnknownAppCommandException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.UnknownServiceException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.app_layer_errors.AppLayerErrorException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.exceptions.app_layer_errors.UnknownAppLayerErrorCodeException;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.AppCommandIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.AppErrorIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.ServiceIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.satl.DataMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.crypto.Cryptograph;
public class AppLayerMessage implements Comparable<AppLayerMessage> {
private static final byte VERSION = 0x20;
private final MessagePriority messagePriority;
private final boolean inCRC;
private final boolean outCRC;
private final Service service;
public AppLayerMessage(MessagePriority messagePriority, boolean inCRC, boolean outCRC, Service service) {
this.messagePriority = messagePriority;
this.inCRC = inCRC;
this.outCRC = outCRC;
this.service = service;
}
protected ByteBuf getData() {
return new ByteBuf(0);
}
protected void parse(ByteBuf byteBuf) throws Exception {
}
public ByteBuf serialize(Class<? extends AppLayerMessage> clazz) {
byte[] data = getData().getBytes();
ByteBuf byteBuf = new ByteBuf(4 + data.length + (outCRC ? 2 : 0));
byteBuf.putByte(VERSION);
byteBuf.putByte(ServiceIDs.IDS.getID(getService()));
byteBuf.putUInt16LE(AppCommandIDs.IDS.getID(clazz));
byteBuf.putBytes(data);
if (outCRC) byteBuf.putUInt16LE(Cryptograph.calculateCRC(data));
return byteBuf;
}
public static AppLayerMessage deserialize(ByteBuf byteBuf) throws Exception {
byte version = byteBuf.readByte();
byte service = byteBuf.readByte();
int command = byteBuf.readUInt16LE();
int error = byteBuf.readUInt16LE();
Class<? extends AppLayerMessage> clazz = AppCommandIDs.IDS.getType(command);
if (clazz == null) throw new UnknownAppCommandException();
if (version != VERSION) throw new IncompatibleAppVersionException();
AppLayerMessage message = clazz.newInstance();
if (ServiceIDs.IDS.getType(service) == null) throw new UnknownServiceException();
if (error != 0) {
Class<? extends AppLayerErrorException> exceptionClass = AppErrorIDs.IDS.getType(error);
if (exceptionClass == null) throw new UnknownAppLayerErrorCodeException(error);
else throw exceptionClass.getConstructor(int.class).newInstance(error);
}
byte[] data = byteBuf.readBytes(byteBuf.getSize() - (message.inCRC ? 2 : 0));
if (message.inCRC && Cryptograph.calculateCRC(data) != byteBuf.readUInt16LE()) throw new InvalidAppCRCException();
message.parse(ByteBuf.from(data));
return message;
}
public static DataMessage wrap(AppLayerMessage message) {
DataMessage dataMessage = new DataMessage();
dataMessage.setData(message.serialize(message.getClass()));
return dataMessage;
}
public static AppLayerMessage unwrap(DataMessage dataMessage) throws Exception {
return deserialize(dataMessage.getData());
}
@Override
public int compareTo(AppLayerMessage o) {
return messagePriority.compareTo(o.messagePriority);
}
public Service getService() {
return this.service;
}
}

View file

@ -0,0 +1,48 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks.ParameterBlock;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.ParameterBlockIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ReadParameterBlockMessage extends AppLayerMessage {
private Class<? extends ParameterBlock> parameterBlockId;
private ParameterBlock parameterBlock;
private Service service;
public ReadParameterBlockMessage() {
super(MessagePriority.NORMAL, true, false, null);
}
@Override
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16LE(ParameterBlockIDs.IDS.getID(parameterBlockId));
return byteBuf;
}
@Override
protected void parse(ByteBuf byteBuf) throws Exception {
parameterBlock = ParameterBlockIDs.IDS.getType(byteBuf.readUInt16LE()).newInstance();
byteBuf.shift(2); //Restriction level
parameterBlock.parse(byteBuf);
}
public ParameterBlock getParameterBlock() {
return this.parameterBlock;
}
public void setParameterBlockId(Class<? extends ParameterBlock> configurationBlockId) {
this.parameterBlockId = configurationBlockId;
}
}

View file

@ -0,0 +1,31 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer;
public enum Service {
CONNECTION((short) 0x0000, null),
STATUS((short) 0x0100, null),
HISTORY((short) 0x0200, null),
CONFIGURATION((short) 0x0200, "u+5Fhz6Gw4j1Kkas"),
PARAMETER((short) 0x0200, null),
REMOTE_CONTROL((short) 0x0100, "MAbcV2X6PVjxuz+R");
private short version;
private String servicePassword;
Service(short version, String servicePassword) {
this.version = version;
this.servicePassword = servicePassword;
}
public short getVersion() {
return this.version;
}
public String getServicePassword() {
return this.servicePassword;
}
public void setServicePassword(String servicePassword) {
this.servicePassword = servicePassword;
}
}

View file

@ -0,0 +1,12 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.configuration;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
public class CloseConfigurationWriteSessionMessage extends AppLayerMessage {
public CloseConfigurationWriteSessionMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONFIGURATION);
}
}

View file

@ -0,0 +1,12 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.configuration;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
public class OpenConfigurationWriteSessionMessage extends AppLayerMessage {
public OpenConfigurationWriteSessionMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONFIGURATION);
}
}

View file

@ -0,0 +1,41 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.configuration;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks.ParameterBlock;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.ParameterBlockIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class WriteConfigurationBlockMessage extends AppLayerMessage {
private ParameterBlock parameterBlock;
private Class<? extends ParameterBlock> configurationBlockId;
public WriteConfigurationBlockMessage() {
super(MessagePriority.NORMAL, false, true, Service.CONFIGURATION);
}
@Override
protected ByteBuf getData() {
ByteBuf configBlockData = parameterBlock.getData();
ByteBuf data = new ByteBuf(4 + configBlockData.getSize());
data.putUInt16LE(ParameterBlockIDs.IDS.getID(parameterBlock.getClass()));
data.putUInt16LE(31);
data.putByteBuf(configBlockData);
return data;
}
@Override
protected void parse(ByteBuf byteBuf) throws Exception {
configurationBlockId = ParameterBlockIDs.IDS.getType(byteBuf.readUInt16LE());
}
public Class<? extends ParameterBlock> getConfigurationBlockId() {
return this.configurationBlockId;
}
public void setParameterBlock(ParameterBlock parameterBlock) {
this.parameterBlock = parameterBlock;
}
}

View file

@ -0,0 +1,51 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.connection;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ActivateServiceMessage extends AppLayerMessage {
private byte serviceID;
private short version;
private byte[] servicePassword;
public ActivateServiceMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONNECTION);
}
protected void parse(ByteBuf byteBuf) {
serviceID = byteBuf.readByte();
version = byteBuf.readShort();
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(19);
byteBuf.putByte(serviceID);
byteBuf.putShort(version);
byteBuf.putBytes(servicePassword);
return byteBuf;
}
public byte getServiceID() {
return this.serviceID;
}
public short getVersion() {
return this.version;
}
public void setServiceID(byte serviceID) {
this.serviceID = serviceID;
}
public void setVersion(short version) {
this.version = version;
}
public void setServicePassword(byte[] servicePassword) {
this.servicePassword = servicePassword;
}
}

View file

@ -0,0 +1,20 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.connection;
import org.spongycastle.util.encoders.Hex;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class BindMessage extends AppLayerMessage {
public BindMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONNECTION);
}
@Override
protected ByteBuf getData() {
return ByteBuf.from(Hex.decode("3438310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"));
}
}

View file

@ -0,0 +1,20 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.connection;
import org.spongycastle.util.encoders.Hex;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ConnectMessage extends AppLayerMessage {
public ConnectMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONNECTION);
}
@Override
protected ByteBuf getData() {
return ByteBuf.from(Hex.decode("0000080100196000"));
}
}

View file

@ -0,0 +1,20 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.connection;
import org.spongycastle.util.encoders.Hex;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class DisconnectMessage extends AppLayerMessage {
public DisconnectMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONNECTION);
}
@Override
protected ByteBuf getData() {
return ByteBuf.from(Hex.decode("0360"));
}
}

View file

@ -0,0 +1,42 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.connection;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ServiceChallengeMessage extends AppLayerMessage {
private byte serviceID;
private byte[] randomData;
private short version;
public ServiceChallengeMessage() {
super(MessagePriority.NORMAL, false, false, Service.CONNECTION);
}
@Override
protected void parse(ByteBuf byteBuf) {
randomData = byteBuf.getBytes(16);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(3);
byteBuf.putByte(serviceID);
byteBuf.putShort(version);
return byteBuf;
}
public byte[] getRandomData() {
return this.randomData;
}
public void setServiceID(byte serviceID) {
this.serviceID = serviceID;
}
public void setVersion(short version) {
this.version = version;
}
}

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history;
public enum HistoryReadingDirection {
FORWARD,
BACKWARD;
}

View file

@ -0,0 +1,34 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events.HistoryEvent;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ReadHistoryEventsMessage extends AppLayerMessage {
private List<HistoryEvent> historyEvents;
public ReadHistoryEventsMessage() {
super(MessagePriority.NORMAL, true, false, Service.HISTORY);
}
@Override
protected void parse(ByteBuf byteBuf) throws Exception {
historyEvents = new ArrayList<>();
byteBuf.shift(2);
int frameCount = byteBuf.readUInt16LE();
for (int i = 0; i < frameCount; i++) {
int length = byteBuf.readUInt16LE();
historyEvents.add(HistoryEvent.deserialize(ByteBuf.from(byteBuf.readBytes(length))));
}
}
public List<HistoryEvent> getHistoryEvents() {
return historyEvents;
}
}

View file

@ -0,0 +1,34 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.HistoryReadingDirectionIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class StartReadingHistoryMessage extends AppLayerMessage {
private long offset;
private HistoryReadingDirection direction;
public StartReadingHistoryMessage() {
super(MessagePriority.NORMAL, false, true, Service.HISTORY);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(8);
byteBuf.putUInt16LE(31);
byteBuf.putUInt16LE(HistoryReadingDirectionIDs.IDS.getID(direction));
byteBuf.putUInt32LE(offset);
return byteBuf;
}
public void setOffset(long offset) {
this.offset = offset;
}
public void setDirection(HistoryReadingDirection direction) {
this.direction = direction;
}
}

View file

@ -0,0 +1,13 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class StopReadingHistoryMessage extends AppLayerMessage {
public StopReadingHistoryMessage() {
super(MessagePriority.NORMAL, false, false, Service.HISTORY);
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class BasalDeliveryChangedEvent extends HistoryEvent {
private double oldBasalRate;
private double newBasalRate;
@Override
public void parse(ByteBuf byteBuf) {
oldBasalRate = byteBuf.readUInt32Decimal1000();
newBasalRate = byteBuf.readUInt32Decimal1000();
}
public double getOldBasalRate() {
return oldBasalRate;
}
public double getNewBasalRate() {
return newBasalRate;
}
}

View file

@ -0,0 +1,64 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.BolusType;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.BolusTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.BOCUtil;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class BolusDeliveredEvent extends HistoryEvent {
private BolusType bolusType;
private int startHour;
private int startMinute;
private int startSecond;
private double immediateAmount;
private double extendedAmount;
private int duration;
private int bolusID;
@Override
public void parse(ByteBuf byteBuf) {
bolusType = BolusTypeIDs.IDS.getType(byteBuf.readUInt16LE());
byteBuf.shift(1);
startHour = BOCUtil.parseBOC(byteBuf.readByte());
startMinute = BOCUtil.parseBOC(byteBuf.readByte());
startSecond = BOCUtil.parseBOC(byteBuf.readByte());
immediateAmount = byteBuf.readUInt16Decimal();
extendedAmount = byteBuf.readUInt16Decimal();
duration = byteBuf.readUInt16LE();
byteBuf.shift(2);
bolusID = byteBuf.readUInt16LE();
}
public BolusType getBolusType() {
return bolusType;
}
public int getStartHour() {
return startHour;
}
public int getStartMinute() {
return startMinute;
}
public int getStartSecond() {
return startSecond;
}
public double getImmediateAmount() {
return immediateAmount;
}
public double getExtendedAmount() {
return extendedAmount;
}
public int getDuration() {
return duration;
}
public int getBolusID() {
return bolusID;
}
}

View file

@ -0,0 +1,45 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.BolusType;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.BolusTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class BolusProgrammedEvent extends HistoryEvent {
private BolusType bolusType;
private double immediateAmount;
private double extendedAmount;
private int duration;
private int bolusID;
@Override
public void parse(ByteBuf byteBuf) {
bolusType = BolusTypeIDs.IDS.getType(byteBuf.readUInt16LE());
immediateAmount = byteBuf.readUInt16Decimal();
extendedAmount = byteBuf.readUInt16Decimal();
duration = byteBuf.readUInt16LE();
byteBuf.shift(4);
bolusID = byteBuf.readUInt16LE();
}
public BolusType getBolusType() {
return bolusType;
}
public double getImmediateAmount() {
return immediateAmount;
}
public double getExtendedAmount() {
return extendedAmount;
}
public int getDuration() {
return duration;
}
public int getBolusID() {
return bolusID;
}
}

View file

@ -0,0 +1,17 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class CannulaFilledEvent extends HistoryEvent {
private double amount;
@Override
public void parse(ByteBuf byteBuf) {
amount = byteBuf.readUInt16Decimal();
}
public double getAmount() {
return amount;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class CartridgeInsertedEvent extends HistoryEvent {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class CartridgeRemovedEvent extends HistoryEvent {
}

View file

@ -0,0 +1,49 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.BOCUtil;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class DateTimeChangedEvent extends HistoryEvent {
private int beforeYear;
private int beforeMonth;
private int beforeDay;
private int beforeHour;
private int beforeMinute;
private int beforeSecond;
@Override
public void parse(ByteBuf byteBuf) {
beforeYear = BOCUtil.parseBOC(byteBuf.readByte()) * 100 + BOCUtil.parseBOC(byteBuf.readByte());
beforeMonth = BOCUtil.parseBOC(byteBuf.readByte());
beforeDay = BOCUtil.parseBOC(byteBuf.readByte());
byteBuf.shift(1);
beforeHour = BOCUtil.parseBOC(byteBuf.readByte());
beforeMinute = BOCUtil.parseBOC(byteBuf.readByte());
beforeSecond = BOCUtil.parseBOC(byteBuf.readByte());
}
public int getBeforeYear() {
return beforeYear;
}
public int getBeforeMonth() {
return beforeMonth;
}
public int getBeforeDay() {
return beforeDay;
}
public int getBeforeHour() {
return beforeHour;
}
public int getBeforeMinute() {
return beforeMinute;
}
public int getBeforeSecond() {
return beforeSecond;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class DefaultDateTimeSetEvent extends HistoryEvent {
}

View file

@ -0,0 +1,43 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.BOCUtil;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class EndOfTBREvent extends HistoryEvent {
private int startHour;
private int startMinute;
private int startSecond;
private int amount;
private int duration;
@Override
public void parse(ByteBuf byteBuf) {
byteBuf.shift(1);
startHour = BOCUtil.parseBOC(byteBuf.readByte());
startMinute = BOCUtil.parseBOC(byteBuf.readByte());
startSecond = BOCUtil.parseBOC(byteBuf.readByte());
amount = byteBuf.readUInt16LE();
duration = byteBuf.readUInt16LE();
}
public int getStartHour() {
return startHour;
}
public int getStartMinute() {
return startMinute;
}
public int getStartSecond() {
return startSecond;
}
public int getAmount() {
return amount;
}
public int getDuration() {
return duration;
}
}

View file

@ -0,0 +1,83 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.HistoryEventIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.BOCUtil;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class HistoryEvent implements Comparable<HistoryEvent> {
private int eventYear;
private int eventMonth;
private int eventDay;
private int eventHour;
private int eventMinute;
private int eventSecond;
private long eventPosition;
public static HistoryEvent deserialize(ByteBuf byteBuf) {
int eventID = byteBuf.readUInt16LE();
Class<? extends HistoryEvent> eventClass = HistoryEventIDs.IDS.getType(eventID);
HistoryEvent event = null;
if (eventClass == null) event = new HistoryEvent();
else {
try {
event = eventClass.newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
event.parseHeader(byteBuf);
event.parse(byteBuf);
return event;
}
public final void parseHeader(ByteBuf byteBuf) {
eventYear = BOCUtil.parseBOC(byteBuf.readByte()) * 100 + BOCUtil.parseBOC(byteBuf.readByte());
eventMonth = BOCUtil.parseBOC(byteBuf.readByte());
eventDay = BOCUtil.parseBOC(byteBuf.readByte());
byteBuf.shift(1);
eventHour = BOCUtil.parseBOC(byteBuf.readByte());
eventMinute = BOCUtil.parseBOC(byteBuf.readByte());
eventSecond = BOCUtil.parseBOC(byteBuf.readByte());
eventPosition = byteBuf.readUInt32LE();
}
public void parse(ByteBuf byteBuf) {
}
public int getEventYear() {
return eventYear;
}
public int getEventMonth() {
return eventMonth;
}
public int getEventDay() {
return eventDay;
}
public int getEventHour() {
return eventHour;
}
public int getEventMinute() {
return eventMinute;
}
public int getEventSecond() {
return eventSecond;
}
public long getEventPosition() {
return eventPosition;
}
@Override
public int compareTo(HistoryEvent historyEvent) {
return (int) (eventPosition - historyEvent.eventPosition);
}
}

View file

@ -0,0 +1,25 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.AlertType;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.AlertTypeIncrementalIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public abstract class OccurrenceOfAlertEvent extends HistoryEvent {
private AlertType alertType;
private int alertID;
@Override
public void parse(ByteBuf byteBuf) {
alertType = AlertTypeIncrementalIDs.IDS.getType(byteBuf.readUInt16LE());
alertID = byteBuf.readUInt16LE();
}
public AlertType getAlertType() {
return alertType;
}
public int getAlertID() {
return alertID;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class OccurrenceOfErrorEvent extends OccurrenceOfAlertEvent {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class OccurrenceOfMaintenanceEvent extends OccurrenceOfAlertEvent {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class OccurrenceOfWarningEvent extends OccurrenceOfAlertEvent {
}

View file

@ -0,0 +1,26 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.OperatingMode;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.OperatingModeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class OperatingModeChangedEvent extends HistoryEvent {
private OperatingMode oldValue;
private OperatingMode newValue;
@Override
public void parse(ByteBuf byteBuf) {
oldValue = OperatingModeIDs.IDS.getType(byteBuf.readUInt16LE());
newValue = OperatingModeIDs.IDS.getType(byteBuf.readUInt16LE());
}
public OperatingMode getOldValue() {
return oldValue;
}
public OperatingMode getNewValue() {
return newValue;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class PowerDownEvent extends HistoryEvent {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
public class PowerUpEvent extends HistoryEvent {
}

View file

@ -0,0 +1,18 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class SniffingDoneEvent extends HistoryEvent {
private double amount;
@Override
public void parse(ByteBuf byteBuf) {
amount = byteBuf.readUInt16Decimal();
}
public double getAmount() {
return amount;
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class StartOfTBREvent extends HistoryEvent {
private int amount;
private int duration;
@Override
public void parse(ByteBuf byteBuf) {
amount = byteBuf.readUInt16LE();
duration = byteBuf.readUInt16LE();
}
public int getAmount() {
return amount;
}
public int getDuration() {
return duration;
}
}

View file

@ -0,0 +1,42 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.BOCUtil;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class TotalDailyDoseEvent extends HistoryEvent {
private double basalTotal;
private double bolusTotal;
private int totalYear;
private int totalMonth;
private int totalDay;
@Override
public void parse(ByteBuf byteBuf) {
basalTotal = byteBuf.readUInt32Decimal100();
bolusTotal = byteBuf.readUInt32Decimal100();
totalYear = BOCUtil.parseBOC(byteBuf.readByte()) * 100 + BOCUtil.parseBOC(byteBuf.readByte());
totalMonth = BOCUtil.parseBOC(byteBuf.readByte());
totalDay = BOCUtil.parseBOC(byteBuf.readByte());
}
public double getBasalTotal() {
return basalTotal;
}
public double getBolusTotal() {
return bolusTotal;
}
public int getTotalYear() {
return totalYear;
}
public int getTotalMonth() {
return totalMonth;
}
public int getTotalDay() {
return totalDay;
}
}

View file

@ -0,0 +1,17 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.history.history_events;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class TubeFilledEvent extends HistoryEvent {
private double amount;
@Override
public void parse(ByteBuf byteBuf) {
amount = byteBuf.readUInt16Decimal();
}
public double getAmount() {
return amount;
}
}

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.BasalProfile;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.ActiveBasalProfileIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ActiveBRProfileBlock extends ParameterBlock {
private BasalProfile activeBasalProfile;
@Override
public void parse(ByteBuf byteBuf) {
activeBasalProfile = ActiveBasalProfileIDs.IDS.getType(byteBuf.readUInt16LE());
}
@Override
public ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16LE(ActiveBasalProfileIDs.IDS.getID(activeBasalProfile));
return byteBuf;
}
public BasalProfile getActiveBasalProfile() {
return activeBasalProfile;
}
public void setActiveBasalProfile(BasalProfile activeBasalProfile) {
this.activeBasalProfile = activeBasalProfile;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile1Block extends BRProfileBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile1NameBlock extends NameBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile2Block extends BRProfileBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile2NameBlock extends NameBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile3Block extends BRProfileBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile3NameBlock extends NameBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile4Block extends BRProfileBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile4NameBlock extends NameBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile5Block extends BRProfileBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class BRProfile5NameBlock extends NameBlock {
}

View file

@ -0,0 +1,50 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.BasalProfileBlock;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public abstract class BRProfileBlock extends ParameterBlock {
private List<BasalProfileBlock> profileBlocks;
@Override
public void parse(ByteBuf byteBuf) {
profileBlocks = new ArrayList<>();
for (int i = 0; i < 24; i++) {
BasalProfileBlock basalProfileBlock = new BasalProfileBlock();
basalProfileBlock.setDuration(byteBuf.readUInt16LE());
profileBlocks.add(basalProfileBlock);
}
for (int i = 0; i < 24; i++) profileBlocks.get(i).setBasalAmount(byteBuf.readUInt16Decimal());
Iterator<BasalProfileBlock> iterator = profileBlocks.iterator();
while (iterator.hasNext())
if (iterator.next().getDuration() == 0)
iterator.remove();
}
@Override
public ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(96);
for (int i = 0; i < 24; i++) {
if (profileBlocks.size() > i) byteBuf.putUInt16LE(profileBlocks.get(i).getDuration());
else byteBuf.putUInt16LE(0);
}
for (int i = 0; i < 24; i++) {
if (profileBlocks.size() > i) byteBuf.putUInt16Decimal(profileBlocks.get(i).getBasalAmount());
else byteBuf.putUInt16Decimal(0);
}
return byteBuf;
}
public List<BasalProfileBlock> getProfileBlocks() {
return profileBlocks;
}
public void setProfileBlocks(List<BasalProfileBlock> profileBlocks) {
this.profileBlocks = profileBlocks;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class FactoryMaxBasalAmountBlock extends InsulinAmountLimitationBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class FactoryMaxBolusAmountBlock extends InsulinAmountLimitationBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class FactoryMinBasalAmountBlock extends InsulinAmountLimitationBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class FactoryMinBolusAmountBlock extends InsulinAmountLimitationBlock {
}

View file

@ -0,0 +1,28 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public abstract class InsulinAmountLimitationBlock extends ParameterBlock {
private double amountLimitation;
@Override
public void parse(ByteBuf byteBuf) {
amountLimitation = byteBuf.readUInt16Decimal();
}
@Override
public ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16Decimal(amountLimitation);
return byteBuf;
}
public double getAmountLimitation() {
return this.amountLimitation;
}
public void setAmountLimitation(double amountLimitation) {
this.amountLimitation = amountLimitation;
}
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class MaxBasalAmountBlock extends InsulinAmountLimitationBlock {
}

View file

@ -0,0 +1,4 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
public class MaxBolusAmountBlock extends InsulinAmountLimitationBlock {
}

View file

@ -0,0 +1,28 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public abstract class NameBlock extends ParameterBlock {
private String name;
@Override
public void parse(ByteBuf byteBuf) {
name = byteBuf.readUTF16(40);
}
@Override
public ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(42);
byteBuf.putUTF16(name, 40);
return byteBuf;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View file

@ -0,0 +1,10 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public abstract class ParameterBlock {
public abstract void parse(ByteBuf byteBuf);
public abstract ByteBuf getData();
}

View file

@ -0,0 +1,26 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.SystemIdentification;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class SystemIdentificationBlock extends ParameterBlock {
private SystemIdentification systemIdentification;
@Override
public void parse(ByteBuf byteBuf) {
systemIdentification = new SystemIdentification();
systemIdentification.setSerialNumber(byteBuf.readUTF16(18));
systemIdentification.setSystemIdAppendix(byteBuf.readUInt32LE());
systemIdentification.setManufacturingDate(byteBuf.readUTF16(22));
}
@Override
public ByteBuf getData() {
return null;
}
public SystemIdentification getSystemIdentification() {
return systemIdentification;
}
}

View file

@ -0,0 +1,31 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.parameter_blocks;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class TBROverNotificationBlock extends ParameterBlock {
private boolean enabled;
private int melody;
@Override
public void parse(ByteBuf byteBuf) {
enabled = byteBuf.readBoolean();
melody = byteBuf.readUInt16LE();
}
@Override
public ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(4);
byteBuf.putBoolean(enabled);
byteBuf.putUInt16LE(melody);
return byteBuf;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}

View file

@ -0,0 +1,26 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class CancelBolusMessage extends AppLayerMessage {
private int bolusID;
public CancelBolusMessage() {
super(MessagePriority.HIGHEST, false, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16LE(bolusID);
return byteBuf;
}
public void setBolusID(int bolusID) {
this.bolusID = bolusID;
}
}

View file

@ -0,0 +1,12 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class CancelTBRMessage extends AppLayerMessage {
public CancelTBRMessage() {
super(MessagePriority.HIGHER, false, false, Service.REMOTE_CONTROL);
}
}

View file

@ -0,0 +1,33 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ChangeTBRMessage extends AppLayerMessage {
private int percentage;
private int duration;
public ChangeTBRMessage() {
super(MessagePriority.NORMAL, false, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(6);
byteBuf.putUInt16LE(percentage);
byteBuf.putUInt16LE(duration);
byteBuf.putUInt16LE(31);
return byteBuf;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setDuration(int duration) {
this.duration = duration;
}
}

View file

@ -0,0 +1,26 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class ConfirmAlertMessage extends AppLayerMessage {
private int alertID;
public ConfirmAlertMessage() {
super(MessagePriority.NORMAL, false, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16LE(alertID);
return byteBuf;
}
public void setAlertID(int alertID) {
this.alertID = alertID;
}
}

View file

@ -0,0 +1,63 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.BolusType;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.BolusTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class DeliverBolusMessage extends AppLayerMessage {
private BolusType bolusType;
private double immediateAmount;
private double extendedAmount;
private int duration;
private int bolusId;
public DeliverBolusMessage() {
super(MessagePriority.NORMAL, true, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(22);
byteBuf.putUInt16LE(805);
byteBuf.putUInt16LE(BolusTypeIDs.IDS.getID(bolusType));
byteBuf.putUInt16LE(31);
byteBuf.putUInt16LE(0);
byteBuf.putUInt16Decimal(immediateAmount);
byteBuf.putUInt16Decimal(extendedAmount);
byteBuf.putUInt16LE(duration);
byteBuf.putUInt16LE(0);
byteBuf.putUInt16Decimal(immediateAmount);
byteBuf.putUInt16Decimal(extendedAmount);
byteBuf.putUInt16LE(duration);
return byteBuf;
}
@Override
protected void parse(ByteBuf byteBuf) throws Exception {
bolusId = byteBuf.readUInt16LE();
}
public void setBolusType(BolusType bolusType) {
this.bolusType = bolusType;
}
public void setImmediateAmount(double immediateAmount) {
this.immediateAmount = immediateAmount;
}
public void setExtendedAmount(double extendedAmount) {
this.extendedAmount = extendedAmount;
}
public void setDuration(int duration) {
this.duration = duration;
}
public int getBolusId() {
return bolusId;
}
}

View file

@ -0,0 +1,28 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.AvailableBolusTypes;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetAvailableBolusTypesMessage extends AppLayerMessage {
private AvailableBolusTypes availableBolusTypes;
public GetAvailableBolusTypesMessage() {
super(MessagePriority.NORMAL, false, false, Service.REMOTE_CONTROL);
}
@Override
protected void parse(ByteBuf byteBuf) throws Exception {
availableBolusTypes = new AvailableBolusTypes();
availableBolusTypes.setStandardAvailable(byteBuf.readBoolean());
availableBolusTypes.setExtendedAvailable(byteBuf.readBoolean());
availableBolusTypes.setMultiwaveAvailable(byteBuf.readBoolean());
}
public AvailableBolusTypes getAvailableBolusTypes() {
return this.availableBolusTypes;
}
}

View file

@ -0,0 +1,32 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.PumpTime;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class SetDateTimeMessage extends AppLayerMessage {
private PumpTime pumpTime;
public SetDateTimeMessage() {
super(MessagePriority.NORMAL, false, true, Service.CONFIGURATION);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(7);
byteBuf.putUInt16LE(pumpTime.getYear());
byteBuf.putUInt8((short) pumpTime.getMonth());
byteBuf.putUInt8((short) pumpTime.getDay());
byteBuf.putUInt8((short) pumpTime.getHour());
byteBuf.putUInt8((short) pumpTime.getMinute());
byteBuf.putUInt8((short) pumpTime.getSecond());
return byteBuf;
}
public void setPumpTime(PumpTime pumpTime) {
this.pumpTime = pumpTime;
}
}

View file

@ -0,0 +1,28 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.OperatingMode;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.OperatingModeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class SetOperatingModeMessage extends AppLayerMessage {
private OperatingMode operatingMode;
public SetOperatingModeMessage() {
super(MessagePriority.HIGHEST, false, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16LE(OperatingModeIDs.IDS.getID(operatingMode));
return byteBuf;
}
public void setOperatingMode(OperatingMode operatingMode) {
this.operatingMode = operatingMode;
}
}

View file

@ -0,0 +1,33 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class SetTBRMessage extends AppLayerMessage {
private int percentage;
private int duration;
public SetTBRMessage() {
super(MessagePriority.NORMAL, false, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(6);
byteBuf.putUInt16LE(percentage);
byteBuf.putUInt16LE(duration);
byteBuf.putUInt16LE(31);
return byteBuf;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setDuration(int duration) {
this.duration = duration;
}
}

View file

@ -0,0 +1,26 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.remote_control;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class SnoozeAlertMessage extends AppLayerMessage {
private int alertID;
public SnoozeAlertMessage() {
super(MessagePriority.NORMAL, false, true, Service.REMOTE_CONTROL);
}
@Override
protected ByteBuf getData() {
ByteBuf byteBuf = new ByteBuf(2);
byteBuf.putUInt16LE(alertID);
return byteBuf;
}
public void setAlertID(int alertID) {
this.alertID = alertID;
}
}

View file

@ -0,0 +1,54 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.Alert;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.AlertCategoryIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.AlertStatusIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.AlertTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetActiveAlertMessage extends AppLayerMessage {
private Alert alert;
public GetActiveAlertMessage() {
super(MessagePriority.NORMAL, true, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
Alert alert = new Alert();
alert.setAlertId(byteBuf.readUInt16LE());
alert.setAlertCategory(AlertCategoryIDs.IDS.getType(byteBuf.readUInt16LE()));
alert.setAlertType(AlertTypeIDs.IDS.getType(byteBuf.readUInt16LE()));
alert.setAlertStatus(AlertStatusIDs.IDS.getType(byteBuf.readUInt16LE()));
if (alert.getAlertType() != null) {
switch (alert.getAlertType()) {
case WARNING_38:
byteBuf.shift(4);
alert.setProgrammedBolusAmount(byteBuf.readUInt16Decimal());
alert.setDeliveredBolusAmount(byteBuf.readUInt16Decimal());
break;
case REMINDER_07:
case WARNING_36:
byteBuf.shift(2);
alert.setTBRAmount(byteBuf.readUInt16LE());
alert.setTBRDuration(byteBuf.readUInt16LE());
break;
case WARNING_31:
alert.setCartridgeAmount(byteBuf.readUInt16Decimal());
break;
}
}
if (alert.getAlertCategory() != null
&& alert.getAlertType() != null
&& alert.getAlertStatus() != null)
this.alert = alert;
}
public Alert getAlert() {
return this.alert;
}
}

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.ActiveBasalRate;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.ActiveBasalProfileIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetActiveBasalRateMessage extends AppLayerMessage {
private ActiveBasalRate activeBasalRate;
public GetActiveBasalRateMessage() {
super(MessagePriority.NORMAL, true, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
ActiveBasalRate activeBasalRate = new ActiveBasalRate();
activeBasalRate.setActiveBasalProfile(ActiveBasalProfileIDs.IDS.getType(byteBuf.readUInt16LE()));
activeBasalRate.setActiveBasalProfileName(byteBuf.readUTF16(30));
activeBasalRate.setActiveBasalRate(byteBuf.readUInt16Decimal());
if (activeBasalRate.getActiveBasalProfile() != null) this.activeBasalRate = activeBasalRate;
}
public ActiveBasalRate getActiveBasalRate() {
return this.activeBasalRate;
}
}

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.ActiveBolus;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.ActiveBolusTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetActiveBolusesMessage extends AppLayerMessage {
private List<ActiveBolus> activeBoluses;
public GetActiveBolusesMessage() {
super(MessagePriority.NORMAL, true, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
activeBoluses = new ArrayList<>();
for (int i = 0; i < 3; i++) {
ActiveBolus activeBolus = new ActiveBolus();
activeBolus.setBolusID(byteBuf.readUInt16LE());
activeBolus.setBolusType(ActiveBolusTypeIDs.IDS.getType(byteBuf.readUInt16LE()));
byteBuf.shift(2);
byteBuf.shift(2);
activeBolus.setInitialAmount(byteBuf.readUInt16Decimal());
activeBolus.setRemainingAmount(byteBuf.readUInt16Decimal());
activeBolus.setRemainingDuration(byteBuf.readUInt16LE());
if (activeBolus.getBolusType() != null) activeBoluses.add(activeBolus);
}
}
public List<ActiveBolus> getActiveBoluses() {
return this.activeBoluses;
}
}

View file

@ -0,0 +1,29 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.ActiveTBR;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetActiveTBRMessage extends AppLayerMessage {
private ActiveTBR activeTBR;
public GetActiveTBRMessage() {
super(MessagePriority.NORMAL, true, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
ActiveTBR activeTBR = new ActiveTBR();
activeTBR.setPercentage(byteBuf.readUInt16LE());
activeTBR.setRemainingDuration(byteBuf.readUInt16LE());
activeTBR.setInitialDuration(byteBuf.readUInt16LE());
if (activeTBR.getPercentage() != 100) this.activeTBR = activeTBR;
}
public ActiveTBR getActiveTBR() {
return this.activeTBR;
}
}

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.BatteryStatus;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.BatteryTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.SymbolStatusIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetBatteryStatusMessage extends AppLayerMessage {
private BatteryStatus batteryStatus;
public GetBatteryStatusMessage() {
super(MessagePriority.NORMAL, false, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
batteryStatus = new BatteryStatus();
batteryStatus.setBatteryType(BatteryTypeIDs.IDS.getType(byteBuf.readUInt16LE()));
batteryStatus.setBatteryAmount(byteBuf.readUInt16LE());
batteryStatus.setSymbolStatus(SymbolStatusIDs.IDS.getType(byteBuf.readUInt16LE()));
}
public BatteryStatus getBatteryStatus() {
return this.batteryStatus;
}
}

View file

@ -0,0 +1,31 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.CartridgeStatus;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.CartridgeTypeIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.ids.SymbolStatusIDs;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetCartridgeStatusMessage extends AppLayerMessage {
private CartridgeStatus cartridgeStatus;
public GetCartridgeStatusMessage() {
super(MessagePriority.NORMAL, false, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
cartridgeStatus = new CartridgeStatus();
cartridgeStatus.setInserted(byteBuf.readBoolean());
cartridgeStatus.setCartridgeType(CartridgeTypeIDs.IDS.getType(byteBuf.readUInt16LE()));
cartridgeStatus.setSymbolStatus(SymbolStatusIDs.IDS.getType(byteBuf.readUInt16LE()));
cartridgeStatus.setRemainingAmount(byteBuf.readUInt16Decimal());
}
public CartridgeStatus getCartridgeStatus() {
return this.cartridgeStatus;
}
}

View file

@ -0,0 +1,31 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.PumpTime;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetDateTimeMessage extends AppLayerMessage {
private PumpTime pumpTime;
public GetDateTimeMessage() {
super(MessagePriority.NORMAL, true, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
pumpTime = new PumpTime();
pumpTime.setYear(byteBuf.readUInt16LE());
pumpTime.setMonth(byteBuf.readUInt8());
pumpTime.setDay(byteBuf.readUInt8());
pumpTime.setHour(byteBuf.readUInt8());
pumpTime.setMinute(byteBuf.readUInt8());
pumpTime.setSecond(byteBuf.readUInt8());
}
public PumpTime getPumpTime() {
return this.pumpTime;
}
}

View file

@ -0,0 +1,39 @@
package info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.status;
import android.util.Log;
import org.spongycastle.util.encoders.Hex;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.PumpInsightLocal.app_layer.Service;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.FirmwareVersions;
import info.nightscout.androidaps.plugins.PumpInsightLocal.descriptors.MessagePriority;
import info.nightscout.androidaps.plugins.PumpInsightLocal.utils.ByteBuf;
public class GetFirmwareVersionsMessage extends AppLayerMessage {
private FirmwareVersions firmwareVersions;
public GetFirmwareVersionsMessage() {
super(MessagePriority.NORMAL, false, false, Service.STATUS);
}
@Override
protected void parse(ByteBuf byteBuf) {
firmwareVersions = new FirmwareVersions();
firmwareVersions.setReleaseSWVersion(byteBuf.readASCII(13));
firmwareVersions.setUiProcSWVersion(byteBuf.readASCII(11));
firmwareVersions.setPcProcSWVersion(byteBuf.readASCII(11));
firmwareVersions.setMdTelProcSWVersion(byteBuf.readASCII(11));
firmwareVersions.setBtInfoPageVersion(byteBuf.readASCII(11));
firmwareVersions.setSafetyProcSWVersion(byteBuf.readASCII(11));
firmwareVersions.setConfigIndex(byteBuf.readUInt16LE());
firmwareVersions.setHistoryIndex(byteBuf.readUInt16LE());
firmwareVersions.setStateIndex(byteBuf.readUInt16LE());
firmwareVersions.setVocabularyIndex(byteBuf.readUInt16LE());
}
public FirmwareVersions getFirmwareVersions() {
return this.firmwareVersions;
}
}

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