resolve RS merge conflict

This commit is contained in:
Milos Kozak 2017-10-10 16:47:03 +02:00
commit d142d2e4f9
110 changed files with 7611 additions and 672 deletions

View file

@ -47,6 +47,10 @@ android {
version "1.54-dev"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild()
ndk {
moduleName "BleCommandUtil"
}
}
lintOptions {
disable 'MissingTranslation'

View file

@ -50,6 +50,13 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".plugins.PumpDanaRS.activities.BLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpDanaRS.activities.BLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" />
<receiver
android:name=".receivers.DataReceiver"
@ -113,6 +120,10 @@
android:name=".plugins.PumpDanaRv2.services.DanaRv2ExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.PumpDanaRS.services.DanaRSService"
android:enabled="true"
android:exported="true"></service>
<service
android:name=".plugins.Wear.wearintegration.WatchUpdaterService"
android:exported="true">

View file

@ -0,0 +1,120 @@
package com.cozmo.danar.util;
import android.content.Context;
import info.nightscout.androidaps.MainApp;
public class BleCommandUtil {
public static final int DANAR_PACKET__TYPE_ENCRYPTION_REQUEST = 0x01;
public static final int DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE = 0x02;
public static final int DANAR_PACKET__TYPE_COMMAND = 0xA1;
public static final int DANAR_PACKET__TYPE_RESPONSE = 0xB2;
public static final int DANAR_PACKET__TYPE_NOTIFY = 0xC3;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK = 0x00;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY = 0xD0;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST = 0xD1;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN = 0xD2;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION = 0x01;
public static final int DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_COMPLETE = 0x01;
public static final int DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_RATE_DISPLAY = 0x02;
public static final int DANAR_PACKET__OPCODE_NOTIFY__ALARM = 0x03;
public static final int DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM = 0x04;
public static final int DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION = 0x02;
public static final int DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS = 0x03;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_PASSWORD = 0x04;
public static final int DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG = 0x10;
public static final int DANAR_PACKET__OPCODE_REVIEW__BOLUS = 0x11;
public static final int DANAR_PACKET__OPCODE_REVIEW__DAILY = 0x12;
public static final int DANAR_PACKET__OPCODE_REVIEW__PRIME = 0x13;
public static final int DANAR_PACKET__OPCODE_REVIEW__REFILL = 0x14;
public static final int DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE = 0x15;
public static final int DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE = 0x16;
public static final int DANAR_PACKET__OPCODE_REVIEW__TEMPORARY = 0x17;
public static final int DANAR_PACKET__OPCODE_REVIEW__SUSPEND = 0x18;
public static final int DANAR_PACKET__OPCODE_REVIEW__ALARM = 0x19;
public static final int DANAR_PACKET__OPCODE_REVIEW__BASAL = 0x1A;
public static final int DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY = 0x1F;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION = 0x20;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_PUMP_CHECK = 0x21;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG = 0x22;
public static final int DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR = 0x23;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION = 0x24;
public static final int DANAR_PACKET__OPCODE_REVIEW__SET_HISTORY_UPLOAD_MODE = 0x25;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL = 0x26;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION = 0x40;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE = 0x41;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS = 0x42;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS = 0x43;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_STOP = 0x44;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION = 0x45;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_MENU_OPTION_STATE = 0x46;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS = 0x47;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_DUAL_BOLUS = 0x48;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL = 0x49;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_START = 0x4A;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CALCULATION_INFORMATION = 0x4B;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_RATE = 0x4C;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_RATE = 0x4D;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY = 0x4E;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_CIR_CF_ARRAY = 0x4F;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_OPTION = 0x50;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_OPTION = 0x51;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_TEMPORARY_BASAL = 0x60;
public static final int DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE = 0x61;
public static final int DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL = 0x62;
public static final int DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER = 0x63;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_NUMBER = 0x64;
public static final int DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_BASAL_RATE = 0x65;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_BASAL_RATE = 0x66;
public static final int DANAR_PACKET__OPCODE_BASAL__GET_BASAL_RATE = 0x67;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_BASAL_RATE = 0x68;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_ON = 0x69;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF = 0x6A;
public static final int DANAR_PACKET__OPCODE_OPTION__GET_PUMP_TIME = 0x70;
public static final int DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME = 0x71;
public static final int DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION = 0x72;
public static final int DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION = 0x73;
public static final int DANAR_PACKET__OPCODE_BASAL__APS_SET_TEMPORARY_BASAL = 0xC1;
public static final int DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS = 0xC2;
public static final int DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY = 0xC3;
public static final int DANAR_PACKET__OPCODE_ETC__SET_HISTORY_SAVE = 0xE0;
public static final int DANAR_PACKET__OPCODE_ETC__KEEP_CONNECTION = 0xFF;
static {
System.loadLibrary("BleCommandUtil");
}
private static native byte[] getEncryptedPacketJni(Object context, int opcode, byte[] bytes, String deviceName);
private static native byte[] getDecryptedPacketJni(Object context, byte[] bytes);
// ---------------------------------------------------------
private static BleCommandUtil mInstance = null;
public static BleCommandUtil getInstance() {
if (mInstance == null) {
mInstance = new BleCommandUtil();
}
return mInstance;
}
// ---------------------------------------------------------
public byte[] getEncryptedPacket(int opcode, byte[] bytes, String deviceName) {
return getEncryptedPacketJni(MainApp.instance().getApplicationContext(), opcode, bytes, deviceName);
}
public byte[] getDecryptedPacket(byte[] bytes) {
return getDecryptedPacketJni(MainApp.instance().getApplicationContext(), bytes);
}
}

View file

@ -44,6 +44,6 @@ public class Config {
// DanaR specific
public static final boolean logDanaBTComm = true;
public static final boolean logDanaMessageDetail = true;
public static boolean logDanaMessageDetail = true;
public static final boolean logDanaSerialEngine = true;
}

View file

@ -52,6 +52,8 @@ import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.services.DanaRSService;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService;
import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin;
@ -123,7 +125,8 @@ public class MainApp extends Application {
pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRPlugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.DANARv2) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRSPlugin.getPlugin());
pluginsList.add(CareportalFragment.getPlugin());
if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getInstance());
@ -207,6 +210,7 @@ public class MainApp extends Application {
startService(new Intent(this, DanaRExecutionService.class));
startService(new Intent(this, DanaRKoreanExecutionService.class));
startService(new Intent(this, DanaRv2ExecutionService.class));
startService(new Intent(this, DanaRSService.class));
}
keepAliveReceiver.setAlarm(this);
}

View file

@ -21,6 +21,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
@ -70,6 +71,8 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
EditTextPreference editTextPref = (EditTextPreference) pref;
if (pref.getKey().contains("password") || pref.getKey().contains("secret")) {
pref.setSummary("******");
} else if (pref.getKey().equals(MainApp.sResources.getString(R.string.key_danars_name))) {
pref.setSummary(SP.getString(R.string.key_danars_name,""));
} else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText());
@ -130,12 +133,16 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
DanaRPlugin danaRPlugin = MainApp.getSpecificPlugin(DanaRPlugin.class);
DanaRKoreanPlugin danaRKoreanPlugin = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
DanaRv2Plugin danaRv2Plugin = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
DanaRSPlugin danaRSPlugin = MainApp.getSpecificPlugin(DanaRSPlugin.class);
if (danaRPlugin.isEnabled(PluginBase.PUMP) || danaRKoreanPlugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_danar);
}
if (danaRv2Plugin != null && danaRv2Plugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_danarv2);
}
if (danaRSPlugin != null && danaRSPlugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_danars);
}
if (danaRPlugin.isEnabled(PluginBase.PROFILE) || danaRKoreanPlugin.isEnabled(PluginBase.PROFILE) || danaRv2Plugin != null && danaRv2Plugin.isEnabled(PluginBase.PROFILE)) {
addPreferencesFromResource(R.xml.pref_danarprofile);
}
@ -145,7 +152,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResource(R.xml.pref_virtualpump);
}
InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin = MainApp.getSpecificPlugin(InsulinOrefFreePeakPlugin.class);
if(insulinOrefFreePeakPlugin.isEnabled(PluginBase.INSULIN)){
if (insulinOrefFreePeakPlugin.isEnabled(PluginBase.INSULIN)) {
addPreferencesFromResource(R.xml.pref_insulinoreffreepeak);
}

View file

@ -18,14 +18,24 @@ public class EventPumpStatusChanged {
public int sSecondsElapsed = 0;
public String sPerfomingAction = "";
public static String error = "";
public EventPumpStatusChanged(int status) {
sStatus = status;
sSecondsElapsed = 0;
error = "";
}
public EventPumpStatusChanged(int status, int secondsElapsed) {
sStatus = status;
sSecondsElapsed = secondsElapsed;
error = "";
}
public EventPumpStatusChanged(int status, String error) {
sStatus = status;
sSecondsElapsed = 0;
this.error = error;
}
public EventPumpStatusChanged(String action) {

View file

@ -49,9 +49,9 @@ public class Notification {
public static final int NSURGENTALARM = 20;
public static final int SHORT_DIA = 21;
public static final int TOAST_ALARM = 22;
public static final int WRONGBASALSTEP = 23;
public static final int BOLUS_DELIVERY_ERROR = 24;
public int id;
public Date date;
public String text;

View file

@ -56,6 +56,7 @@ public class DanaRFragment extends SubscriberFragment {
TextView firmwareView;
TextView basalStepView;
TextView bolusStepView;
TextView serialNumberView;
Button viewProfileButton;
Button historyButton;
Button statsButton;
@ -105,6 +106,7 @@ public class DanaRFragment extends SubscriberFragment {
statsButton = (Button) view.findViewById(R.id.danar_stats);
basalStepView = (TextView) view.findViewById(R.id.danar_basalstep);
bolusStepView = (TextView) view.findViewById(R.id.danar_bolusstep);
serialNumberView = (TextView) view.findViewById(R.id.danar_serialnumber);
viewProfileButton.setOnClickListener(new View.OnClickListener() {
@ -246,6 +248,7 @@ public class DanaRFragment extends SubscriberFragment {
}
basalStepView.setText("" + pump.basalStep);
bolusStepView.setText("" + pump.bolusStep);
serialNumberView.setText("" + pump.serialNumber);
}
});

View file

@ -649,7 +649,11 @@ public class DanaRPlugin implements PluginBase, PumpInterface, DanaRInterface, C
}
public static void doConnect(String from) {
if (sExecutionService != null) sExecutionService.connect(from);
if (sExecutionService != null) {
sExecutionService.connect(from);
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
}
}
public static boolean isConnected() {

View file

@ -9,8 +9,10 @@ import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.utils.SP;
@ -52,6 +54,7 @@ public class DanaRPump {
public static final int PRIME = 12;
public static final int PROFILECHANGE = 13;
public static final int CARBS = 14;
public static final int PRIMECANNULA = 15;
public Date lastConnection = new Date(0);
public Date lastSettingsRead = new Date(0);
@ -78,10 +81,12 @@ public class DanaRPump {
public boolean pumpSuspended;
public boolean calculatorEnabled;
public double dailyTotalUnits;
public double dailyTotalBolusUnits = 0; // RS only
public double dailyTotalBasalUnits = 0; // RS only
public int maxDailyTotalUnits;
public double bolusStep;
public double basalStep;
public double bolusStep = 0.1;
public double basalStep = 0.1;
public double iob;
@ -108,6 +113,7 @@ public class DanaRPump {
public int extendedBolusSoFarInMinutes;
public Date extendedBolusStart;
public int extendedBolusRemainingMinutes;
public double extendedBolusDeliveredSoFar; //RS only
// Profile
public int units;
@ -136,6 +142,27 @@ public class DanaRPump {
public double maxBolus;
public double maxBasal;
// DanaRS specific
public String rs_password = "";
// User settings
public int timeDisplayType;
public int buttonScrollOnOff;
public int beepAndAlarm;
public int lcdOnTimeSec;
public int backlightOnTimeSec;
public int selectedLanguage;
public int shutdownHour;
public int lowReservoirRate;
public int cannulaVolume;
public int refillAmount;
public double initialBolusAmount;
// Bolus settings
public int bolusCalculationOption;
public int missedBolusConfig;
public String getUnits() {
return units == UNITS_MGDL ? Constants.MGDL : Constants.MMOL;
}
@ -205,4 +232,17 @@ public class DanaRPump {
return PROFILE_PREFIX + (activeProfile + 1);
}
public static double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
//Some values get truncated to the next lower one.
// -> round them to two decimals and make sure we are a small delta larger (that will get truncated)
double value = Math.round(100d * nsProfile.getBasal((Integer) (hour * 60 * 60)))/100d + 0.00001;
if (Config.logDanaMessageDetail)
log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value;
}
return record;
}
}

View file

@ -42,6 +42,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionServi
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils;
@ -122,6 +123,7 @@ public class DanaRHistoryActivity extends Activity {
statusView.setVisibility(View.GONE);
boolean isKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginBase.PUMP);
boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginBase.PUMP);
// Types
@ -132,8 +134,12 @@ public class DanaRHistoryActivity extends Activity {
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_CARBO, getString(R.string.danar_history_carbohydrates)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_DAILY, getString(R.string.danar_history_dailyinsulin)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_GLUCOSE, getString(R.string.danar_history_glucose)));
if (!isKorean) {
if (!isKorean && !isRS) {
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_ERROR, getString(R.string.danar_history_errors)));
}
if (isRS)
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_PRIME, getString(R.string.danar_history_prime)));
if (!isKorean) {
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_REFILL, getString(R.string.danar_history_refill)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_SUSPEND, getString(R.string.danar_history_syspend)));
}

View file

@ -40,6 +40,13 @@ public class MsgSettingMeal extends MessageBase {
log.debug("Is Config U/d: " + pump.isConfigUD);
}
if (pump.basalStep != 0.01d) {
Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.sResources.getString(R.string.danar_setbasalstep001), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP));
}
if (pump.isConfigUD) {
Notification notification = new Notification(Notification.UD_MODE_ENABLED, MainApp.sResources.getString(R.string.danar_switchtouhmode), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));

View file

@ -24,9 +24,10 @@ public class MsgStatusBasic extends MessageBase {
pump.reservoirRemainingUnits = intFromBuff(bytes, 7, 3) / 750d;
pump.bolusBlocked = intFromBuff(bytes, 10, 1) == 1;
pump.currentBasal = intFromBuff(bytes, 11, 2) / 100d;
pump.tempBasalPercent = intFromBuff(bytes, 13, 1);
pump.isExtendedInProgress = intFromBuff(bytes, 14, 1) == 1;
pump.isTempBasalInProgress = intFromBuff(bytes, 15, 1) == 1;
// removed. info taken from tempstatus message
//pump.tempBasalPercent = intFromBuff(bytes, 13, 1);
//pump.isExtendedInProgress = intFromBuff(bytes, 14, 1) == 1;
//pump.isTempBasalInProgress = intFromBuff(bytes, 15, 1) == 1;
pump.batteryRemaining = intFromBuff(bytes, 20, 1);
if (Config.logDanaMessageDetail) {
@ -37,9 +38,9 @@ public class MsgStatusBasic extends MessageBase {
log.debug("Reservoir remaining units: " + pump.reservoirRemainingUnits);
log.debug("Bolus blocked: " + pump.bolusBlocked);
log.debug("Current basal: " + pump.currentBasal);
log.debug("Current temp basal percent: " + pump.tempBasalPercent);
log.debug("Is extended bolus running: " + pump.isExtendedInProgress);
log.debug("Is temp basal running: " + pump.isTempBasalInProgress);
//log.debug("Current temp basal percent: " + pump.tempBasalPercent);
//log.debug("Is extended bolus running: " + pump.isExtendedInProgress);
//log.debug("Is temp basal running: " + pump.isTempBasalInProgress);
}
}
}

View file

@ -109,7 +109,7 @@ public class DanaRExecutionService extends Service {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
log.debug("Device has disconnected " + device.getName());//Device has disconnected
log.debug("Device was disconnected " + device.getName());//Device was disconnected
if (mBTDevice != null && mBTDevice.getName() != null && mBTDevice.getName().equals(device.getName())) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast");
@ -290,10 +290,13 @@ public class DanaRExecutionService extends Service {
}
}
mSerialIOThread.sendMessage(tempStatusMsg); // do this before statusBasic because here is temp duration
mSerialIOThread.sendMessage(exStatusMsg);
mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus)));
if (!statusMsg.received) {
mSerialIOThread.sendMessage(statusMsg);
@ -319,6 +322,7 @@ public class DanaRExecutionService extends Service {
Date now = new Date();
if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime() || !MainApp.getSpecificPlugin(DanaRPlugin.class).isInitialized()) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingMeal());
@ -329,6 +333,7 @@ public class DanaRExecutionService extends Service {
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds");
@ -526,7 +531,7 @@ public class DanaRExecutionService extends Service {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = buildDanaRProfileRecord(profile);
double[] basal = DanaRPump.buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet);
MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0);
@ -537,19 +542,6 @@ public class DanaRExecutionService extends Service {
return true;
}
private double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
//Some values get truncated to the next lower one.
// -> round them to two decimals and make sure we are a small delta larger (that will get truncated)
double value = Math.round(100d * nsProfile.getBasal((Integer) (hour * 60 * 60)))/100d + 0.00001;
if (Config.logDanaMessageDetail)
log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value;
}
return record;
}
private void waitMsec(long msecs) {
SystemClock.sleep(msecs);
}

View file

@ -646,7 +646,11 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, DanaRInterf
}
public static void doConnect(String from) {
if (sExecutionService != null) sExecutionService.connect(from);
if (sExecutionService != null) {
sExecutionService.connect(from);
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
}
}
public static boolean isConnected() {

View file

@ -105,7 +105,7 @@ public class DanaRKoreanExecutionService extends Service {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
log.debug("Device has disconnected " + device.getName());//Device has disconnected
log.debug("Device was disconnected " + device.getName());//Device was disconnected
if (mBTDevice != null && mBTDevice.getName() != null && mBTDevice.getName().equals(device.getName())) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast");
@ -286,11 +286,13 @@ public class DanaRKoreanExecutionService extends Service {
}
}
mSerialIOThread.sendMessage(new MsgSettingShippingInfo()); // TODO: show it somewhere
mSerialIOThread.sendMessage(tempStatusMsg); // do this before statusBasic because here is temp duration
mSerialIOThread.sendMessage(exStatusMsg);
//mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus)));
// if (!statusMsg.received) {
// mSerialIOThread.sendMessage(statusMsg);
@ -316,6 +318,7 @@ public class DanaRKoreanExecutionService extends Service {
Date now = new Date();
if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime() || !MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isInitialized()) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingMeal());
mSerialIOThread.sendMessage(new MsgSettingBasal_k());
@ -323,6 +326,8 @@ public class DanaRKoreanExecutionService extends Service {
mSerialIOThread.sendMessage(new MsgSettingMaxValues());
mSerialIOThread.sendMessage(new MsgSettingGlucose());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 10) {
@ -502,7 +507,7 @@ public class DanaRKoreanExecutionService extends Service {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = buildDanaRProfileRecord(profile);
double[] basal = DanaRPump.buildDanaRProfileRecord(profile);
MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal);
mSerialIOThread.sendMessage(msgSet);
danaRPump.lastSettingsRead = new Date(0); // force read full settings
@ -511,17 +516,6 @@ public class DanaRKoreanExecutionService extends Service {
return true;
}
private double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
double value = Math.round(100d * nsProfile.getBasal((Integer) (hour * 60 * 60)))/100d + 0.00001;
if (Config.logDanaMessageDetail)
log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value;
}
return record;
}
private void waitMsec(long msecs) {
SystemClock.sleep(msecs);
}

View file

@ -0,0 +1,809 @@
package info.nightscout.androidaps.plugins.PumpDanaRS;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Objects;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.DanaRInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSDeviceChange;
import info.nightscout.androidaps.plugins.PumpDanaRS.services.DanaRSService;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
/**
* Created by mike on 03.09.2017.
*/
public class DanaRSPlugin implements PluginBase, PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface {
private static Logger log = LoggerFactory.getLogger(DanaRSPlugin.class);
@Override
public int getType() {
return PluginBase.PUMP;
}
@Override
public String getFragmentClass() {
return DanaRFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.danarspump);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.danarspump_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
@Override
public boolean isEnabled(int type) {
if (type == PluginBase.PROFILE) return fragmentProfileEnabled && fragmentPumpEnabled;
else if (type == PluginBase.PUMP) return fragmentPumpEnabled;
else if (type == PluginBase.CONSTRAINTS) return fragmentPumpEnabled;
return false;
}
@Override
public boolean isVisibleInTabs(int type) {
if (type == PluginBase.PROFILE || type == PluginBase.CONSTRAINTS) return false;
else if (type == PluginBase.PUMP) return fragmentPumpVisible;
return false;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return type == PUMP;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == PluginBase.PROFILE)
this.fragmentProfileEnabled = fragmentEnabled;
else if (type == PluginBase.PUMP)
this.fragmentPumpEnabled = fragmentEnabled;
// if pump profile was enabled need to switch to another too
if (type == PluginBase.PUMP && !fragmentEnabled && this.fragmentProfileEnabled) {
setFragmentEnabled(PluginBase.PROFILE, false);
setFragmentVisible(PluginBase.PROFILE, false);
MainApp.getSpecificPlugin(NSProfilePlugin.class).setFragmentEnabled(PluginBase.PROFILE, true);
MainApp.getSpecificPlugin(NSProfilePlugin.class).setFragmentVisible(PluginBase.PROFILE, true);
}
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == PluginBase.PUMP)
this.fragmentPumpVisible = fragmentVisible;
}
static boolean fragmentPumpEnabled = false;
static boolean fragmentProfileEnabled = false;
static boolean fragmentPumpVisible = false;
public static DanaRSService danaRSService;
public static String mDeviceAddress = "";
public static String mDeviceName = "";
private static DanaRSPlugin plugin = null;
private static DanaRPump pump = DanaRPump.getInstance();
public static PumpDescription pumpDescription = new PumpDescription();
public static DanaRSPlugin getPlugin() {
if (plugin == null)
plugin = new DanaRSPlugin();
return plugin;
}
DanaRSPlugin() {
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, DanaRSService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
MainApp.bus().register(this);
onStatusEvent(new EventDanaRSDeviceChange()); // load device name
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.05d;
pumpDescription.isExtendedBolusCapable = true;
pumpDescription.extendedBolusStep = 0.05d;
pumpDescription.extendedBolusDurationStep = 30;
pumpDescription.extendedBolusMaxDuration = 8 * 60;
pumpDescription.isTempBasalCapable = true;
pumpDescription.tempBasalStyle = PumpDescription.PERCENT;
pumpDescription.maxTempPercent = 200;
pumpDescription.tempPercentStep = 10;
pumpDescription.tempDurationStep = 60;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = true;
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.04d;
pumpDescription.isRefillingCapable = true;
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
log.debug("Service is disconnected");
danaRSService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
log.debug("Service is connected");
DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder) service;
danaRSService = mLocalBinder.getServiceInstance();
}
};
@SuppressWarnings("UnusedParameters")
@Subscribe
public void onStatusEvent(final EventAppExit e) {
MainApp.instance().getApplicationContext().unbindService(mConnection);
}
@Subscribe
public void onStatusEvent(final EventDanaRSDeviceChange e) {
mDeviceAddress = SP.getString(R.string.key_danars_address, "");
mDeviceName = SP.getString(R.string.key_danars_name, "");
}
public static void connectIfNotConnected(String from) {
if (!isConnected())
connect(from);
}
public static void connect(String from) {
if (danaRSService != null && !mDeviceAddress.equals("") && !mDeviceName.equals("")) {
final Object o = new Object();
danaRSService.connect(from, mDeviceAddress, o);
synchronized (o) {
try {
o.wait(20000);
} catch (InterruptedException e) {
log.error("InterruptedException " + e);
}
}
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
log.debug("RS connected:" + from);
}
}
public static boolean isConnected() {
return danaRSService != null && danaRSService.isConnected();
}
public static boolean isConnecting() {
return danaRSService != null && danaRSService.isConnecting();
}
public static void disconnect(String from) {
if (danaRSService != null) danaRSService.disconnect(from);
}
public static void sendMessage(DanaRS_Packet message) {
if (danaRSService != null) danaRSService.sendMessage(message);
}
// DanaR interface
@Override
public boolean loadHistory(byte type) {
connectIfNotConnected("loadHistory");
return danaRSService.loadHistory(type);
}
// Constraints interface
@Override
public boolean isLoopEnabled() {
return true;
}
@Override
public boolean isClosedModeEnabled() {
return true;
}
@Override
public boolean isAutosensModeEnabled() {
return true;
}
@Override
public boolean isAMAModeEnabled() {
return true;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
double origAbsoluteRate = absoluteRate;
if (pump != null) {
if (absoluteRate > pump.maxBasal) {
absoluteRate = pump.maxBasal;
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
log.debug("Limiting rate " + origAbsoluteRate + "U/h by pump constraint to " + absoluteRate + "U/h");
}
}
return absoluteRate;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
Integer origPercentRate = percentRate;
if (percentRate < 0) percentRate = 0;
if (percentRate > getPumpDescription().maxTempPercent)
percentRate = getPumpDescription().maxTempPercent;
if (!Objects.equals(percentRate, origPercentRate) && Config.logConstraintsChanges && !Objects.equals(origPercentRate, Constants.basalPercentOnlyForCheckLimit))
log.debug("Limiting percent rate " + origPercentRate + "% to " + percentRate + "%");
return percentRate;
}
@Override
public Double applyBolusConstraints(Double insulin) {
double origInsulin = insulin;
if (pump != null) {
if (insulin > pump.maxBolus) {
insulin = pump.maxBolus;
if (Config.logConstraintsChanges && origInsulin != Constants.bolusOnlyForCheckLimit)
log.debug("Limiting bolus " + origInsulin + "U by pump constraint to " + insulin + "U");
}
}
return insulin;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
return carbs;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
return maxIob;
}
// Profile interface
@Nullable
@Override
public ProfileStore getProfile() {
if (pump.lastSettingsRead.getTime() == 0)
return null; // no info now
return pump.createConvertedProfile();
}
@Override
public String getUnits() {
return pump.getUnits();
}
@Override
public String getProfileName() {
return pump.createConvertedProfileName();
}
// Pump interface
@Override
public boolean isInitialized() {
return pump.lastConnection.getTime() > 0;
}
@Override
public boolean isSuspended() {
return pump.pumpSuspended;
}
@Override
public boolean isBusy() {
if (danaRSService == null) return false;
return danaRSService.isConnected() || danaRSService.isConnecting();
}
@Override
public int setNewBasalProfile(Profile profile) {
if (danaRSService == null) {
log.error("setNewBasalProfile sExecutionService is null");
return FAILED;
}
if (!isInitialized()) {
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return FAILED;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
}
connectIfNotConnected("updateBasalsInPump");
if (!danaRSService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.sResources.getString(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return FAILED;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
return SUCCESS;
}
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
if (pump.pumpProfiles == null)
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
int basalValues = pump.basal48Enable ? 48 : 24;
int basalIncrement = pump.basal48Enable ? 30 * 60 : 60 * 60;
for (int h = 0; h < basalValues; h++) {
Double pumpValue = pump.pumpProfiles[pump.activeProfile][h];
Double profileValue = profile.getBasal((Integer) (h * basalIncrement));
if (profileValue == null) return true;
if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) {
log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue);
return false;
}
}
return true;
}
@Override
public Date lastDataTime() {
return pump.lastConnection;
}
@Override
public void refreshDataFromPump(String reason) {
if (!isConnected() && !isConnecting()) {
connect(reason);
}
}
@Override
public double getBaseBasalRate() {
return pump.currentBasal;
}
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder();
detailedBolusInfo.insulin = configBuilderPlugin.applyBolusConstraints(detailedBolusInfo.insulin);
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) {
DetailedBolusInfoStorage.add(detailedBolusInfo); // will be picked up on reading history
int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0);
int speed = 12;
switch (preferencesSpeed) {
case 0:
speed = 12;
break;
case 1:
speed = 30;
break;
case 2:
speed = 60;
break;
}
// v2 stores end time for bolus, we need to adjust time
// default delivery speed is 12 U/min
detailedBolusInfo.date += detailedBolusInfo.insulin / speed * 60d * 1000;
// clean carbs to prevent counting them as twice because they will picked up as another record
// I don't think it's necessary to copy DetailedBolusInfo right now for carbs records
double carbs = detailedBolusInfo.carbs;
detailedBolusInfo.carbs = 0;
int carbTime = detailedBolusInfo.carbTime;
detailedBolusInfo.carbTime = 0;
Treatment t = new Treatment();
boolean connectionOK = false;
connectIfNotConnected("bolus");
if (detailedBolusInfo.insulin > 0 || carbs > 0)
connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, System.currentTimeMillis() + carbTime * 60 * 1000 + 1000, t); // +1000 to make the record different
PumpEnactResult result = new PumpEnactResult();
result.success = connectionOK;
result.bolusDelivered = t.insulin;
result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
// remove carbs because it's get from history seprately
return result;
} else {
PumpEnactResult result = new PumpEnactResult();
result.success = false;
result.bolusDelivered = 0d;
result.carbsDelivered = 0d;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input");
return result;
}
}
@Override
public void stopBolusDelivering() {
if (danaRSService == null) {
log.error("stopBolusDelivering sExecutionService is null");
return;
}
danaRSService.bolusStop();
}
// This is called from APS
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean force) {
// Recheck pump status if older than 30 min
if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) {
connect("setTempBasalAbsolute old data");
}
PumpEnactResult result = new PumpEnactResult();
ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder();
absoluteRate = configBuilderPlugin.applyBasalConstraints(absoluteRate);
final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d;
final boolean doLowTemp = absoluteRate < getBaseBasalRate();
final boolean doHighTemp = absoluteRate > getBaseBasalRate();
if (doTempOff) {
// If temp in progress
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)");
return cancelTempBasal(false);
}
result.success = true;
result.enacted = false;
result.percent = 100;
result.isPercent = true;
result.isTempCancel = true;
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: doTempOff OK");
return result;
}
if (doLowTemp || doHighTemp) {
Integer percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue();
else percentRate = Round.floorTo((double) percentRate, 10d).intValue();
if (percentRate > 500) // Special high temp 500/15min
percentRate = 500;
// Check if some temp is already in progress
if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
// Correct basal already set ?
if (MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis()).percentRate == percentRate) {
if (!force) {
result.success = true;
result.percent = percentRate;
result.absolute = MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory();
result.enacted = false;
result.duration = ((Double) MainApp.getConfigBuilder().getTempBasalRemainingMinutesFromHistory()).intValue();
result.isPercent = true;
result.isTempCancel = false;
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)");
return result;
}
}
}
// Convert duration from minutes to hours
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)");
// use special APS temp basal call ... 100+/15min .... 100-/30min
result = setHighTempBasalPercent(percentRate);
if (!result.success) {
log.error("setTempBasalAbsolute: Failed to set hightemp basal");
return result;
}
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: hightemp basal set ok");
return result;
}
// We should never end here
log.error("setTempBasalAbsolute: Internal error");
result.success = false;
result.comment = "Internal error";
return result;
}
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
PumpEnactResult result = new PumpEnactResult();
ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder();
percent = configBuilderPlugin.applyBasalConstraints(percent);
if (percent < 0) {
result.isTempCancel = false;
result.enacted = false;
result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("setTempBasalPercent: Invalid input");
return result;
}
if (percent > getPumpDescription().maxTempPercent)
percent = getPumpDescription().maxTempPercent;
TemporaryBasal runningTB = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (runningTB != null && runningTB.percentRate == percent) {
result.enacted = false;
result.success = true;
result.isTempCancel = false;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent;
result.absolute = MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory();
result.isPercent = true;
if (Config.logPumpActions)
log.debug("setTempBasalPercent: Correct value already set");
return result;
}
int durationInHours = Math.max(durationInMinutes / 60, 1);
connectIfNotConnected("tempbasal");
boolean connectionOK = danaRSService.tempBasal(percent, durationInHours);
if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) {
result.enacted = true;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.isTempCancel = false;
result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent;
result.absolute = MainApp.getConfigBuilder().getTempBasalAbsoluteRateHistory();
result.isPercent = true;
if (Config.logPumpActions)
log.debug("setTempBasalPercent: OK");
return result;
}
result.enacted = false;
result.success = false;
result.comment = MainApp.instance().getString(R.string.tempbasaldeliveryerror);
log.error("setTempBasalPercent: Failed to set temp basal");
return result;
}
public PumpEnactResult setHighTempBasalPercent(Integer percent) {
PumpEnactResult result = new PumpEnactResult();
connectIfNotConnected("hightempbasal");
boolean connectionOK = danaRSService.highTempBasal(percent);
if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) {
result.enacted = true;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.isTempCancel = false;
result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent;
result.isPercent = true;
if (Config.logPumpActions)
log.debug("setHighTempBasalPercent: OK");
return result;
}
result.enacted = false;
result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly);
log.error("setHighTempBasalPercent: Failed to set temp basal");
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder();
insulin = configBuilderPlugin.applyBolusConstraints(insulin);
// needs to be rounded
int durationInHalfHours = Math.max(durationInMinutes / 30, 1);
insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep * (1 + durationInHalfHours % 1));
PumpEnactResult result = new PumpEnactResult();
ExtendedBolus runningEB = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = false;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.duration = pump.extendedBolusRemainingMinutes;
result.absolute = pump.extendedBolusAbsoluteRate;
result.isPercent = false;
result.isTempCancel = false;
if (Config.logPumpActions)
log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount + " Asked: " + insulin);
return result;
}
connectIfNotConnected("extendedBolus");
boolean connectionOK = danaRSService.extendedBolus(insulin, durationInHalfHours);
if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAmount - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = true;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.isTempCancel = false;
result.duration = pump.extendedBolusRemainingMinutes;
result.absolute = pump.extendedBolusAbsoluteRate;
result.bolusDelivered = pump.extendedBolusAmount;
result.isPercent = false;
if (Config.logPumpActions)
log.debug("setExtendedBolus: OK");
return result;
}
result.enacted = false;
result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly);
log.error("setExtendedBolus: Failed to extended bolus");
return result;
}
@Override
public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult();
TemporaryBasal runningTB = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (runningTB != null) {
connectIfNotConnected("tempBasalStop");
danaRSService.tempBasalStop();
result.enacted = true;
result.isTempCancel = true;
}
if (!pump.isTempBasalInProgress) {
result.success = true;
result.isTempCancel = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (Config.logPumpActions)
log.debug("cancelRealTempBasal: OK");
return result;
} else {
result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly);
result.isTempCancel = true;
log.error("cancelRealTempBasal: Failed to cancel temp basal");
return result;
}
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult();
ExtendedBolus runningEB = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
if (runningEB != null) {
connectIfNotConnected("extendedBolusStop");
danaRSService.extendedBolusStop();
result.enacted = true;
result.isTempCancel = true;
}
if (!pump.isExtendedInProgress) {
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (Config.logPumpActions)
log.debug("cancelExtendedBolus: OK");
return result;
} else {
result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly);
log.error("cancelExtendedBolus: Failed to cancel extended bolus");
return result;
}
}
@Override
public JSONObject getJSONStatus() {
if (pump.lastConnection.getTime() + 5 * 60 * 1000L < System.currentTimeMillis()) {
return null;
}
JSONObject pumpjson = new JSONObject();
JSONObject battery = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
try {
battery.put("percent", pump.batteryRemaining);
status.put("status", pump.pumpSuspended ? "suspended" : "normal");
status.put("timestamp", DateUtil.toISOString(pump.lastConnection));
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extended.put("PumpIOB", pump.iob);
if (pump.lastBolusTime.getTime() != 0) {
extended.put("LastBolus", pump.lastBolusTime.toLocaleString());
extended.put("LastBolusAmount", pump.lastBolusAmount);
}
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(System.currentTimeMillis()));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
}
ExtendedBolus eb = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
pumpjson.put("battery", battery);
pumpjson.put("status", status);
pumpjson.put("extended", extended);
pumpjson.put("reservoir", (int) pump.reservoirRemainingUnits);
pumpjson.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
return pumpjson;
}
@Override
public String deviceID() {
return pump.serialNumber;
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return null;
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
}

View file

@ -0,0 +1,232 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.activities;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSDeviceChange;
import info.nightscout.utils.SP;
public class BLEScanActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(BLEScanActivity.class);
private Context mContext = null;
private ListView listView = null;
private ListAdapter mListAdapter = null;
private ArrayList<BluetoothDeviceItem> mDevices = new ArrayList<>();
;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothLeScanner mBluetoothLeScanner = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.danars_blescanner_activity);
mListAdapter = new ListAdapter();
listView = (ListView) findViewById(R.id.danars_blescanner_listview);
listView.setEmptyView(findViewById(R.id.danars_blescanner_nodevice));
listView.setAdapter(mListAdapter);
initView();
}
private void initView() {
mContext = getApplicationContext();
BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
// MIKE: test mBluetoothLeScanner for null (bt disabled)
mListAdapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
super.onResume();
startScan();
}
@Override
protected void onPause() {
super.onPause();
stopScan();
}
private void startScan() {
mBluetoothLeScanner.startScan(mBleScanCallback);
}
private void stopScan() {
mBluetoothLeScanner.stopScan(mBleScanCallback);
}
private void addBleDevice(BluetoothDevice device) {
if (device == null || device.getName() == null || device.getName().equals("")) {
return;
}
BluetoothDeviceItem item = new BluetoothDeviceItem(device);
if (!isSNCheck(device.getName()) || mDevices.contains(item)) {
return;
}
mDevices.add(item);
new Handler().post(new Runnable() {
public void run() {
mListAdapter.notifyDataSetChanged();
}
});
}
private ScanCallback mBleScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
addBleDevice(result.getDevice());
}
};
class ListAdapter extends BaseAdapter {
@Override
public int getCount() {
return mDevices.size();
}
@Override
public BluetoothDeviceItem getItem(int i) {
return mDevices.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = View.inflate(mContext, R.layout.danars_blescanner_item, null);
holder = new ViewHolder(v);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
BluetoothDeviceItem item = getItem(i);
holder.setData(i, item);
return v;
}
private class ViewHolder implements View.OnClickListener {
private BluetoothDeviceItem item = null;
private TextView mName = null;
private TextView mAddress = null;
public ViewHolder(View v) {
mName = (TextView) v.findViewById(R.id.ble_name);
mAddress = (TextView) v.findViewById(R.id.ble_address);
v.setOnClickListener(ViewHolder.this);
}
@Override
public void onClick(View v) {
SP.putString(R.string.key_danars_address, item.device.getAddress());
SP.putString(R.string.key_danars_name, mName.getText().toString());
MainApp.bus().post(new EventDanaRSDeviceChange());
finish();
}
public void setData(int pos, BluetoothDeviceItem data) {
if (data != null) {
try {
String tTitle = data.device.getName();
if (tTitle == null || tTitle.equals("")) {
tTitle = "(unknown)";
} else if (tTitle.length() > 10) {
tTitle = tTitle.substring(0, 10);
}
mName.setText(tTitle);
mAddress.setText(data.device.getAddress());
item = data;
} catch (Exception e) {
}
}
}
}
}
//
private class BluetoothDeviceItem {
private BluetoothDevice device;
public BluetoothDeviceItem(BluetoothDevice device) {
super();
this.device = device;
}
@Override
public boolean equals(Object o) {
if (device == null || o == null || !(o instanceof BluetoothDeviceItem)) {
return false;
}
BluetoothDeviceItem checkItem = (BluetoothDeviceItem) o;
if (checkItem.device == null) {
return false;
}
return stringEquals(device.getAddress(), checkItem.device.getAddress());
}
public boolean stringEquals(String arg1, String arg2) {
try {
return arg1.equals(arg2);
} catch (Exception e) {
return false;
}
}
}
public static boolean isSNCheck(String sn) {
String regex = "^([a-zA-Z]{3})([0-9]{5})([a-zA-Z]{2})$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sn);
return m.matches();
}
}

View file

@ -0,0 +1,15 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class PairingHelperActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PairingProgressDialog bolusProgressDialog = new PairingProgressDialog();
bolusProgressDialog.setHelperActivity(this);
bolusProgressDialog.show(this.getSupportFragmentManager(), "PairingProgress");
}
}

View file

@ -0,0 +1,148 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.activities;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSPairingSuccess;
public class PairingProgressDialog extends DialogFragment implements View.OnClickListener {
TextView statusView;
ProgressBar progressBar;
Button button;
PairingHelperActivity helperActivity;
static int secondsPassed = 0;
public static boolean pairingEnded = false;
public static boolean running = true;
private static Handler sHandler;
private static HandlerThread sHandlerThread;
public PairingProgressDialog() {
super();
// Required empty public constructor
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(PairingProgressDialog.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
secondsPassed = 0;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.danars_pairingprogressdialog, container, false);
getDialog().setTitle(MainApp.sResources.getString(R.string.pairing));
statusView = (TextView) view.findViewById(R.id.danars_paringprogress_status);
progressBar = (ProgressBar) view.findViewById(R.id.danars_paringprogress_progressbar);
button = (Button) view.findViewById(R.id.ok);
progressBar.setMax(100);
progressBar.setProgress(0);
statusView.setText(MainApp.sResources.getString(R.string.waitingforpairing));
button.setVisibility(View.GONE);
button.setOnClickListener(this);
setCancelable(false);
sHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (pairingEnded) {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setProgress(100);
statusView.setText(R.string.pairingok);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
dismiss();
}
});
} else
dismiss();
return;
}
progressBar.setProgress(i * 5);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setProgress(100);
statusView.setText(R.string.pairingtimedout);
button.setVisibility(View.VISIBLE);
}
});
}
}
});
return view;
}
@Override
public void onResume() {
super.onResume();
MainApp.bus().register(this);
running = true;
if (pairingEnded) dismiss();
}
@Override
public void dismiss() {
super.dismiss();
if (helperActivity != null) {
helperActivity.finish();
}
}
@Override
public void onPause() {
super.onPause();
MainApp.bus().unregister(this);
running = false;
}
@Subscribe
public void onStatusEvent(final EventDanaRSPairingSuccess ev) {
pairingEnded = true;
}
public void setHelperActivity(PairingHelperActivity activity) {
this.helperActivity = activity;
}
@Override
public void onClick(View v) {
running = false;
dismiss();
}
}

View file

@ -0,0 +1,108 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import info.nightscout.androidaps.Config;
/**
* Created by mike on 28.05.2016.
*/
public class DanaRSMessageHashTable {
private static Logger log = LoggerFactory.getLogger(DanaRSMessageHashTable.class);
public static HashMap<Integer, DanaRS_Packet> messages = null;
static {
if (messages == null) {
boolean savedState = Config.logDanaMessageDetail;
Config.logDanaMessageDetail = false;
messages = new HashMap<>();
put(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
put(new DanaRS_Packet_Basal_Get_Basal_Rate());
put(new DanaRS_Packet_Basal_Get_Profile_Basal_Rate());
put(new DanaRS_Packet_Basal_Get_Profile_Number());
put(new DanaRS_Packet_Basal_Set_Basal_Rate());
put(new DanaRS_Packet_Basal_Set_Profile_Basal_Rate());
put(new DanaRS_Packet_Basal_Set_Profile_Number());
put(new DanaRS_Packet_Basal_Set_Suspend_Off());
put(new DanaRS_Packet_Basal_Set_Suspend_On());
put(new DanaRS_Packet_Basal_Set_Temporary_Basal());
put(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
put(new DanaRS_Packet_Bolus_Get_Bolus_Option());
put(new DanaRS_Packet_Bolus_Get_Initial_Bolus());
put(new DanaRS_Packet_Bolus_Get_Calculation_Information());
put(new DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information());
put(new DanaRS_Packet_Bolus_Get_CIR_CF_Array());
put(new DanaRS_Packet_Bolus_Get_Dual_Bolus());
put(new DanaRS_Packet_Bolus_Get_Extended_Bolus());
put(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
put(new DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State());
put(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information());
put(new DanaRS_Packet_Bolus_Set_Bolus_Option());
put(new DanaRS_Packet_Bolus_Set_Initial_Bolus());
put(new DanaRS_Packet_Bolus_Set_CIR_CF_Array());
put(new DanaRS_Packet_Bolus_Set_Dual_Bolus());
put(new DanaRS_Packet_Bolus_Set_Extended_Bolus());
put(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel());
put(new DanaRS_Packet_Bolus_Set_Step_Bolus_Start());
put(new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop());
put(new DanaRS_Packet_Etc_Keep_Connection());
put(new DanaRS_Packet_Etc_Set_History_Save());
put(new DanaRS_Packet_General_Delivery_Status());
put(new DanaRS_Packet_General_Get_Password());
put(new DanaRS_Packet_General_Initial_Screen_Information());
put(new DanaRS_Packet_Notify_Alarm());
put(new DanaRS_Packet_Notify_Delivery_Complete());
put(new DanaRS_Packet_Notify_Delivery_Rate_Display());
put(new DanaRS_Packet_Notify_Missed_Bolus_Alarm());
put(new DanaRS_Packet_Option_Get_Pump_Time());
put(new DanaRS_Packet_Option_Get_User_Option());
put(new DanaRS_Packet_Option_Set_Pump_Time());
put(new DanaRS_Packet_Option_Set_User_Option());
//put(new DanaRS_Packet_History_());
put(new DanaRS_Packet_History_Alarm());
put(new DanaRS_Packet_History_All_History());
put(new DanaRS_Packet_History_Basal());
put(new DanaRS_Packet_History_Blood_Glucose());
put(new DanaRS_Packet_History_Bolus());
put(new DanaRS_Packet_Review_Bolus_Avg());
put(new DanaRS_Packet_History_Carbohydrate());
put(new DanaRS_Packet_History_Daily());
put(new DanaRS_Packet_General_Get_More_Information());
put(new DanaRS_Packet_General_Get_Pump_Check());
put(new DanaRS_Packet_General_Get_Shipping_Information());
put(new DanaRS_Packet_General_Get_Today_Delivery_Total());
put(new DanaRS_Packet_General_Get_User_Time_Change_Flag());
put(new DanaRS_Packet_History_Prime());
put(new DanaRS_Packet_History_Refill());
put(new DanaRS_Packet_General_Set_History_Upload_Mode());
put(new DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear());
put(new DanaRS_Packet_History_Suspend());
put(new DanaRS_Packet_History_Temporary());
// APS
put(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal());
put(new DanaRS_Packet_APS_History_Events());
put(new DanaRS_Packet_APS_Set_Event_History());
Config.logDanaMessageDetail = savedState;
}
}
public static void put(DanaRS_Packet message) {
int command = message.getCommand();
messages.put(command, message);
}
public static DanaRS_Packet findMessage(Integer command) {
if (messages.containsKey(command)) {
return messages.get(command);
} else {
return new DanaRS_Packet();
}
}
}

View file

@ -0,0 +1,207 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import android.annotation.TargetApi;
import android.os.Build;
import com.cozmo.danar.util.BleCommandUtil;
import java.nio.charset.StandardCharsets;
import java.util.Date;
public class DanaRS_Packet {
protected static final int TYPE_START = 0;
protected static final int OPCODE_START = 1;
protected static final int DATA_START = 2;
private boolean received;
protected boolean failed;
protected int type = BleCommandUtil.DANAR_PACKET__TYPE_RESPONSE; // most of the messages, should be changed for others
protected int opCode;
public DanaRS_Packet() {
received = false;
failed = false;
}
public void setReceived() {
received = true;
}
public boolean isReceived() {
return received;
}
public int getType() {
return type;
}
public int getOpCode() {
return opCode;
}
public int getCommand() {
return ((type & 0xFF) << 8) + (opCode & 0xFF);
}
public byte[] getRequestParams() {
return null;
}
;
// STATIC FUNCTIONS
public static int getCommand(byte[] data) {
int type = byteArrayToInt(getBytes(data, TYPE_START, 1));
int opCode = byteArrayToInt(getBytes(data, OPCODE_START, 1));
return ((type & 0xFF) << 8) + (opCode & 0xFF);
}
public void handleMessage(byte[] data) {
}
public String getFriendlyName() {
return "UNKNOWN_PACKET";
}
protected static byte[] getBytes(byte[] data, int srcStart, int srcLength) {
try {
byte[] ret = new byte[srcLength];
System.arraycopy(data, srcStart, ret, 0, srcLength);
return ret;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected static int byteArrayToInt(byte[] b) {
int ret;
switch (b.length) {
case 1:
ret = b[0] & 0x000000FF;
break;
case 2:
ret = ((b[1] & 0x000000FF) << 8) + (b[0] & 0x000000FF);
break;
case 3:
ret = ((b[2] & 0x000000FF) << 16) + ((b[1] & 0x000000FF) << 8) + (b[0] & 0x000000FF);
break;
case 4:
ret = ((b[3] & 0x000000FF) << 24) + ((b[2] & 0x000000FF) << 16) + ((b[1] & 0x000000FF) << 8) + (b[0] & 0x000000FF);
break;
default:
ret = -1;
break;
}
return ret;
}
public static Date dateTimeSecFromBuff(byte[] buff, int offset) {
Date date =
new Date(
100 + intFromBuff(buff, offset, 1),
intFromBuff(buff, offset + 1, 1) - 1,
intFromBuff(buff, offset + 2, 1),
intFromBuff(buff, offset + 3, 1),
intFromBuff(buff, offset + 4, 1),
intFromBuff(buff, offset + 5, 1)
);
return date;
}
protected static int intFromBuff(byte[] b, int srcStart, int srcLength) {
int ret;
switch (srcLength) {
case 1:
ret = b[DATA_START + srcStart + 0] & 0x000000FF;
break;
case 2:
ret = ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 0] & 0x000000FF);
break;
case 3:
ret = ((b[DATA_START + srcStart + 2] & 0x000000FF) << 16) + ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 0] & 0x000000FF);
break;
case 4:
ret = ((b[DATA_START + srcStart + 3] & 0x000000FF) << 24) + ((b[DATA_START + srcStart + 2] & 0x000000FF) << 16) + ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 0] & 0x000000FF);
break;
default:
ret = -1;
break;
}
return ret;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String stringFromBuff(byte[] buff, int offset, int length) {
byte[] strbuff = new byte[length];
System.arraycopy(buff, offset, strbuff, 0, length);
return new String(strbuff, StandardCharsets.UTF_8);
}
public static Date dateFromBuff(byte[] buff, int offset) {
Date date =
new Date(
100 + byteArrayToInt(getBytes(buff, offset, 1)),
byteArrayToInt(getBytes(buff, offset + 1, 1)) - 1,
byteArrayToInt(getBytes(buff, offset + 2, 1))
);
return date;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String asciiStringFromBuff(byte[] buff, int offset, int length) {
byte[] strbuff = new byte[length];
System.arraycopy(buff, offset, strbuff, 0, length);
for (int pos = 0; pos < length; pos++)
strbuff[pos] += 65; // "A"
return new String(strbuff, StandardCharsets.UTF_8);
}
public static String toHexString(byte[] buff) {
if (buff == null)
return "";
StringBuffer sb = new StringBuffer();
int count = 0;
for (byte element : buff) {
sb.append(String.format("%02X ", element));
if (++count % 4 == 0) sb.append(" ");
}
return sb.toString();
}
final private static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hexToBytes(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static int ByteToInt(byte b) {
return b & 0x000000FF;
}
}

View file

@ -0,0 +1,67 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
public class DanaRS_Packet_APS_Basal_Set_Temporary_Basal extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.class);
private int temporaryBasalRatio;
private int temporaryBasalDuration;
public int error;
public DanaRS_Packet_APS_Basal_Set_Temporary_Basal() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__APS_SET_TEMPORARY_BASAL;
}
public DanaRS_Packet_APS_Basal_Set_Temporary_Basal(int percent) {
this();
//HARDCODED LIMITS
if (percent < 0) percent = 0;
if (percent > 500) percent = 500;
temporaryBasalRatio = percent;
if (percent < 100) {
temporaryBasalDuration = 160;
if (Config.logDanaMessageDetail)
log.debug("APS Temp basal start percent: " + percent + " duration 30 min");
} else {
temporaryBasalDuration = 150;
if (Config.logDanaMessageDetail)
log.debug("APS Temp basal start percent: " + percent + " duration 15 min");
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[3];
request[0] = (byte) (temporaryBasalRatio & 0xff);
request[1] = (byte) ((temporaryBasalRatio >>> 8) & 0xff);
request[2] = (byte) (temporaryBasalDuration & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int result = byteArrayToInt(getBytes(data, DATA_START, 1));
if (result != 1) {
failed = true;
log.debug("Set APS temp basal start result: " + result + " FAILED!!!");
} else {
if (Config.logDanaMessageDetail)
log.debug("Set APS temp basal start result: " + result);
}
}
@Override
public String getFriendlyName() {
return "BASAL__APS_SET_TEMPORARY_BASAL";
}
}

View file

@ -0,0 +1,190 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.ConfigBuilder.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.utils.DateUtil;
public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_APS_History_Events.class);
private int year = 0;
private int month = 0;
private int day = 0;
private int hour = 0;
private int min = 0;
private int sec = 0;
public boolean done;
public int totalCount;
public static long lastEventTimeLoaded = 0;
public DanaRS_Packet_APS_History_Events() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS;
done = false;
totalCount = 0;
}
public DanaRS_Packet_APS_History_Events(long from) {
this();
GregorianCalendar cal = new GregorianCalendar();
if (from != 0)
cal.setTimeInMillis(from);
else
cal.set(2000, 0, 1, 0, 0, 0);
year = cal.get(Calendar.YEAR) - 1900 - 100;
month = cal.get(Calendar.MONTH) + 1;
day = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
log.debug("Loading event history from: " + new Date(cal.getTimeInMillis()).toLocaleString());
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[6];
request[0] = (byte) (year & 0xff);
request[1] = (byte) (month & 0xff);
request[2] = (byte) (day & 0xff);
request[3] = (byte) (hour & 0xff);
request[4] = (byte) (min & 0xff);
request[5] = (byte) (sec & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
byte recordCode = (byte) intFromBuff(data, 0, 1);
// Last record
if (recordCode == (byte) 0xFF) {
done = true;
return;
}
Date datetime = dateTimeSecFromBuff(data, 1); // 6 bytes
int param1 = ((intFromBuff(data, 7, 1) << 8) & 0xFF) + (intFromBuff(data, 8, 1) & 0xFF);
int param2 = ((intFromBuff(data, 9, 1) << 8) & 0xFF) + (intFromBuff(data, 10, 1) & 0xFF);
TemporaryBasal temporaryBasal = new TemporaryBasal();
temporaryBasal.date = datetime.getTime();
temporaryBasal.source = Source.PUMP;
temporaryBasal.pumpId = datetime.getTime();
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.date = datetime.getTime();
extendedBolus.source = Source.PUMP;
extendedBolus.pumpId = datetime.getTime();
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime.getTime());
if (detailedBolusInfo == null) {
log.debug("DetailedBolusInfo not found for " + datetime.toLocaleString());
detailedBolusInfo = new DetailedBolusInfo();
}
detailedBolusInfo.date = datetime.getTime();
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime.getTime();
switch (recordCode) {
case DanaRPump.TEMPSTART:
log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min");
temporaryBasal.percentRate = param1;
temporaryBasal.durationInMinutes = param2;
MainApp.getConfigBuilder().addToHistoryTempBasal(temporaryBasal);
break;
case DanaRPump.TEMPSTOP:
log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString());
MainApp.getConfigBuilder().addToHistoryTempBasal(temporaryBasal);
break;
case DanaRPump.EXTENDEDSTART:
log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
extendedBolus.insulin = param1 / 100d;
extendedBolus.durationInMinutes = param2;
MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus);
break;
case DanaRPump.EXTENDEDSTOP:
log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min");
MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus);
break;
case DanaRPump.BOLUS:
detailedBolusInfo.insulin = param1 / 100d;
boolean newRecord = MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
DetailedBolusInfoStorage.remove(detailedBolusInfo.date);
break;
case DanaRPump.DUALBOLUS:
detailedBolusInfo.insulin = param1 / 100d;
newRecord = MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
DetailedBolusInfoStorage.remove(detailedBolusInfo.date);
break;
case DanaRPump.DUALEXTENDEDSTART:
log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
extendedBolus.insulin = param1 / 100d;
extendedBolus.durationInMinutes = param2;
MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus);
break;
case DanaRPump.DUALEXTENDEDSTOP:
log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min");
MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus);
break;
case DanaRPump.SUSPENDON:
log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString());
break;
case DanaRPump.SUSPENDOFF:
log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString());
break;
case DanaRPump.REFILL:
log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U");
break;
case DanaRPump.PRIME:
log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U");
break;
case DanaRPump.PROFILECHANGE:
log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h");
break;
case DanaRPump.CARBS:
DetailedBolusInfo emptyCarbsInfo = new DetailedBolusInfo();
emptyCarbsInfo.carbs = param1;
emptyCarbsInfo.date = datetime.getTime();
emptyCarbsInfo.source = Source.PUMP;
emptyCarbsInfo.pumpId = datetime.getTime();
newRecord = MainApp.getConfigBuilder().addToHistoryTreatment(emptyCarbsInfo);
log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g");
break;
case DanaRPump.PRIMECANNULA:
log.debug("EVENT PRIME CANNULA(" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U");
break;
default:
log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2);
break;
}
if (datetime.getTime() > lastEventTimeLoaded)
lastEventTimeLoaded = datetime.getTime();
}
@Override
public String getFriendlyName() {
return "APS_HISTORY_EVENTS";
}
}

View file

@ -0,0 +1,77 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.GregorianCalendar;
import info.nightscout.androidaps.Config;
public class DanaRS_Packet_APS_Set_Event_History extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_APS_Set_Event_History.class);
private int type;
private long time;
public int param1;
public int param2;
public DanaRS_Packet_APS_Set_Event_History() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY;
}
public DanaRS_Packet_APS_Set_Event_History(int type, long time, int param1, int param2) {
this();
this.type = type;
this.time = time;
this.param1 = param1;
this.param2 = param2;
}
@Override
public byte[] getRequestParams() {
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(time);
int year = cal.get(Calendar.YEAR) - 1900 - 100;
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
byte[] request = new byte[11];
request[0] = (byte) (type & 0xff);
request[1] = (byte) (year & 0xff);
request[2] = (byte) (month & 0xff);
request[3] = (byte) (day & 0xff);
request[4] = (byte) (hour & 0xff);
request[5] = (byte) (min & 0xff);
request[6] = (byte) (sec & 0xff);
request[7] = (byte) ((param1 >>> 8) & 0xff);
request[8] = (byte) (param1 & 0xff);
request[9] = (byte) ((param2 >>> 8) & 0xff);
request[10] = (byte) (param2 & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int result = intFromBuff(data, 0, 1);
if (result != 1) {
failed = true;
log.debug("Set history entry result: " + result + " FAILED!!!");
} else {
if (Config.logDanaMessageDetail)
log.debug("Set history entry result: " + result);
}
}
@Override
public String getFriendlyName() {
return "APS_SET_EVENT_HISTORY";
}
}

View file

@ -0,0 +1,68 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Get_Basal_Rate extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.class);
public DanaRS_Packet_Basal_Get_Basal_Rate() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_BASAL_RATE;
if (Config.logDanaMessageDetail) {
log.debug("Requesting basal rates");
}
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 2;
pump.maxBasal = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
pump.basalStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (pump.pumpProfiles == null) pump.pumpProfiles = new double[4][];
pump.pumpProfiles[pump.activeProfile] = new double[24];
for (int i = 0, size = 24; i < size; i++) {
dataIndex += dataSize;
dataSize = 2;
pump.pumpProfiles[pump.activeProfile][i] = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
}
if (Config.logDanaMessageDetail) {
log.debug("Max basal: " + pump.maxBasal + " U");
log.debug("Basal step: " + pump.basalStep + " U");
for (int index = 0; index < 24; index++)
log.debug("Basal " + String.format("%02d", index) + "h: " + pump.pumpProfiles[pump.activeProfile][index]);
}
if (pump.basalStep != 0.01d) {
Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.sResources.getString(R.string.danar_setbasalstep001), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP));
}
}
@Override
public String getFriendlyName() {
return "BASAL__GET_BASAL_RATE";
}
}

View file

@ -0,0 +1,61 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Basal_Get_Profile_Basal_Rate extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Get_Profile_Basal_Rate.class);
private int profileNumber;
public DanaRS_Packet_Basal_Get_Profile_Basal_Rate() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_BASAL_RATE;
}
// 0 - 4
public DanaRS_Packet_Basal_Get_Profile_Basal_Rate(int profileNumber) {
this();
this.profileNumber = profileNumber;
if (Config.logDanaMessageDetail) {
log.debug("Requesting basal rates for profile " + profileNumber);
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[1];
request[0] = (byte) (profileNumber & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 2;
if (pump.pumpProfiles == null) pump.pumpProfiles = new double[4][];
pump.pumpProfiles[profileNumber] = new double[24];
for (int i = 0, size = 24; i < size; i++) {
pump.pumpProfiles[profileNumber][i] = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
}
if (Config.logDanaMessageDetail) {
for (int index = 0; index < 24; index++)
log.debug("Basal " + String.format("%02d", index) + "h: " + pump.pumpProfiles[profileNumber][index]);
}
}
@Override
public String getFriendlyName() {
return "BASAL__GET_PROFILE_BASAL_RATE";
}
}

View file

@ -0,0 +1,37 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Basal_Get_Profile_Number extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Get_Profile_Number.class);
public DanaRS_Packet_Basal_Get_Profile_Number() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER;
if (Config.logDanaMessageDetail) {
log.debug("Requesting active profile");
}
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
pump.activeProfile = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Active profile: " + pump.activeProfile);
}
}
@Override
public String getFriendlyName() {
return "BASAL__GET_PROFILE_NUMBER";
}
}

View file

@ -0,0 +1,77 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import android.support.annotation.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Get_Temporary_Basal_State.class);
public DanaRS_Packet_Basal_Get_Temporary_Basal_State() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE;
if (Config.logDanaMessageDetail) {
log.debug("Requesting temporary basal status");
}
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.isTempBasalInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01;
boolean isAPSTempBasalInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x02;
dataIndex += dataSize;
dataSize = 1;
pump.tempBasalPercent = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (pump.tempBasalPercent > 200) pump.tempBasalPercent = (pump.tempBasalPercent - 200) * 10;
dataIndex += dataSize;
dataSize = 1;
int durationHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (durationHour == 150) pump.tempBasalTotalSec = 15 * 60;
else if (durationHour == 160) pump.tempBasalTotalSec = 30 * 60;
else pump.tempBasalTotalSec = durationHour * 60 * 60;
dataIndex += dataSize;
dataSize = 2;
int runningMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
int tempBasalRemainingMin = (pump.tempBasalTotalSec - runningMin * 60) / 60;
Date tempBasalStart = pump.isTempBasalInProgress ? getDateFromTempBasalSecAgo(runningMin * 60) : new Date(0);
if (Config.logDanaMessageDetail) {
log.debug("Error code: " + error);
log.debug("Is temp basal running: " + pump.isTempBasalInProgress);
log.debug("Is APS temp basal running: " + isAPSTempBasalInProgress);
log.debug("Current temp basal percent: " + pump.tempBasalPercent);
log.debug("Current temp basal remaining min: " + tempBasalRemainingMin);
log.debug("Current temp basal total sec: " + pump.tempBasalTotalSec);
log.debug("Current temp basal start: " + tempBasalStart);
}
}
@Override
public String getFriendlyName() {
return "BASAL__TEMPORARY_BASAL_STATE";
}
@NonNull
private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000);
}
}

View file

@ -0,0 +1,53 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Basal_Rate extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Basal_Rate.class);
private double[] profileBasalRate;
public int error;
public DanaRS_Packet_Basal_Set_Basal_Rate() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_BASAL_RATE;
}
public DanaRS_Packet_Basal_Set_Basal_Rate(double[] profileBasalRate) {
this();
this.profileBasalRate = profileBasalRate;
if (Config.logDanaMessageDetail) {
log.debug("Setting new basal rates");
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[48];
for (int i = 0, size = 24; i < size; i++) {
int rate = (int) (profileBasalRate[i] * 100d);
request[0 + (i * 2)] = (byte) (rate & 0xff);
request[1 + (i * 2)] = (byte) ((rate >>> 8) & 0xff);
}
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__SET_BASAL_RATE";
}
}

View file

@ -0,0 +1,36 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.class);
public int error;
public DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL;
if (Config.logDanaMessageDetail) {
log.debug("Canceling temp basal");
}
}
@Override
public void handleMessage(byte[] data) {
error = byteArrayToInt(getBytes(data, DATA_START, 1));
if (Config.logDanaMessageDetail) {
log.debug("Result " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__CANCEL_TEMPORARY_BASAL";
}
}

View file

@ -0,0 +1,56 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Profile_Basal_Rate extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Profile_Basal_Rate.class);
private int profileNumber; // 0 - 4
private double[] profileBasalRate;
public int error;
public DanaRS_Packet_Basal_Set_Profile_Basal_Rate() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_BASAL_RATE;
}
public DanaRS_Packet_Basal_Set_Profile_Basal_Rate(int profileNumber, double[] profileBasalRate) {
this();
this.profileNumber = profileNumber;
this.profileBasalRate = profileBasalRate;
if (Config.logDanaMessageDetail) {
log.debug("Setting new basal rates for profile " + profileNumber);
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[49];
request[0] = (byte) (profileNumber & 0xff);
for (int i = 0, size = 24; i < size; i++) {
int rate = (int) (profileBasalRate[i] * 100d);
request[1 + (i * 2)] = (byte) (rate & 0xff);
request[2 + (i * 2)] = (byte) ((rate >>> 8) & 0xff);
}
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__SET_PROFILE_BASAL_RATE";
}
}

View file

@ -0,0 +1,48 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Profile_Number extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Profile_Number.class);
private int profileNumber;
public int error;
public DanaRS_Packet_Basal_Set_Profile_Number() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_NUMBER;
}
public DanaRS_Packet_Basal_Set_Profile_Number(int profileNumber) {
this();
this.profileNumber = profileNumber;
if (Config.logDanaMessageDetail) {
log.debug("Setting profile number " + profileNumber);
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[1];
request[0] = (byte) (profileNumber & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__SET_PROFILE_NUMBER";
}
}

View file

@ -0,0 +1,35 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Suspend_Off extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Suspend_Off.class);
public int error;
public DanaRS_Packet_Basal_Set_Suspend_Off() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF;
if (Config.logDanaMessageDetail) {
log.debug("Turning off suspend");
}
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__SET_SUSPEND_OFF";
}
}

View file

@ -0,0 +1,35 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Suspend_On extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Suspend_On.class);
public int error;
public DanaRS_Packet_Basal_Set_Suspend_On() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_ON;
if (Config.logDanaMessageDetail) {
log.debug("Turning on suspend");
}
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__SET_SUSPEND_ON";
}
}

View file

@ -0,0 +1,52 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Basal_Set_Temporary_Basal extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Temporary_Basal.class);
private int temporaryBasalRatio;
private int temporaryBasalDuration;
public int error;
public DanaRS_Packet_Basal_Set_Temporary_Basal() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_TEMPORARY_BASAL;
}
public DanaRS_Packet_Basal_Set_Temporary_Basal(int temporaryBasalRatio, int temporaryBasalDuration) {
this();
this.temporaryBasalRatio = temporaryBasalRatio;
this.temporaryBasalDuration = temporaryBasalDuration;
if (Config.logDanaMessageDetail) {
log.debug("Setting temporary basal of " + temporaryBasalRatio + "% for " + temporaryBasalDuration + " hours");
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[2];
request[0] = (byte) (temporaryBasalRatio & 0xff);
request[1] = (byte) (temporaryBasalDuration & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "BASAL__SET_TEMPORARY_BASAL";
}
}

View file

@ -0,0 +1,137 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Bolus_Option extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Bolus_Option.class);
public DanaRS_Packet_Bolus_Get_Bolus_Option() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_OPTION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
pump.isExtendedBolusEnabled = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 1;
dataIndex += dataSize;
dataSize = 1;
pump.bolusCalculationOption = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.missedBolusConfig = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus01StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus01StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus01EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus01EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus02StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus02StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus02EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus02EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus03StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus03StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus03EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus03EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus04StartHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus04StartMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus04EndHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int missedBolus04EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (!pump.isExtendedBolusEnabled) {
Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.sResources.getString(R.string.danar_enableextendedbolus), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
}
if (Config.logDanaMessageDetail) {
log.debug("Extended bolus enabled: " + pump.isExtendedBolusEnabled);
log.debug("Missed bolus config: " + pump.missedBolusConfig);
log.debug("missedBolus01StartHour: " + missedBolus01StartHour);
log.debug("missedBolus01StartMin: " + missedBolus01StartMin);
log.debug("missedBolus01EndHour: " + missedBolus01EndHour);
log.debug("missedBolus01EndMin: " + missedBolus01EndMin);
log.debug("missedBolus02StartHour: " + missedBolus02StartHour);
log.debug("missedBolus02StartMin: " + missedBolus02StartMin);
log.debug("missedBolus02EndHour: " + missedBolus02EndHour);
log.debug("missedBolus02EndMin: " + missedBolus02EndMin);
log.debug("missedBolus03StartHour: " + missedBolus03StartHour);
log.debug("missedBolus03StartMin: " + missedBolus03StartMin);
log.debug("missedBolus03EndHour: " + missedBolus03EndHour);
log.debug("missedBolus03EndMin: " + missedBolus03EndMin);
log.debug("missedBolus04StartHour: " + missedBolus04StartHour);
log.debug("missedBolus04StartMin: " + missedBolus04StartMin);
log.debug("missedBolus04EndHour: " + missedBolus04EndHour);
log.debug("missedBolus04EndMin: " + missedBolus04EndMin);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_BOLUS_OPTION";
}
}

View file

@ -0,0 +1,145 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_CIR_CF_Array extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_CIR_CF_Array.class);
public DanaRS_Packet_Bolus_Get_CIR_CF_Array() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int language = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.morningCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
int cir02 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.afternoonCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
int cir04 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.eveningCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
int cir06 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.nightCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize));
double cf02, cf04, cf06;
if (pump.units == DanaRPump.UNITS_MGDL) {
dataIndex += dataSize;
dataSize = 2;
pump.morningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
cf02 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.afternoonCF = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
cf04 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.eveningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
cf06 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize));
} else {
dataIndex += dataSize;
dataSize = 2;
pump.morningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
cf02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.afternoonCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
cf04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.eveningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
cf06 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
}
if (Config.logDanaMessageDetail) {
log.debug("Language: " + language);
log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
log.debug("Current pump morning CIR: " + pump.morningCIR);
log.debug("Current pump morning CF: " + pump.morningCF);
log.debug("Current pump afternoon CIR: " + pump.afternoonCIR);
log.debug("Current pump afternoon CF: " + pump.afternoonCF);
log.debug("Current pump evening CIR: " + pump.eveningCIR);
log.debug("Current pump evening CF: " + pump.eveningCF);
log.debug("Current pump night CIR: " + pump.nightCIR);
log.debug("Current pump night CF: " + pump.nightCF);
log.debug("cir02: " + cir02);
log.debug("cir04: " + cir04);
log.debug("cir06: " + cir06);
log.debug("cf02: " + cf02);
log.debug("cf04: " + cf04);
log.debug("cf06: " + cf06);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_CIR_CF_ARRAY";
}
}

View file

@ -0,0 +1,77 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Calculation_Information extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Calculation_Information.class);
public DanaRS_Packet_Bolus_Get_Calculation_Information() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_CALCULATION_INFORMATION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
double currentBG = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
int carbohydrate = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.currentTarget = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.currentCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.currentCF = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
pump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (pump.units == DanaRPump.UNITS_MMOL) {
pump.currentCF = pump.currentCF / 100d;
pump.currentTarget = pump.currentTarget / 100d;
currentBG = currentBG / 100d;
}
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
log.debug("Current BG: " + currentBG);
log.debug("Carbs: " + carbohydrate);
log.debug("Current target: " + pump.currentTarget);
log.debug("Current CIR: " + pump.currentCIR);
log.debug("Current CF: " + pump.currentCF);
log.debug("Pump IOB: " + pump.iob);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_CALCULATION_INFORMATION";
}
}

View file

@ -0,0 +1,47 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.class);
public DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
int carbs = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.currentCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
log.debug("Carbs: " + carbs);
log.debug("Current CIR: " + pump.currentCIR);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION";
}
}

View file

@ -0,0 +1,55 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Dual_Bolus extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Dual_Bolus.class);
public DanaRS_Packet_Bolus_Get_Dual_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
double bolusIncrement = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
log.debug("Bolus step: " + pump.bolusStep + " U");
log.debug("Extended bolus running: " + pump.extendedBolusAbsoluteRate + " U/h");
log.debug("Max bolus: " + pump.maxBolus + " U");
log.debug("bolusIncrement: " + bolusIncrement + " U");
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_DUAL_BOLUS";
}
}

View file

@ -0,0 +1,52 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Extended_Bolus extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Extended_Bolus.class);
public DanaRS_Packet_Bolus_Get_Extended_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
log.debug("Extended bolus running: " + pump.extendedBolusAbsoluteRate + " U/h");
log.debug("Max bolus: " + pump.maxBolus + " U");
log.debug("Bolus step: " + pump.bolusStep + " U");
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_EXTENDED_BOLUS";
}
}

View file

@ -0,0 +1,62 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Extended_Bolus_State extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Extended_Bolus_State.class);
public DanaRS_Packet_Bolus_Get_Extended_Bolus_State() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01;
dataIndex += dataSize;
dataSize = 1;
pump.extendedBolusMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) * 30;
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusSoFarInMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusDeliveredSoFar = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
log.debug("Is extended bolus running: " + pump.isExtendedInProgress);
log.debug("Extended bolus running: " + pump.extendedBolusAbsoluteRate + " U/h");
log.debug("Extended bolus duration: " + pump.extendedBolusMinutes + " min");
log.debug("Extended bolus so far: " + pump.extendedBolusSoFarInMinutes + " min");
log.debug("Extended bolus delivered so far: " + pump.extendedBolusDeliveredSoFar + " U");
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_EXTENDED_BOLUS_STATE";
}
}

View file

@ -0,0 +1,42 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.class);
public DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_MENU_OPTION_STATE;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int extendedMenuOption = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01;
if (Config.logDanaMessageDetail) {
log.debug("extendedMenuOption: " + extendedMenuOption);
log.debug("Is extended bolus running: " + pump.isExtendedInProgress);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_EXTENDED_MENU_OPTION_STATE";
}
}

View file

@ -0,0 +1,46 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Get_Initial_Bolus extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Initial_Bolus.class);
public DanaRS_Packet_Bolus_Get_Initial_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_RATE;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 2;
double initialBolusValue01 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double initialBolusValue02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double initialBolusValue03 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double initialBolusValue04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Initial bolus amount 01: " + initialBolusValue01);
log.debug("Initial bolus amount 02: " + initialBolusValue02);
log.debug("Initial bolus amount 03: " + initialBolusValue03);
log.debug("Initial bolus amount 04: " + initialBolusValue04);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_BOLUS_RATE";
}
}

View file

@ -0,0 +1,72 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Step_Bolus_Information.class);
public DanaRS_Packet_Bolus_Get_Step_Bolus_Information() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int bolusType = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.initialBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
Date lastBolusTime = new Date(); // it doesn't provide day only hour+min, workaround: expecting today
dataIndex += dataSize;
dataSize = 1;
lastBolusTime.setHours(byteArrayToInt(getBytes(data, dataIndex, dataSize)));
dataIndex += dataSize;
dataSize = 1;
lastBolusTime.setMinutes(byteArrayToInt(getBytes(data, dataIndex, dataSize)));
dataIndex += dataSize;
dataSize = 2;
pump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
log.debug("BolusType: " + bolusType);
log.debug("Initial bolus amount: " + pump.initialBolusAmount + " U");
log.debug("Last bolus time: " + lastBolusTime.toLocaleString());
log.debug("Last bolus amount: " + pump.lastBolusAmount);
log.debug("Max bolus: " + pump.maxBolus + " U");
log.debug("Bolus step: " + pump.bolusStep + " U");
}
}
@Override
public String getFriendlyName() {
return "BOLUS__GET_STEP_BOLUS_INFORMATION";
}
}

View file

@ -0,0 +1,127 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Set_Bolus_Option extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Bolus_Option.class);
private int extendedBolusOptionOnOff;
private int bolusCalculationOption;
private int missedBolusConfig;
private int missedBolus01StartHour;
private int missedBolus01StartMin;
private int missedBolus01EndHour;
private int missedBolus01EndMin;
private int missedBolus02StartHour;
private int missedBolus02StartMin;
private int missedBolus02EndHour;
private int missedBolus02EndMin;
private int missedBolus03StartHour;
private int missedBolus03StartMin;
private int missedBolus03EndHour;
private int missedBolus03EndMin;
private int missedBolus04StartHour;
private int missedBolus04StartMin;
private int missedBolus04EndHour;
private int missedBolus04EndMin;
public DanaRS_Packet_Bolus_Set_Bolus_Option() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_OPTION;
}
public DanaRS_Packet_Bolus_Set_Bolus_Option(
int extendedBolusOptionOnOff,
int bolusCalculationOption,
int missedBolusConfig,
int missedBolus01StartHour,
int missedBolus01StartMin,
int missedBolus01EndHour,
int missedBolus01EndMin,
int missedBolus02StartHour,
int missedBolus02StartMin,
int missedBolus02EndHour,
int missedBolus02EndMin,
int missedBolus03StartHour,
int missedBolus03StartMin,
int missedBolus03EndHour,
int missedBolus03EndMin,
int missedBolus04StartHour,
int missedBolus04StartMin,
int missedBolus04EndHour,
int missedBolus04EndMin) {
this();
this.extendedBolusOptionOnOff = extendedBolusOptionOnOff;
this.bolusCalculationOption = bolusCalculationOption;
this.missedBolusConfig = missedBolusConfig;
this.missedBolus01StartHour = missedBolus01StartHour;
this.missedBolus01StartMin = missedBolus01StartMin;
this.missedBolus01EndHour = missedBolus01EndHour;
this.missedBolus01EndMin = missedBolus01EndMin;
this.missedBolus02StartHour = missedBolus02StartHour;
this.missedBolus02StartMin = missedBolus02StartMin;
this.missedBolus02EndHour = missedBolus02EndHour;
this.missedBolus02EndMin = missedBolus02EndMin;
this.missedBolus03StartHour = missedBolus03StartHour;
this.missedBolus03StartMin = missedBolus03StartMin;
this.missedBolus03EndHour = missedBolus03EndHour;
this.missedBolus03EndMin = missedBolus03EndMin;
this.missedBolus04StartHour = missedBolus04StartHour;
this.missedBolus04StartMin = missedBolus04StartMin;
this.missedBolus04EndHour = missedBolus04EndHour;
this.missedBolus04EndMin = missedBolus04EndMin;
if (Config.logDanaMessageDetail) {
log.debug("Setting bolus options");
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[19];
request[0] = (byte) (extendedBolusOptionOnOff & 0xff);
request[1] = (byte) (bolusCalculationOption & 0xff);
request[2] = (byte) (missedBolusConfig & 0xff);
request[3] = (byte) (missedBolus01StartHour & 0xff);
request[4] = (byte) (missedBolus01StartMin & 0xff);
request[5] = (byte) (missedBolus01EndHour & 0xff);
request[6] = (byte) (missedBolus01EndMin & 0xff);
request[7] = (byte) (missedBolus02StartHour & 0xff);
request[8] = (byte) (missedBolus02StartMin & 0xff);
request[9] = (byte) (missedBolus02EndHour & 0xff);
request[10] = (byte) (missedBolus02EndMin & 0xff);
request[11] = (byte) (missedBolus03StartHour & 0xff);
request[12] = (byte) (missedBolus03StartMin & 0xff);
request[13] = (byte) (missedBolus03EndHour & 0xff);
request[14] = (byte) (missedBolus03EndMin & 0xff);
request[15] = (byte) (missedBolus04StartHour & 0xff);
request[16] = (byte) (missedBolus04StartMin & 0xff);
request[17] = (byte) (missedBolus04EndHour & 0xff);
request[18] = (byte) (missedBolus04EndMin & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_BOLUS_OPTION";
}
}

View file

@ -0,0 +1,100 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Set_CIR_CF_Array extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_CIR_CF_Array.class);
private int cir01;
private int cir02;
private int cir03;
private int cir04;
private int cir05;
private int cir06;
private int cir07;
private int cf01;
private int cf02;
private int cf03;
private int cf04;
private int cf05;
private int cf06;
private int cf07;
public DanaRS_Packet_Bolus_Set_CIR_CF_Array() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_CIR_CF_ARRAY;
}
public DanaRS_Packet_Bolus_Set_CIR_CF_Array(int cir01, int cir02, int cir03, int cir04, int cir05, int cir06, int cir07, int cf01, int cf02, int cf03, int cf04, int cf05, int cf06, int cf07) {
this();
this.cir01 = cir01;
this.cir02 = cir02;
this.cir03 = cir03;
this.cir04 = cir04;
this.cir05 = cir05;
this.cir06 = cir06;
this.cir07 = cir07;
this.cf01 = cf01;
this.cf02 = cf02;
this.cf03 = cf03;
this.cf04 = cf04;
this.cf05 = cf05;
this.cf06 = cf06;
this.cf07 = cf07;
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[28];
request[0] = (byte) (cir01 & 0xff);
request[1] = (byte) ((cir01 >>> 8) & 0xff);
request[2] = (byte) (cir02 & 0xff);
request[3] = (byte) ((cir02 >>> 8) & 0xff);
request[4] = (byte) (cir03 & 0xff);
request[5] = (byte) ((cir03 >>> 8) & 0xff);
request[6] = (byte) (cir04 & 0xff);
request[7] = (byte) ((cir04 >>> 8) & 0xff);
request[8] = (byte) (cir05 & 0xff);
request[9] = (byte) ((cir05 >>> 8) & 0xff);
request[10] = (byte) (cir06 & 0xff);
request[11] = (byte) ((cir06 >>> 8) & 0xff);
request[12] = (byte) (cir07 & 0xff);
request[13] = (byte) ((cir07 >>> 8) & 0xff);
request[14] = (byte) (cf01 & 0xff);
request[15] = (byte) ((cf01 >>> 8) & 0xff);
request[16] = (byte) (cf02 & 0xff);
request[17] = (byte) ((cf02 >>> 8) & 0xff);
request[18] = (byte) (cf03 & 0xff);
request[19] = (byte) ((cf03 >>> 8) & 0xff);
request[20] = (byte) (cf04 & 0xff);
request[21] = (byte) ((cf04 >>> 8) & 0xff);
request[22] = (byte) (cf05 & 0xff);
request[23] = (byte) ((cf05 >>> 8) & 0xff);
request[24] = (byte) (cf06 & 0xff);
request[25] = (byte) ((cf06 >>> 8) & 0xff);
request[26] = (byte) (cf07 & 0xff);
request[27] = (byte) ((cf07 >>> 8) & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_CIR_CF_ARRAY";
}
}

View file

@ -0,0 +1,60 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Set_Dual_Bolus extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Dual_Bolus.class);
private double amount;
private double extendedAmount;
private int extendedBolusDurationInHalfHours;
public DanaRS_Packet_Bolus_Set_Dual_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_DUAL_BOLUS;
}
public DanaRS_Packet_Bolus_Set_Dual_Bolus(double amount, double extendedAmount, int extendedBolusDurationInHalfHours) {
this();
this.amount = amount;
this.extendedAmount = extendedAmount;
this.extendedBolusDurationInHalfHours = extendedBolusDurationInHalfHours;
if (Config.logDanaMessageDetail)
log.debug("Dual bolus start : " + amount + " U extended: " + extendedAmount + " U halfhours: " + extendedBolusDurationInHalfHours);
}
@Override
public byte[] getRequestParams() {
int stepBolusRate = (int) (amount / 100d);
int extendedBolusRate = (int) (extendedAmount / 100d);
byte[] request = new byte[5];
request[0] = (byte) (stepBolusRate & 0xff);
request[1] = (byte) ((stepBolusRate >>> 8) & 0xff);
request[2] = (byte) (extendedBolusRate & 0xff);
request[3] = (byte) ((extendedBolusRate >>> 8) & 0xff);
request[4] = (byte) (extendedBolusDurationInHalfHours & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_DUAL_BOLUS";
}
}

View file

@ -0,0 +1,56 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Set_Extended_Bolus extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Extended_Bolus.class);
private double extendedAmount;
private int extendedBolusDurationInHalfHours;
public DanaRS_Packet_Bolus_Set_Extended_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS;
}
public DanaRS_Packet_Bolus_Set_Extended_Bolus(double extendedAmount, int extendedBolusDurationInHalfHours) {
this();
this.extendedAmount = extendedAmount;
this.extendedBolusDurationInHalfHours = extendedBolusDurationInHalfHours;
if (Config.logDanaMessageDetail)
log.debug("Extended bolus start : " + extendedAmount + " U halfhours: " + extendedBolusDurationInHalfHours);
}
@Override
public byte[] getRequestParams() {
int extendedBolusRate = (int) (extendedAmount * 100d);
byte[] request = new byte[3];
request[0] = (byte) (extendedBolusRate & 0xff);
request[1] = (byte) ((extendedBolusRate >>> 8) & 0xff);
request[2] = (byte) (extendedBolusDurationInHalfHours & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_EXTENDED_BOLUS";
}
}

View file

@ -0,0 +1,35 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.class);
public DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL;
if (Config.logDanaMessageDetail)
log.debug("Cancel extended bolus");
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_EXTENDED_BOLUS_CANCEL";
}
}

View file

@ -0,0 +1,60 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Bolus_Set_Initial_Bolus extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Initial_Bolus.class);
private int bolusRate01;
private int bolusRate02;
private int bolusRate03;
private int bolusRate04;
public DanaRS_Packet_Bolus_Set_Initial_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_RATE;
}
public DanaRS_Packet_Bolus_Set_Initial_Bolus(double bolusRate01, double bolusRate02, double bolusRate03, double bolusRate04) {
this();
this.bolusRate01 = (int) (bolusRate01 / 100d);
this.bolusRate02 = (int) (bolusRate02 / 100d);
this.bolusRate03 = (int) (bolusRate03 / 100d);
this.bolusRate04 = (int) (bolusRate04 / 100d);
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[8];
request[0] = (byte) (bolusRate01 & 0xff);
request[1] = (byte) ((bolusRate01 >>> 8) & 0xff);
request[2] = (byte) (bolusRate02 & 0xff);
request[3] = (byte) ((bolusRate02 >>> 8) & 0xff);
request[4] = (byte) (bolusRate03 & 0xff);
request[5] = (byte) ((bolusRate03 >>> 8) & 0xff);
request[6] = (byte) (bolusRate04 & 0xff);
request[7] = (byte) ((bolusRate04 >>> 8) & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_BOLUS_RATE";
}
}

View file

@ -0,0 +1,66 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.utils.HardLimits;
public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Step_Bolus_Start.class);
private double amount;
private int speed;
public boolean failed;
public DanaRS_Packet_Bolus_Set_Step_Bolus_Start() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_START;
}
// Speed 0 => 12 sec/U, 1 => 30 sec/U, 2 => 60 sec/U
public DanaRS_Packet_Bolus_Set_Step_Bolus_Start(double amount, int speed) {
this();
// HARDCODED LIMIT
amount = MainApp.getConfigBuilder().applyBolusConstraints(amount);
if (amount < 0) amount = 0d;
if (amount > HardLimits.maxBolus()) amount = HardLimits.maxBolus();
this.amount = amount;
this.speed = speed;
if (Config.logDanaMessageDetail)
log.debug("Bolus start : " + amount + " speed: " + speed);
}
@Override
public byte[] getRequestParams() {
int stepBolusRate = (int) (amount * 100);
byte[] request = new byte[3];
request[0] = (byte) (stepBolusRate & 0xff);
request[1] = (byte) ((stepBolusRate >>> 8) & 0xff);
request[2] = (byte) (speed & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
failed = status != 0x00;
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_STEP_BOLUS_START";
}
}

View file

@ -0,0 +1,61 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
public class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.class);
private static Treatment t;
private static Double amount;
public static boolean stopped = false;
public static boolean forced = false;
public DanaRS_Packet_Bolus_Set_Step_Bolus_Stop() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_STOP;
}
public DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(Double amount, Treatment t) {
this();
this.t = t;
this.amount = amount;
forced = false;
stopped = false;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
stopped = true;
if (!forced) {
t.insulin = amount;
bolusingEvent.status = MainApp.sResources.getString(R.string.overview_bolusprogress_delivered);
bolusingEvent.percent = 100;
} else {
bolusingEvent.status = MainApp.sResources.getString(R.string.overview_bolusprogress_stoped);
}
MainApp.bus().post(bolusingEvent);
}
@Override
public String getFriendlyName() {
return "BOLUS__SET_STEP_BOLUS_STOP";
}
}

View file

@ -0,0 +1,32 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Etc_Keep_Connection extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Etc_Keep_Connection.class);
public DanaRS_Packet_Etc_Keep_Connection() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_ETC__KEEP_CONNECTION;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "ETC__KEEP_CONNECTION";
}
}

View file

@ -0,0 +1,71 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Etc_Set_History_Save extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Etc_Set_History_Save.class);
private int historyType;
private int historyYear;
private int historyMonth;
private int historyDate;
private int historyHour;
private int historyMinute;
private int historySecond;
private int historyCode;
private int historyValue;
public DanaRS_Packet_Etc_Set_History_Save() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_ETC__SET_HISTORY_SAVE;
}
public DanaRS_Packet_Etc_Set_History_Save(int historyType, int historyYear, int historyMonth, int historyDate, int historyHour, int historyMinute, int historySecond, int historyCode, int historyValue) {
this();
this.historyType = historyType;
this.historyYear = historyYear;
this.historyMonth = historyMonth;
this.historyDate = historyDate;
this.historyHour = historyHour;
this.historyMinute = historyMinute;
this.historySecond = historySecond;
this.historyCode = historyCode;
this.historyValue = historyValue;
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[10];
request[0] = (byte) (historyType & 0xff);
request[1] = (byte) (historyYear & 0xff);
request[2] = (byte) (historyMonth & 0xff);
request[3] = (byte) (historyDate & 0xff);
request[4] = (byte) (historyHour & 0xff);
request[5] = (byte) (historyMinute & 0xff);
request[6] = (byte) (historySecond & 0xff);
request[7] = (byte) (historyCode & 0xff);
request[8] = (byte) (historyValue & 0xff);
request[9] = (byte) ((historyValue >>> 8) & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "ETC__SET_HISTORY_SAVE";
}
}

View file

@ -0,0 +1,32 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_General_Delivery_Status extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Delivery_Status.class);
public DanaRS_Packet_General_Delivery_Status() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Status: " + status);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__DELIVERY_STATUS";
}
}

View file

@ -0,0 +1,70 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_General_Get_More_Information extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_More_Information.class);
public DanaRS_Packet_General_Get_More_Information() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 2;
pump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
pump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01;
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusRemainingMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
double remainRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
Date lastBolusTime = new Date(); // it doesn't provide day only hour+min, workaround: expecting today
dataIndex += dataSize;
dataSize = 1;
lastBolusTime.setHours(byteArrayToInt(getBytes(data, dataIndex, dataSize)));
dataIndex += dataSize;
dataSize = 1;
lastBolusTime.setMinutes(byteArrayToInt(getBytes(data, dataIndex, dataSize)));
dataIndex += dataSize;
dataSize = 2;
pump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Daily total units: " + pump.dailyTotalUnits + " U");
log.debug("Is extended in progress: " + pump.isExtendedInProgress);
log.debug("Extended bolus remaining minutes: " + pump.extendedBolusRemainingMinutes);
log.debug("Last bolus time: " + lastBolusTime.toLocaleString());
log.debug("Last bolus amount: " + pump.lastBolusAmount);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__GET_MORE_INFORMATION";
}
}

View file

@ -0,0 +1,36 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_General_Get_Password extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_Password.class);
public DanaRS_Packet_General_Get_Password() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_PASSWORD;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int pass = ((data[DATA_START + 1] & 0x000000FF) << 8) + (data[DATA_START + 0] & 0x000000FF);
pass = pass ^ 3463;
pump.rs_password = Integer.toHexString(pass);
if (Config.logDanaMessageDetail) {
log.debug("Pump password: " + pump.rs_password);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__GET_PASSWORD";
}
}

View file

@ -0,0 +1,51 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_General_Get_Pump_Check extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_Pump_Check.class);
public DanaRS_Packet_General_Get_Pump_Check() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_PUMP_CHECK;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
pump.model = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.protocol = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.productCode = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Model: " + String.format("%02X ", pump.model));
log.debug("Protocol: " + String.format("%02X ", pump.protocol));
log.debug("Product Code: " + String.format("%02X ", pump.productCode));
}
}
@Override
public String getFriendlyName() {
return "REVIEW__GET_PUMP_CHECK";
}
}

View file

@ -0,0 +1,46 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_General_Get_Shipping_Information extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.class);
public DanaRS_Packet_General_Get_Shipping_Information() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 10;
pump.serialNumber = stringFromBuff(data, dataIndex, dataSize);
dataIndex += dataSize;
dataSize = 3;
pump.shippingDate = dateFromBuff(data, dataIndex);
dataIndex += dataSize;
dataSize = 3;
pump.shippingCountry = asciiStringFromBuff(data, dataIndex, dataSize);
if (Config.logDanaMessageDetail) {
log.debug("Serial number: " + pump.serialNumber);
log.debug("Shipping date: " + pump.shippingDate);
log.debug("Shipping country: " + pump.shippingCountry);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__GET_SHIPPING_INFORMATION";
}
}

View file

@ -0,0 +1,47 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_General_Get_Today_Delivery_Total extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_Today_Delivery_Total.class);
public DanaRS_Packet_General_Get_Today_Delivery_Total() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 2;
pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Daily total: " + pump.dailyTotalUnits + " U");
log.debug("Daily total bolus: " + pump.dailyTotalBolusUnits + " U");
log.debug("Daily total basal: " + pump.dailyTotalBasalUnits + " U");
}
}
@Override
public String getFriendlyName() {
return "REVIEW__GET_TODAY_DELIVERY_TOTAL";
}
}

View file

@ -0,0 +1,32 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_General_Get_User_Time_Change_Flag extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_User_Time_Change_Flag.class);
public DanaRS_Packet_General_Get_User_Time_Change_Flag() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int userTimeChangeFlag = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("UserTimeChangeFlag: " + userTimeChangeFlag);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__GET_USER_TIME_CHANGE_FLAG";
}
}

View file

@ -0,0 +1,85 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_General_Initial_Screen_Information extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Step_Bolus_Information.class);
public DanaRS_Packet_General_Initial_Screen_Information() {
super();
type = BleCommandUtil.DANAR_PACKET__TYPE_RESPONSE;
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION;
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
pump.pumpSuspended = (status & 0x01) == 0x01;
pump.isTempBasalInProgress = (status & 0x10) == 0x10;
pump.isExtendedInProgress = (status & 0x04) == 0x04;
pump.isDualBolusInProgress = (status & 0x08) == 0x08;
dataIndex += dataSize;
dataSize = 2;
pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.maxDailyTotalUnits = (int) (byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d);
dataIndex += dataSize;
dataSize = 2;
pump.reservoirRemainingUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.currentBasal = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 1;
pump.tempBasalPercent = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.batteryRemaining = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
pump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Pump suspended: " + pump.pumpSuspended);
log.debug("Temp basal in progress: " + pump.isTempBasalInProgress);
log.debug("Extended in progress: " + pump.isExtendedInProgress);
log.debug("Dual in progress: " + pump.isDualBolusInProgress);
log.debug("Daily units: " + pump.dailyTotalUnits);
log.debug("Max daily units: " + pump.maxDailyTotalUnits);
log.debug("Reservoir remaining units: " + pump.reservoirRemainingUnits);
log.debug("Battery: " + pump.batteryRemaining);
log.debug("Current basal: " + pump.currentBasal);
log.debug("Temp basal percent: " + pump.tempBasalPercent);
log.debug("Extended absolute rate: " + pump.extendedBolusAbsoluteRate);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__INITIAL_SCREEN_INFORMATION";
}
}

View file

@ -0,0 +1,47 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_General_Set_History_Upload_Mode extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Set_History_Upload_Mode.class);
private int mode;
public DanaRS_Packet_General_Set_History_Upload_Mode() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SET_HISTORY_UPLOAD_MODE;
}
public DanaRS_Packet_General_Set_History_Upload_Mode(int mode) {
this();
this.mode = mode;
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[1];
request[0] = (byte) (mode & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__SET_HISTORY_UPLOAD_MODE";
}
}

View file

@ -0,0 +1,33 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.class);
public DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int status = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + status);
}
}
@Override
public String getFriendlyName() {
return "REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR";
}
}

View file

@ -0,0 +1,230 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.utils.DateUtil;
public abstract class DanaRS_Packet_History_ extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_History_.class);
private int year = 0;
private int month = 0;
private int day = 0;
private int hour = 0;
private int min = 0;
private int sec = 0;
public boolean done;
public int totalCount;
public DanaRS_Packet_History_() {
super();
done = false;
totalCount = 0;
}
public DanaRS_Packet_History_(Date from) {
this();
GregorianCalendar cal = new GregorianCalendar();
if (from.getTime() != 0)
cal.setTime(from);
else
cal.set(2000, 0, 1, 0, 0, 0);
year = cal.get(Calendar.YEAR) - 1900 - 100;
month = cal.get(Calendar.MONTH) + 1;
day = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
log.debug("Loading event history from: " + new Date(cal.getTimeInMillis()).toLocaleString());
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[6];
request[0] = (byte) (year & 0xff);
request[1] = (byte) (month & 0xff);
request[2] = (byte) (day & 0xff);
request[3] = (byte) (hour & 0xff);
request[4] = (byte) (min & 0xff);
request[5] = (byte) (sec & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int error;
totalCount = 0;
if (data.length == 3) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
done = true;
log.debug("History end. Code: " + error + " Success: " + (error == 0x00));
} else if (data.length == 5) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
done = true;
dataIndex += dataSize;
dataSize = 2;
totalCount = byteArrayToInt(getBytes(data, dataIndex, dataSize));
log.debug("History end. Code: " + error + " Success: " + (error == 0x00) + " Toatal count: " + totalCount);
} else {
int recordCode = byteArrayToInt(getBytes(data, DATA_START, 1));
int historyYear = byteArrayToInt(getBytes(data, DATA_START + 1, 1));
int historyMonth = byteArrayToInt(getBytes(data, DATA_START +2 , 1));
int historyDay = byteArrayToInt(getBytes(data, DATA_START + 3, 1));
int historyHour = byteArrayToInt(getBytes(data, DATA_START + 4, 1));
double dailyBasal = (((data[DATA_START + 4] & 0xFF) << 8) + (data[DATA_START + 5] & 0xFF)) * 0.01d;
int historyMinute = byteArrayToInt(getBytes(data, DATA_START + 5, 1));
int historySecond = byteArrayToInt(getBytes(data, DATA_START + 6, 1));
byte paramByte7 = (byte) historySecond;
double dailyBolus = (((data[DATA_START + 6] & 0xFF) << 8) + (data[DATA_START + 7] & 0xFF)) * 0.01d;
Date date = new Date(100 + historyYear, historyMonth - 1, historyDay);
Date datetime = new Date(100 + historyYear, historyMonth - 1, historyDay, historyHour, historyMinute);
Date datetimewihtsec = new Date(100 + historyYear, historyMonth - 1, historyDay, historyHour, historyMinute, historySecond);
int historyCode = byteArrayToInt(getBytes(data, DATA_START + 7, 1));
byte paramByte8 = (byte) historyCode;
int value = ((data[DATA_START + 8] & 0xFF) << 8) + (data[DATA_START + 9] & 0xFF);
log.debug("History packet: " + recordCode + " Date: " + datetimewihtsec.toLocaleString() + " Code: " + historyCode + " Value: " + value);
EventDanaRSyncStatus ev = new EventDanaRSyncStatus();
DanaRHistoryRecord danaRHistoryRecord = new DanaRHistoryRecord();
danaRHistoryRecord.setBytes(data);
// danaRHistoryRecord.recordCode is different from DanaR codes
// set in switch for every type
String messageType = "";
switch (recordCode) {
case 0x02:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_BOLUS;
danaRHistoryRecord.recordDate = datetime.getTime();
switch (0xF0 & paramByte8) {
case 0xA0:
danaRHistoryRecord.bolusType = "DS";
messageType += "DS bolus";
break;
case 0xC0:
danaRHistoryRecord.bolusType = "E";
messageType += "E bolus";
break;
case 0x80:
danaRHistoryRecord.bolusType = "S";
messageType += "S bolus";
break;
case 0x90:
danaRHistoryRecord.bolusType = "DE";
messageType += "DE bolus";
break;
default:
danaRHistoryRecord.bolusType = "None";
break;
}
danaRHistoryRecord.recordDuration = ((int) paramByte8 & 0x0F) * 60 + (int) paramByte7;
danaRHistoryRecord.recordValue = value * 0.01;
break;
case 0x03:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_DAILY;
messageType += "dailyinsulin";
danaRHistoryRecord.recordDate = date.getTime();
danaRHistoryRecord.recordDailyBasal = dailyBasal;
danaRHistoryRecord.recordDailyBolus = dailyBolus;
break;
case 0x04:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_PRIME;
messageType += "prime";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
danaRHistoryRecord.recordValue = value * 0.01;
break;
case 0x05:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_REFILL;
messageType += "refill";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
danaRHistoryRecord.recordValue = value * 0.01;
break;
case 0x0b:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_BASALHOUR;
messageType += "basal hour";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
danaRHistoryRecord.recordValue = value * 0.01;
break;
case 0x99: ///// ????????? don't know the right code
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_TEMP_BASAL;
messageType += "tb";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
danaRHistoryRecord.recordValue = value * 0.01;
break;
case 0x06:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_GLUCOSE;
messageType += "glucose";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
danaRHistoryRecord.recordValue = value;
break;
case 0x07:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_CARBO;
messageType += "carbo";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
danaRHistoryRecord.recordValue = value;
break;
case 0x0a:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_ALARM;
messageType += "alarm";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
String strAlarm = "None";
switch ((int) paramByte8) {
case 67:
strAlarm = "Check";
break;
case 79:
strAlarm = "Occlusion";
break;
case 66:
strAlarm = "Low Battery";
break;
case 83:
strAlarm = "Shutdown";
break;
}
danaRHistoryRecord.recordAlarm = strAlarm;
danaRHistoryRecord.recordValue = value * 0.01;
break;
case 0x09:
danaRHistoryRecord.recordCode = RecordTypes.RECORD_TYPE_SUSPEND;
messageType += "suspend";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime();
String strRecordValue = "Off";
if ((int) paramByte8 == 79)
strRecordValue = "On";
danaRHistoryRecord.stringRecordValue = strRecordValue;
break;
}
MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord);
ev.message = DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate);
ev.message += " " + messageType;
MainApp.bus().post(ev);
}
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Alarm extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Alarm() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM;
}
public DanaRS_Packet_History_Alarm(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM;
}
@Override
public String getFriendlyName() {
return "REVIEW__ALARM";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_All_History extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_All_History() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY;
}
public DanaRS_Packet_History_All_History(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY;
}
@Override
public String getFriendlyName() {
return "REVIEW__ALL_HISTORY";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Basal extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Basal() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL;
}
public DanaRS_Packet_History_Basal(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL;
}
@Override
public String getFriendlyName() {
return "REVIEW__BASAL";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Blood_Glucose extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Blood_Glucose() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE;
}
public DanaRS_Packet_History_Blood_Glucose(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE;
}
@Override
public String getFriendlyName() {
return "REVIEW__BLOOD_GLUCOSE";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Bolus extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Bolus() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS;
}
public DanaRS_Packet_History_Bolus(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS;
}
@Override
public String getFriendlyName() {
return "REVIEW__BOLUS";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Carbohydrate extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Carbohydrate() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE;
}
public DanaRS_Packet_History_Carbohydrate(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE;
}
@Override
public String getFriendlyName() {
return "REVIEW__CARBOHYDRATE";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Daily extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Daily() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY;
}
public DanaRS_Packet_History_Daily(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY;
}
@Override
public String getFriendlyName() {
return "REVIEW__DAILY";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Prime extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Prime() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME;
}
public DanaRS_Packet_History_Prime(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME;
}
@Override
public String getFriendlyName() {
return "REVIEW__PRIME";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Refill extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Refill() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL;
}
public DanaRS_Packet_History_Refill(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL;
}
@Override
public String getFriendlyName() {
return "REVIEW__REFILL";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Suspend extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Suspend() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND;
}
public DanaRS_Packet_History_Suspend(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND;
}
@Override
public String getFriendlyName() {
return "REVIEW__SUSPEND";
}
}

View file

@ -0,0 +1,23 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import java.util.Date;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_History_Temporary extends DanaRS_Packet_History_ {
public DanaRS_Packet_History_Temporary() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY;
}
public DanaRS_Packet_History_Temporary(Date from) {
super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY;
}
@Override
public String getFriendlyName() {
return "REVIEW__TEMPORARY";
}
}

View file

@ -0,0 +1,88 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.utils.NSUpload;
public class DanaRS_Packet_Notify_Alarm extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Alarm.class);
private int alarmCode;
public DanaRS_Packet_Notify_Alarm() {
super();
type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY;
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__ALARM;
}
@Override
public void handleMessage(byte[] data) {
alarmCode = byteArrayToInt(getBytes(data, DATA_START, 1));
String errorString = "";
switch (alarmCode) {
case 0x01:
// Battery 0% Alarm
errorString = MainApp.sResources.getString(R.string.batterydischarged);
break;
case 0x02:
// Pump Error
errorString = MainApp.sResources.getString(R.string.pumperror) + " " + alarmCode;
break;
case 0x03:
// Occlusion
errorString = MainApp.sResources.getString(R.string.occlusion);
break;
case 0x04:
// LOW BATTERY
errorString = MainApp.sResources.getString(R.string.lowbattery);
break;
case 0x05:
// Shutdown
errorString = MainApp.sResources.getString(R.string.lowbattery);
break;
case 0x06:
// Basal Compare
errorString = "BasalCompare ????";
break;
case 0x09:
// Empty Reservoir
errorString = MainApp.sResources.getString(R.string.emptyreservoir);
break;
// BT
case 0x07:
case 0xFF:
// Blood sugar measurement alert
errorString = MainApp.sResources.getString(R.string.bloodsugarmeasurementalert);
break;
case 0x08:
case 0xFE:
// Remaining insulin level
errorString = MainApp.sResources.getString(R.string.remaininsulinalert);
break;
case 0xFD:
// Blood sugar check miss alarm
errorString = "Blood sugar check miss alarm ???";
break;
}
if (Config.logDanaMessageDetail)
log.debug("Error detected: " + errorString);
NSUpload.uploadError(errorString);
}
@Override
public String getFriendlyName() {
return "NOTIFY__ALARM";
}
}

View file

@ -0,0 +1,57 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Delivery_Complete.class);
private static Treatment t;
private static double amount;
public static boolean done;
public DanaRS_Packet_Notify_Delivery_Complete() {
super();
type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY;
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_COMPLETE;
}
public DanaRS_Packet_Notify_Delivery_Complete(double amount, Treatment t) {
this();
this.amount = amount;
this.t = t;
done = false;
}
@Override
public void handleMessage(byte[] data) {
double deliveredInsulin = byteArrayToInt(getBytes(data, DATA_START, 2)) / 100d;
if (t != null) {
t.insulin = deliveredInsulin;
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.status = String.format(MainApp.sResources.getString(R.string.bolusdelivering), deliveredInsulin);
bolusingEvent.t = t;
bolusingEvent.percent = Math.min((int) (deliveredInsulin / amount * 100), 100);
done = true;
MainApp.bus().post(bolusingEvent);
}
if (Config.logDanaMessageDetail)
log.debug("Delivered insulin: " + deliveredInsulin);
}
@Override
public String getFriendlyName() {
return "NOTIFY__DELIVERY_COMPLETE";
}
}

View file

@ -0,0 +1,56 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Delivery_Rate_Display.class);
private static Treatment t;
private static double amount;
public static long lastReceive = 0;
public DanaRS_Packet_Notify_Delivery_Rate_Display() {
super();
type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY;
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_RATE_DISPLAY;
}
public DanaRS_Packet_Notify_Delivery_Rate_Display(double amount, Treatment t) {
this();
this.amount = amount;
this.t = t;
lastReceive = System.currentTimeMillis();
}
@Override
public void handleMessage(byte[] data) {
double deliveredInsulin = byteArrayToInt(getBytes(data, DATA_START, 2)) / 100d;
if (t != null) {
lastReceive = System.currentTimeMillis();
t.insulin = deliveredInsulin;
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.status = String.format(MainApp.sResources.getString(R.string.bolusdelivering), deliveredInsulin);
bolusingEvent.t = t;
bolusingEvent.percent = Math.min((int) (deliveredInsulin / amount * 100), 100);
MainApp.bus().post(bolusingEvent);
}
if (Config.logDanaMessageDetail)
log.debug("Delivered insulin so far: " + deliveredInsulin);
}
@Override
public String getFriendlyName() {
return "NOTIFY__DELIVERY_RATE_DISPLAY";
}
}

View file

@ -0,0 +1,54 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Notify_Missed_Bolus_Alarm extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Missed_Bolus_Alarm.class);
public DanaRS_Packet_Notify_Missed_Bolus_Alarm() {
super();
type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY;
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM;
}
@Override
public void handleMessage(byte[] data) {
int startHour;
int startMin;
int endHour;
int endMin;
int dataIndex = DATA_START;
int dataSize = 1;
startHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
startMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
endHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
endMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Start hour: " + startHour);
log.debug("Start min: " + startMin);
log.debug("End hour: " + endHour);
log.debug("End min: " + endMin);
}
}
@Override
public String getFriendlyName() {
return "NOTIFY__MISSED_BOLUS_ALARM";
}
}

View file

@ -0,0 +1,61 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Option_Get_Pump_Time extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Get_Pump_Time.class);
public DanaRS_Packet_Option_Get_Pump_Time() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__GET_PUMP_TIME;
if (Config.logDanaMessageDetail) {
log.debug("Requesting pump time");
}
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
int year = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int month = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int day = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int hour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int min = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int sec = byteArrayToInt(getBytes(data, dataIndex, dataSize));
Date time = new Date(100 + year, month - 1, day, hour, min, sec);
DanaRPump.getInstance().pumpTime = time;
if (Config.logDanaMessageDetail) {
log.debug("Pump time " + time.toLocaleString());
}
}
@Override
public String getFriendlyName() {
return "OPTION__GET_PUMP_TIME";
}
}

View file

@ -0,0 +1,114 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Option_Get_User_Option extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Get_User_Option.class);
public DanaRS_Packet_Option_Get_User_Option() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION;
if (Config.logDanaMessageDetail) {
log.debug("Requesting user settings");
}
}
@Override
public void handleMessage(byte[] data) {
DanaRPump pump = DanaRPump.getInstance();
int dataIndex = DATA_START;
int dataSize = 1;
pump.timeDisplayType = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.buttonScrollOnOff = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.beepAndAlarm = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.lcdOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.backlightOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.selectedLanguage = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.shutdownHour = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
pump.lowReservoirRate = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.cannulaVolume = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 2;
pump.refillAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int selectableLanguage1 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int selectableLanguage2 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int selectableLanguage3 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int selectableLanguage4 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
dataIndex += dataSize;
dataSize = 1;
int selectableLanguage5 = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("timeDisplayType: " + pump.timeDisplayType);
log.debug("buttonScrollOnOff: " + pump.buttonScrollOnOff);
log.debug("beepAndAlarm: " + pump.beepAndAlarm);
log.debug("lcdOnTimeSec: " + pump.lcdOnTimeSec);
log.debug("backlightOnTimeSec: " + pump.backlightOnTimeSec);
log.debug("selectedLanguage: " + pump.selectedLanguage);
log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL"));
log.debug("shutdownHour: " + pump.shutdownHour);
log.debug("lowReservoirRate: " + pump.lowReservoirRate);
log.debug("refillAmount: " + pump.refillAmount);
log.debug("selectableLanguage1: " + selectableLanguage1);
log.debug("selectableLanguage2: " + selectableLanguage2);
log.debug("selectableLanguage3: " + selectableLanguage3);
log.debug("selectableLanguage4: " + selectableLanguage4);
log.debug("selectableLanguage5: " + selectableLanguage5);
}
}
@Override
public String getFriendlyName() {
return "OPTION__GET_USER_OPTION";
}
}

View file

@ -0,0 +1,56 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Option_Set_Pump_Time extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Set_Pump_Time.class);
private Date date;
public int error;
public DanaRS_Packet_Option_Set_Pump_Time() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME;
}
public DanaRS_Packet_Option_Set_Pump_Time(Date date) {
this();
this.date = date;
if (Config.logDanaMessageDetail) {
log.debug("Setting pump time " + date.toLocaleString());
}
}
@Override
public byte[] getRequestParams() {
byte[] request = new byte[6];
request[0] = (byte) ((date.getYear() - 100) & 0xff);
request[1] = (byte) ((date.getMonth() + 1) & 0xff);
request[2] = (byte) (date.getDate() & 0xff);
request[3] = (byte) (date.getHours() & 0xff);
request[4] = (byte) (date.getMinutes() & 0xff);
request[5] = (byte) (date.getSeconds() & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "OPTION__SET_PUMP_TIME";
}
}

View file

@ -0,0 +1,58 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
public class DanaRS_Packet_Option_Set_User_Option extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Set_User_Option.class);
private int error;
public DanaRS_Packet_Option_Set_User_Option() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION;
if (Config.logDanaMessageDetail) {
log.debug("Setting user settings");
}
}
@Override
public byte[] getRequestParams() {
DanaRPump pump = DanaRPump.getInstance();
byte[] request = new byte[13];
request[0] = (byte) (pump.timeDisplayType & 0xff);
request[1] = (byte) (pump.buttonScrollOnOff & 0xff);
request[2] = (byte) (pump.beepAndAlarm & 0xff);
request[3] = (byte) (pump.lcdOnTimeSec & 0xff);
request[4] = (byte) (pump.backlightOnTimeSec & 0xff);
request[5] = (byte) (pump.selectedLanguage & 0xff);
request[6] = (byte) (pump.units & 0xff);
request[7] = (byte) (pump.shutdownHour & 0xff);
request[8] = (byte) (pump.lowReservoirRate & 0xff);
request[9] = (byte) (pump.cannulaVolume & 0xff);
request[10] = (byte) ((pump.cannulaVolume >>> 8) & 0xff);
request[11] = (byte) (pump.refillAmount & 0xff);
request[12] = (byte) ((pump.refillAmount >>> 8) & 0xff);
return request;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 1;
error = byteArrayToInt(getBytes(data, dataIndex, dataSize));
if (Config.logDanaMessageDetail) {
log.debug("Result: " + error);
}
}
@Override
public String getFriendlyName() {
return "OPTION__SET_USER_OPTION";
}
}

View file

@ -0,0 +1,52 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import com.cozmo.danar.util.BleCommandUtil;
public class DanaRS_Packet_Review_Bolus_Avg extends DanaRS_Packet {
private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Review_Bolus_Avg.class);
public DanaRS_Packet_Review_Bolus_Avg() {
super();
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG;
}
@Override
public void handleMessage(byte[] data) {
int dataIndex = DATA_START;
int dataSize = 2;
double bolusAvg03 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double bolusAvg07 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double bolusAvg14 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double bolusAvg21 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
dataIndex += dataSize;
dataSize = 2;
double bolusAvg28 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if (Config.logDanaMessageDetail) {
log.debug("Bolus average 3d: " + bolusAvg03 + " U");
log.debug("Bolus average 7d: " + bolusAvg07 + " U");
log.debug("Bolus average 14d: " + bolusAvg14 + " U");
log.debug("Bolus average 21d: " + bolusAvg21 + " U");
log.debug("Bolus average 28d: " + bolusAvg28 + " U");
}
}
@Override
public String getFriendlyName() {
return "REVIEW__BOLUS_AVG";
}
}

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.events;
/**
* Created by mike on 05.09.2017.
*/
public class EventDanaRSDeviceChange {
}

View file

@ -0,0 +1,15 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.events;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet;
/**
* Created by mike on 01.09.2017.
*/
public class EventDanaRSPacket {
public EventDanaRSPacket(DanaRS_Packet data) {
this.data = data;
}
public DanaRS_Packet data;
}

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.events;
/**
* Created by mike on 01.09.2017.
*/
public class EventDanaRSPairingSuccess {
}

View file

@ -0,0 +1,701 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.services;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.activities.PairingHelperActivity;
import info.nightscout.androidaps.plugins.PumpDanaRS.activities.PairingProgressDialog;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRSMessageHashTable;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet;
import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSPacket;
import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSPairingSuccess;
import info.nightscout.utils.SP;
/**
* Created by mike on 23.09.2017.
*/
public class BLEComm {
private static Logger log = LoggerFactory.getLogger(BLEComm.class);
private static final long WRITE_DELAY_MILLIS = 50;
public static String UART_READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb";
public static String UART_WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb";
private byte PACKET_START_BYTE = (byte) 0xA5;
private byte PACKET_END_BYTE = (byte) 0x5A;
private static BLEComm instance = null;
public static BLEComm getInstance(DanaRSService service) {
if (instance == null)
instance = new BLEComm(service);
return instance;
}
private Object mConfirmConnect = null;
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> scheduledDisconnection = null;
private DanaRS_Packet processsedMessage = null;
private ArrayList<byte[]> mSendQueue = new ArrayList<>();
// Variables for connection progress (elapsed time)
private Handler sHandler;
private HandlerThread sHandlerThread;
private long connectionStartTime = 0;
private final Runnable updateProgress = new Runnable() {
@Override
public void run() {
long secondsElapsed = (System.currentTimeMillis() - connectionStartTime) / 1000;
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed));
sHandler.postDelayed(updateProgress, 1000);
}
};
private BluetoothManager mBluetoothManager = null;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mBluetoothDevice = null;
private String mBluetoothDeviceAddress = null;
private String mBluetoothDeviceName = null;
private BluetoothGatt mBluetoothGatt = null;
protected boolean isConnected = false;
protected boolean isConnecting = false;
private BluetoothGattCharacteristic UART_Read;
private BluetoothGattCharacteristic UART_Write;
private DanaRSService service;
BLEComm(DanaRSService service) {
this.service = service;
initialize();
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(PairingProgressDialog.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
}
private boolean initialize() {
log.debug("Initializing BLEComm.");
if (mBluetoothManager == null) {
mBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE));
if (mBluetoothManager == null) {
log.debug("Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
log.debug("Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
public boolean isConnected() {
return isConnected;
}
public boolean isConnecting() {
return isConnecting;
}
public boolean connect(String from, String address, Object confirmConnect) {
mConfirmConnect = confirmConnect;
BluetoothManager tBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE));
if (tBluetoothManager == null) {
return false;
}
BluetoothAdapter tBluetoothAdapter = tBluetoothManager.getAdapter();
if (tBluetoothAdapter == null) {
return false;
}
if (mBluetoothAdapter == null) {
if (!initialize()) {
return false;
}
}
if (address == null) {
log.debug("unspecified address.");
return false;
}
connectionStartTime = System.currentTimeMillis();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING));
isConnecting = true;
// Following should be removed later because we close Gatt on disconnect and this should never happen
if ((mBluetoothDeviceAddress != null) && (address.equals(mBluetoothDeviceAddress)) && (mBluetoothGatt != null)) {
log.debug("Trying to use an existing mBluetoothGatt for connection.");
sHandler.post(updateProgress);
if (mBluetoothGatt.connect()) {
setCharacteristicNotification(getUARTReadBTGattChar(), true);
return true;
}
sHandler.removeCallbacks(updateProgress);
return false;
}
// end
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
log.debug("Device not found. Unable to connect.");
return false;
}
sHandler.post(updateProgress);
mBluetoothGatt = device.connectGatt(service.getApplicationContext(), false, mGattCallback);
setCharacteristicNotification(getUARTReadBTGattChar(), true);
log.debug("Trying to create a new connection.");
mBluetoothDevice = device;
mBluetoothDeviceAddress = address;
mBluetoothDeviceName = device.getName();
return true;
}
public void disconnect(String from) {
log.debug("disconnect from: " + from);
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
return;
}
setCharacteristicNotification(getUARTReadBTGattChar(), false);
mBluetoothGatt.disconnect();
isConnected = false;
}
public void close() {
log.debug("BluetoothAdapter close");
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
public BluetoothDevice getConnectDevice() {
return mBluetoothDevice;
}
public String getConnectDeviceAddress() {
return mBluetoothDeviceAddress;
}
public String getConnectDeviceName() {
return mBluetoothDeviceName;
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
log.debug("onConnectionStateChange");
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
close();
isConnected = false;
sHandler.removeCallbacks(updateProgress); // just to be sure
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected
}
}
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
log.debug("onServicesDiscovered");
isConnecting = false;
if (status == BluetoothGatt.GATT_SUCCESS) {
findCharacteristic();
}
// stop sending connection progress
sHandler.removeCallbacks(updateProgress);
SendPumpCheck();
// 1st message sent to pump after connect
}
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
log.debug("onCharacteristicRead" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : ""));
addToReadBuffer(characteristic.getValue());
readDataParsing();
}
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
log.debug("onCharacteristicChanged" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : ""));
addToReadBuffer(characteristic.getValue());
new Thread(new Runnable() {
@Override
public void run() {
readDataParsing();
}
}).start();
}
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : ""));
new Thread(new Runnable() {
@Override
public void run() {
synchronized (mSendQueue) {
// after message sent, check if there is the rest of the message waiting and send it
if (mSendQueue.size() > 0) {
byte[] bytes = mSendQueue.get(0);
mSendQueue.remove(0);
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
}
}
}).start();
}
};
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
log.debug("setCharacteristicNotification");
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.debug("BluetoothAdapter not initialized_ERROR");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
log.debug("readCharacteristic");
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.debug("BluetoothAdapter not initialized_ERROR");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
public void writeCharacteristic_NO_RESPONSE(final BluetoothGattCharacteristic characteristic, final byte[] data) {
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.debug("BluetoothAdapter not initialized_ERROR");
return;
}
new Thread(new Runnable() {
public void run() {
SystemClock.sleep(WRITE_DELAY_MILLIS);
characteristic.setValue(data);
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data));
mBluetoothGatt.writeCharacteristic(characteristic);
}
}).start();
}
public BluetoothGattCharacteristic getUARTReadBTGattChar() {
if (UART_Read == null) {
UART_Read = new BluetoothGattCharacteristic(UUID.fromString(UART_READ_UUID), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0);
}
return UART_Read;
}
public BluetoothGattCharacteristic getUARTWriteBTGattChar() {
if (UART_Write == null) {
UART_Write = new BluetoothGattCharacteristic(UUID.fromString(UART_WRITE_UUID), BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, 0);
}
return UART_Write;
}
public List<BluetoothGattService> getSupportedGattServices() {
log.debug("getSupportedGattServices");
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.debug("BluetoothAdapter not initialized_ERROR");
return null;
}
return mBluetoothGatt.getServices();
}
private void findCharacteristic() {
List<BluetoothGattService> gattServices = getSupportedGattServices();
if (gattServices == null) {
return;
}
String uuid = null;
for (BluetoothGattService gattService : gattServices) {
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
uuid = gattCharacteristic.getUuid().toString();
if (UART_READ_UUID.equals(uuid)) {
UART_Read = gattCharacteristic;
setCharacteristicNotification(UART_Read, true);
}
if (UART_WRITE_UUID.equals(uuid)) {
UART_Write = gattCharacteristic;
}
}
}
}
private byte[] readBuffer = new byte[1024];
private int bufferLength = 0;
private void addToReadBuffer(byte[] buffer) {
//log.debug("addToReadBuffer " + DanaRS_Packet.toHexString(buffer));
if (buffer == null || buffer.length == 0) {
return;
}
synchronized (readBuffer) {
// Append incomming data to input buffer
System.arraycopy(buffer, 0, readBuffer, bufferLength, buffer.length);
bufferLength += buffer.length;
}
}
private void readDataParsing() {
boolean startSignatureFound = false, packetIsValid = false;
boolean isProcessing;
isProcessing = true;
while (isProcessing) {
int length = 0;
byte[] inputBuffer = null;
synchronized (readBuffer) {
// Find packet start [A5 A5]
if (bufferLength >= 6) {
for (int idxStartByte = 0; idxStartByte < bufferLength - 2; idxStartByte++) {
if ((readBuffer[idxStartByte] == PACKET_START_BYTE) && (readBuffer[idxStartByte + 1] == PACKET_START_BYTE)) {
if (idxStartByte > 0) {
// if buffer doesn't start with signature remove the leading trash
log.debug("Shifting the input buffer by " + idxStartByte + " bytes");
System.arraycopy(readBuffer, idxStartByte, readBuffer, 0, bufferLength - idxStartByte);
bufferLength -= idxStartByte;
}
startSignatureFound = true;
break;
}
}
}
// A5 A5 LEN TYPE CODE PARAMS CHECKSUM1 CHECKSUM2 5A 5A
// ^---- LEN -----^
// total packet length 2 + 1 + readBuffer[2] + 2 + 2
if (startSignatureFound) {
length = readBuffer[2];
// test if there is enough data loaded
if (length + 7 > bufferLength)
return;
// Verify packed end [5A 5A]
if ((readBuffer[length + 5] == PACKET_END_BYTE) && (readBuffer[length + 6] == PACKET_END_BYTE)) {
packetIsValid = true;
}
}
if (packetIsValid) {
inputBuffer = new byte[length + 7];
// copy packet to input buffer
System.arraycopy(readBuffer, 0, inputBuffer, 0, length + 7);
// Cut off the message from readBuffer
try {
System.arraycopy(readBuffer, length + 7, readBuffer, 0, bufferLength - (length + 7));
} catch (Exception e) {
log.debug("length: " + length + "bufferLength: " + bufferLength);
throw e;
}
bufferLength -= (length + 7);
// now we have encrypted packet in inputBuffer
}
}
if (packetIsValid) {
try {
// decrypt the packet
inputBuffer = BleCommandUtil.getInstance().getDecryptedPacket(inputBuffer);
if (inputBuffer == null) {
log.debug("Null decryptedInputBuffer");
return;
}
switch (inputBuffer[0]) {
// initial handshake packet
case (byte) BleCommandUtil.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE:
switch (inputBuffer[1]) {
// 1st packet
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK:
if (inputBuffer.length == 4 && inputBuffer[2] == 'O' && inputBuffer[3] == 'K') {
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(inputBuffer));
// Grab pairing key from preferences if exists
String pairingKey = SP.getString(MainApp.sResources.getString(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, null);
log.debug("Using stored pairing key: " + pairingKey);
if (pairingKey != null) {
byte[] encodedPairingKey = DanaRS_Packet.hexToBytes(pairingKey);
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY, encodedPairingKey, null);
log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
} else {
// Stored pairing key does not exists, request pairing
SendPairingRequest();
}
} else if (inputBuffer.length == 6 && inputBuffer[2] == 'B' && inputBuffer[3] == 'U' && inputBuffer[4] == 'S' && inputBuffer[5] == 'Y') {
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.sResources.getString(R.string.pumpbusy)));
} else {
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.sResources.getString(R.string.connectionerror)));
}
break;
// 2nd packet, pairing key
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY:
log.debug("<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(inputBuffer));
if (inputBuffer[2] == (byte) 0x00) {
// Paring is not requested, sending time info
SendTimeInfo();
} else {
// Pairing on pump is requested
SendPairingRequest();
}
break;
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST:
log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer));
if (inputBuffer[2] != (byte) 0x00) {
disconnect("passkey request failed");
}
break;
// Paring response, OK button on pump pressed
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN:
log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer));
// Paring is successfull, sending time info
MainApp.bus().post(new EventDanaRSPairingSuccess());
SendTimeInfo();
byte[] pairingKey = {inputBuffer[2], inputBuffer[3]};
// store pairing key to preferences
SP.putString(MainApp.sResources.getString(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, DanaRS_Packet.bytesToHex(pairingKey));
log.debug("Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey));
break;
// time and user password information. last packet in handshake
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION:
log.debug("<<<<< " + "ENCRYPTION__TIME_INFORMATION " + /*message.getMessageName() + " " + */ DanaRS_Packet.toHexString(inputBuffer));
int size = inputBuffer.length;
int pass = ((inputBuffer[size - 1] & 0x000000FF) << 8) + ((inputBuffer[size - 2] & 0x000000FF));
pass = pass ^ 3463;
DanaRPump.getInstance().rs_password = Integer.toHexString(pass);
log.debug("Pump user password: " + Integer.toHexString(pass));
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED));
isConnected = true;
isConnecting = false;
service.getPumpStatus();
scheduleDisconnection();
if (mConfirmConnect != null) {
synchronized (mConfirmConnect) {
mConfirmConnect.notify();
mConfirmConnect = null;
}
}
break;
}
break;
// common data packet
default:
DanaRS_Packet message;
// Retrieve message code from received buffer and last message sent
int originalCommand = processsedMessage != null ? processsedMessage.getCommand() : 0xFFFF;
int receivedCommand = DanaRS_Packet.getCommand(inputBuffer);
if (originalCommand == receivedCommand) {
// it's response to last message
message = processsedMessage;
} else {
// it's not response to last message, create new instance
message = DanaRSMessageHashTable.findMessage(receivedCommand);
}
if (message != null) {
log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer));
// process received data
message.handleMessage(inputBuffer);
message.setReceived();
synchronized (message) {
// notify to sendMessage
message.notify();
}
MainApp.bus().post(new EventDanaRSPacket(message));
} else {
log.error("Unknown message received " + DanaRS_Packet.toHexString(inputBuffer));
}
scheduleDisconnection();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
startSignatureFound = false;
packetIsValid = false;
if (bufferLength < 6) {
// stop the loop
isProcessing = false;
}
} else {
// stop the loop
isProcessing = false;
}
}
}
public void sendMessage(DanaRS_Packet message) {
processsedMessage = message;
if (message == null)
return;
byte[] command = {(byte) message.getType(), (byte) message.getOpCode()};
byte[] params = message.getRequestParams();
log.debug(">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params));
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(message.getOpCode(), params, null);
// If there is another message not completely sent, add to queue only
if (mSendQueue.size() > 0) {
// Split to parts per 20 bytes max
for (; ; ) {
if (bytes.length > 20) {
byte[] addBytes = new byte[20];
System.arraycopy(bytes, 0, addBytes, 0, addBytes.length);
byte[] reBytes = new byte[bytes.length - addBytes.length];
System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length);
bytes = reBytes;
synchronized (mSendQueue) {
mSendQueue.add(addBytes);
}
} else {
synchronized (mSendQueue) {
mSendQueue.add(bytes);
}
break;
}
}
} else {
if (bytes.length > 20) {
// Cut first 20 bytes
byte[] sendBytes = new byte[20];
System.arraycopy(bytes, 0, sendBytes, 0, sendBytes.length);
byte[] reBytes = new byte[bytes.length - sendBytes.length];
System.arraycopy(bytes, sendBytes.length, reBytes, 0, reBytes.length);
bytes = reBytes;
// and send
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), sendBytes);
// The rest split to parts per 20 bytes max
for (; ; ) {
if (bytes.length > 20) {
byte[] addBytes = new byte[20];
System.arraycopy(bytes, 0, addBytes, 0, addBytes.length);
reBytes = new byte[bytes.length - addBytes.length];
System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length);
bytes = reBytes;
synchronized (mSendQueue) {
mSendQueue.add(addBytes);
}
} else {
synchronized (mSendQueue) {
mSendQueue.add(bytes);
}
break;
}
}
} else {
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
}
// The rest from queue is send from onCharasteristicWrite (after sending 1st part)
synchronized (message) {
try {
message.wait(5000);
} catch (InterruptedException e) {
log.error("sendMessage InterruptedException", e);
e.printStackTrace();
}
}
//SystemClock.sleep(200);
if (!message.isReceived()) {
log.warn("Reply not received " + message.getFriendlyName());
}
scheduleDisconnection();
}
private void SendPairingRequest() {
// Start activity which is waiting 20sec
// On pump pairing request is displayed and is waiting for conformation
Intent i = new Intent();
i.setClass(MainApp.instance(), PairingHelperActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null);
log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
protected void SendPumpCheck() {
// 1st message sent to pump after connect
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, getConnectDeviceName());
log.debug(">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
private void SendTimeInfo() {
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, null, null);
log.debug(">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
public void scheduleDisconnection() {
class DisconnectRunnable implements Runnable {
public void run() {
disconnect("scheduleDisconnection");
scheduledDisconnection = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple disconnections
if (scheduledDisconnection != null)
scheduledDisconnection.cancel(false);
Runnable task = new DisconnectRunnable();
final int sec = 5;
scheduledDisconnection = worker.schedule(task, sec, TimeUnit.SECONDS);
log.debug("Disconnection scheduled");
}
}

View file

@ -0,0 +1,398 @@
package info.nightscout.androidaps.plugins.PumpDanaRS.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_APS_Basal_Set_Temporary_Basal;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_APS_History_Events;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_APS_Set_Event_History;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Get_Basal_Rate;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Get_Profile_Number;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Get_Temporary_Basal_State;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Set_Profile_Basal_Rate;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Set_Profile_Number;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Basal_Set_Temporary_Basal;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Get_Bolus_Option;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Get_CIR_CF_Array;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Get_Calculation_Information;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Get_Extended_Bolus_State;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Get_Step_Bolus_Information;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Start;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Stop;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_General_Get_Pump_Check;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_General_Get_Shipping_Information;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_General_Initial_Screen_Information;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_General_Set_History_Upload_Mode;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Alarm;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Basal;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Blood_Glucose;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Bolus;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Carbohydrate;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Daily;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Prime;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Refill;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_History_Suspend;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Notify_Delivery_Complete;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Notify_Delivery_Rate_Display;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Option_Get_Pump_Time;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Option_Set_Pump_Time;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
public class DanaRSService extends Service {
private static Logger log = LoggerFactory.getLogger(DanaRSService.class);
private BLEComm bleComm = BLEComm.getInstance(this);
private PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new LocalBinder();
private DanaRPump danaRPump = DanaRPump.getInstance();
private Treatment bolusingTreatment = null;
private long lastHistoryFetched = 0;
public DanaRSService() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, DanaRSService.class.getSimpleName());
}
public boolean isConnected() {
return bleComm.isConnected;
}
public boolean isConnecting() {
return bleComm.isConnecting;
}
public boolean connect(String from, String address, Object confirmConnect) {
return bleComm.connect(from, address, confirmConnect);
}
public void disconnect(String from) {
bleComm.disconnect(from);
}
public void sendMessage(DanaRS_Packet message) {
bleComm.sendMessage(message);
}
protected boolean getPumpStatus() {
try {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus)));
bleComm.sendMessage(new DanaRS_Packet_General_Initial_Screen_Information());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingextendedbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // last bolus
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingtempbasalstatus)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
Date now = new Date();
if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime() || !MainApp.getSpecificPlugin(DanaRSPlugin.class).isInitialized()) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpsettings)));
bleComm.sendMessage(new DanaRS_Packet_General_Get_Shipping_Information()); // serial no
bleComm.sendMessage(new DanaRS_Packet_General_Get_Pump_Check()); // firmware
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Profile_Number());
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Bolus_Option()); // isExtendedEnabled
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // bolusStep, maxBolus
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate()); // basal profile, basalStep, maxBasal
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Calculation_Information()); // target
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_CIR_CF_Array());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumptime)));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time());
long timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 10) {
bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(new Date()));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time());
timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds");
}
danaRPump.lastSettingsRead = now;
}
loadEvents();
danaRPump.lastConnection = now;
MainApp.bus().post(new EventDanaRNewStatus());
MainApp.bus().post(new EventInitializationChanged());
NSUpload.uploadDeviceStatus();
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits);
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U");
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
return true;
}
public boolean loadEvents() {
DanaRS_Packet_APS_History_Events msg;
if (lastHistoryFetched == 0) {
msg = new DanaRS_Packet_APS_History_Events(0);
log.debug("Loading complete event history");
} else {
msg = new DanaRS_Packet_APS_History_Events(lastHistoryFetched);
log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString());
}
bleComm.sendMessage(msg);
while (!msg.done && bleComm.isConnected()) {
SystemClock.sleep(100);
}
SystemClock.sleep(200);
lastHistoryFetched = DanaRS_Packet_APS_History_Events.lastEventTimeLoaded;
return true;
}
public boolean bolus(double insulin, int carbs, long carbtime, Treatment t) {
bolusingTreatment = t;
int speed = SP.getInt(R.string.key_danars_bolusspeed, 0);
DanaRS_Packet_Bolus_Set_Step_Bolus_Start start = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(insulin, speed);
DanaRS_Packet_Bolus_Set_Step_Bolus_Stop stop = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(insulin, t); // initialize static variables
DanaRS_Packet_Notify_Delivery_Complete complete = new DanaRS_Packet_Notify_Delivery_Complete(insulin, t); // initialize static variables
if (!isConnected()) return false;
if (carbs > 0) {
// MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbtime, carbs); ####
// bleComm.sendMessage(msg);
DanaRS_Packet_APS_Set_Event_History msgSetHistoryEntry_v2 = new DanaRS_Packet_APS_Set_Event_History(DanaRPump.CARBS, carbtime, carbs, 0);
bleComm.sendMessage(msgSetHistoryEntry_v2);
lastHistoryFetched = carbtime - 60000;
}
if (insulin > 0) {
DanaRS_Packet_Notify_Delivery_Rate_Display progress = new DanaRS_Packet_Notify_Delivery_Rate_Display(insulin, t); // initialize static variables
if (!stop.stopped) {
bleComm.sendMessage(start);
} else {
t.insulin = 0d;
return false;
}
while (!stop.stopped && !start.failed && !complete.done) {
SystemClock.sleep(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm
stop.stopped = true;
stop.forced = true;
log.debug("Communication stopped");
}
}
}
SystemClock.sleep(3000);
bolusingTreatment = null;
DanaRSPlugin.connectIfNotConnected("ReadHistoryAfterBolus");
loadEvents();
return true;
}
public void bolusStop() {
if (Config.logDanaBTComm)
log.debug("bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin));
DanaRS_Packet_Bolus_Set_Step_Bolus_Stop stop = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop();
stop.forced = true;
if (isConnected()) {
bleComm.sendMessage(stop);
while (!stop.stopped) {
bleComm.sendMessage(stop);
SystemClock.sleep(200);
}
} else {
stop.stopped = true;
}
}
public boolean tempBasal(Integer percent, int durationInHours) {
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
SystemClock.sleep(500);
}
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Temporary_Basal(percent, durationInHours));
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true;
}
public boolean highTempBasal(Integer percent) {
if (danaRPump.isTempBasalInProgress) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
SystemClock.sleep(500);
}
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(percent));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true;
}
public boolean tempBasalStop() {
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true;
}
public boolean extendedBolus(Double insulin, int durationInHalfHours) {
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus(insulin, durationInHalfHours));
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
loadEvents();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true;
}
public boolean extendedBolusStop() {
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel());
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
loadEvents();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true;
}
public boolean updateBasalsInPump(Profile profile) {
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = DanaRPump.buildDanaRProfileRecord(profile);
DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(0, basal);
bleComm.sendMessage(msgSet);
DanaRS_Packet_Basal_Set_Profile_Number msgActivate = new DanaRS_Packet_Basal_Set_Profile_Number(0);
bleComm.sendMessage(msgActivate);
danaRPump.lastSettingsRead = new Date(0); // force read full settings
getPumpStatus();
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true;
}
public boolean loadHistory(byte type) {
if (!isConnected()) return false;
DanaRS_Packet_History_ msg = null;
switch (type) {
case RecordTypes.RECORD_TYPE_ALARM:
msg = new DanaRS_Packet_History_Alarm();
break;
case RecordTypes.RECORD_TYPE_PRIME:
msg = new DanaRS_Packet_History_Prime();
break;
case RecordTypes.RECORD_TYPE_BASALHOUR:
msg = new DanaRS_Packet_History_Basal();
break;
case RecordTypes.RECORD_TYPE_BOLUS:
msg = new DanaRS_Packet_History_Bolus();
break;
case RecordTypes.RECORD_TYPE_CARBO:
msg = new DanaRS_Packet_History_Carbohydrate();
break;
case RecordTypes.RECORD_TYPE_DAILY:
msg = new DanaRS_Packet_History_Daily();
break;
case RecordTypes.RECORD_TYPE_GLUCOSE:
msg = new DanaRS_Packet_History_Blood_Glucose();
break;
case RecordTypes.RECORD_TYPE_REFILL:
msg = new DanaRS_Packet_History_Refill();
break;
case RecordTypes.RECORD_TYPE_SUSPEND:
msg = new DanaRS_Packet_History_Suspend();
break;
}
if (msg != null) {
bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(1));
SystemClock.sleep(200);
bleComm.sendMessage(msg);
while (!msg.done && isConnected()) {
SystemClock.sleep(100);
}
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(0));
}
return true;
}
public class LocalBinder extends Binder {
public DanaRSService getServiceInstance() {
return DanaRSService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Subscribe
public void onStatusEvent(EventAppExit event) {
if (Config.logFunctionCalls)
log.debug("EventAppExit received");
stopSelf();
if (Config.logFunctionCalls)
log.debug("EventAppExit finished");
}
}

View file

@ -210,7 +210,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, DanaRInterface,
@Override
public boolean isInitialized() {
return pump.lastConnection.getTime() > 0 && pump.isExtendedBolusEnabled;
return pump.lastConnection.getTime() > 0;
}
@Override
@ -578,7 +578,11 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, DanaRInterface,
}
public static void doConnect(String from) {
if (sExecutionService != null) sExecutionService.connect(from);
if (sExecutionService != null) {
sExecutionService.connect(from);
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
}
}
public static boolean isConnected() {

View file

@ -79,7 +79,7 @@ public class DanaRv2ExecutionService extends Service {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
log.debug("Device has disconnected " + device.getName());//Device has disconnected
log.debug("Device was disconnected " + device.getName());//Device was disconnected
if (mBTDevice != null && mBTDevice.getName() != null && mBTDevice.getName().equals(device.getName())) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast");
@ -261,10 +261,13 @@ public class DanaRv2ExecutionService extends Service {
}
}
mSerialIOThread.sendMessage(tempStatusMsg); // do this before statusBasic because here is temp duration
mSerialIOThread.sendMessage(exStatusMsg);
mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus)));
if (!statusMsg.received) {
mSerialIOThread.sendMessage(statusMsg);
@ -290,6 +293,7 @@ public class DanaRv2ExecutionService extends Service {
Date now = new Date();
if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime() || !MainApp.getSpecificPlugin(DanaRv2Plugin.class).isInitialized()) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingMeal());
@ -300,6 +304,7 @@ public class DanaRv2ExecutionService extends Service {
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds");
@ -538,7 +543,7 @@ public class DanaRv2ExecutionService extends Service {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = buildDanaRProfileRecord(profile);
double[] basal = DanaRPump.buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet);
MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0);
@ -549,17 +554,6 @@ public class DanaRv2ExecutionService extends Service {
return true;
}
private double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
double value = Math.round(100d * nsProfile.getBasal((Integer) (hour * 60 * 60)))/100d + 0.00001;
if (Config.logDanaMessageDetail)
log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value;
}
return record;
}
private void waitMsec(long msecs) {
SystemClock.sleep(msecs);
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

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