KoreanDanaR queue

This commit is contained in:
Milos Kozak 2017-11-22 20:11:25 +01:00
parent dfd0218a6a
commit 8818afe033
3 changed files with 103 additions and 94 deletions

View file

@ -35,6 +35,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
@ -82,6 +83,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
@ -364,7 +366,7 @@ public class DanaRExecutionService extends Service {
return true;
}
public boolean bolus(double amount, int carbs, Treatment t) {
public boolean bolus(double amount, int carbs, final Treatment t) {
bolusingTreatment = t;
int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0);
MessageBase start;
@ -391,7 +393,7 @@ public class DanaRExecutionService extends Service {
}
while (!stop.stopped && !start.failed) {
waitMsec(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm
stop.stopped = true;
stop.forced = true;
log.debug("Communication stopped");
@ -429,17 +431,27 @@ public class DanaRExecutionService extends Service {
MainApp.bus().post(bolusingEvent);
SystemClock.sleep(1000);
}
if (!isConnected())
connect("bolusingInterrupted");
getPumpStatus();
if (danaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old
t.insulin = danaRPump.lastBolusAmount;
log.debug("Used bolus amount from history: " + danaRPump.lastBolusAmount);
} else {
log.debug("Bolus amount in history too old: " + danaRPump.lastBolusTime.toLocaleString());
final Object o = new Object();
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusingInterrupted", new Callback() {
@Override
public void run() {
if (danaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old
t.insulin = danaRPump.lastBolusAmount;
log.debug("Used bolus amount from history: " + danaRPump.lastBolusAmount);
} else {
log.debug("Bolus amount in history too old: " + danaRPump.lastBolusTime.toLocaleString());
}
o.notify();
}
});
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
getPumpStatus();
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusOK", null);
}
return true;
}

View file

@ -352,9 +352,10 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, DanaRInterf
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean enforceNew) {
// Recheck pump status if older than 30 min
if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) {
connect("setTempBasalAbsolute old data");
}
//This should not be needed while using queue because connection should be done before calling this
//if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) {
// connect("setTempBasalAbsolute old data");
//}
PumpEnactResult result = new PumpEnactResult();
@ -682,12 +683,12 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, DanaRInterf
@Override
public void stopConnecting() {
// TODO AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
if (sExecutionService != null) sExecutionService.stopConnecting();
}
@Override
public void getPumpStatus() {
// TODO AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
if (sExecutionService != null) sExecutionService.getPumpStatus();
}
@Override

View file

@ -35,6 +35,8 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusProgress;
@ -76,6 +78,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgCheckValue_k;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgSettingBasal_k;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgStatusBasic_k;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
@ -89,14 +92,12 @@ public class DanaRKoreanExecutionService extends Service {
private BluetoothSocket mRfcommSocket;
private BluetoothDevice mBTDevice;
private PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new LocalBinder();
private DanaRPump danaRPump = DanaRPump.getInstance();
private Treatment bolusingTreatment = null;
private static Boolean connectionInProgress = false;
private static final Object connectionLock = new Object();
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
@ -120,9 +121,6 @@ public class DanaRKoreanExecutionService extends Service {
public DanaRKoreanExecutionService() {
registerBus();
MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DanaRKoreanExecutionService");
}
public class LocalBinder extends Binder {
@ -184,35 +182,28 @@ public class DanaRKoreanExecutionService extends Service {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error);
return;
}
while (isConnected() || isConnecting()) {
if (Config.logDanaBTComm)
log.debug("already connected/connecting from: " + from);
waitMsec(3000);
}
final long maxConnectionTime = 5 * 60 * 1000L; // 5 min
synchronized (connectionLock) {
//log.debug("entering connection while loop");
connectionInProgress = true;
mWakeLock.acquire();
getBTSocketForSelectedPump();
if (mRfcommSocket == null || mBTDevice == null)
return; // Device not found
long startTime = System.currentTimeMillis();
while (!isConnected() && startTime + maxConnectionTime >= System.currentTimeMillis()) {
long secondsElapsed = (System.currentTimeMillis() - startTime) / 1000L;
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed));
if (Config.logDanaBTComm)
log.debug("connect waiting " + secondsElapsed + "sec from: " + from);
if (connectionInProgress)
return;
new Thread(new Runnable() {
@Override
public void run() {
connectionInProgress = true;
getBTSocketForSelectedPump();
if (mRfcommSocket == null || mBTDevice == null) {
connectionInProgress = false;
return; // Device not found
}
try {
mRfcommSocket.connect();
} catch (IOException e) {
//log.error("Unhandled exception", e);
if (e.getMessage().contains("socket closed")) {
log.error("Unhandled exception", e);
break;
}
}
waitMsec(1000);
if (isConnected()) {
if (mSerialIOThread != null) {
@ -220,23 +211,16 @@ public class DanaRKoreanExecutionService extends Service {
}
mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0));
if (!getPumpStatus()) {
mSerialIOThread.disconnect("getPumpStatus failed");
waitMsec(3000);
if (!MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginBase.PUMP))
return;
getBTSocketForSelectedPump();
startTime = System.currentTimeMillis();
}
}
connectionInProgress = false;
}
if (!isConnected()) {
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
log.error("Pump connection timed out");
}
connectionInProgress = false;
mWakeLock.release();
}
}).start();
}
public void stopConnecting() {
if (mSerialIOThread != null)
mSerialIOThread.disconnect("stopConnecting");
}
private void getBTSocketForSelectedPump() {
@ -271,7 +255,7 @@ public class DanaRKoreanExecutionService extends Service {
mSerialIOThread.disconnect("EventPreferenceChange");
}
private boolean getPumpStatus() {
public void getPumpStatus() {
try {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus)));
//MsgStatus_k statusMsg = new MsgStatus_k();
@ -283,7 +267,7 @@ public class DanaRKoreanExecutionService extends Service {
if (danaRPump.isNewPump) {
mSerialIOThread.sendMessage(checkValue);
if (!checkValue.received) {
return false;
return;
}
}
@ -295,28 +279,6 @@ public class DanaRKoreanExecutionService extends Service {
mSerialIOThread.sendMessage(exStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus)));
// if (!statusMsg.received) {
// mSerialIOThread.sendMessage(statusMsg);
// }
if (!statusBasicMsg.received) {
mSerialIOThread.sendMessage(statusBasicMsg);
}
if (!tempStatusMsg.received) {
// Load of status of current basal rate failed, give one more try
mSerialIOThread.sendMessage(tempStatusMsg);
}
if (!exStatusMsg.received) {
// Load of status of current extended bolus failed, give one more try
mSerialIOThread.sendMessage(exStatusMsg);
}
// Check we have really current status of pump
if (/*!statusMsg.received || */!statusBasicMsg.received || !tempStatusMsg.received || !exStatusMsg.received) {
waitMsec(10 * 1000);
log.debug("getPumpStatus failed");
return false;
}
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)));
@ -344,7 +306,7 @@ public class DanaRKoreanExecutionService extends Service {
MainApp.bus().post(new EventDanaRNewStatus());
MainApp.bus().post(new EventInitializationChanged());
NSUpload.uploadDeviceStatus();
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) {
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));
@ -353,11 +315,10 @@ public class DanaRKoreanExecutionService extends Service {
} catch (Exception e) {
log.error("Unhandled exception", e);
}
return true;
return;
}
public boolean tempBasal(int percent, int durationInHours) {
connect("tempBasal");
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
@ -372,7 +333,6 @@ public class DanaRKoreanExecutionService extends Service {
}
public boolean tempBasalStop() {
connect("tempBasalStop");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
@ -382,7 +342,6 @@ public class DanaRKoreanExecutionService extends Service {
}
public boolean extendedBolus(double insulin, int durationInHalfHours) {
connect("extendedBolus");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
@ -392,7 +351,6 @@ public class DanaRKoreanExecutionService extends Service {
}
public boolean extendedBolusStop() {
connect("extendedBolusStop");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
@ -401,12 +359,11 @@ public class DanaRKoreanExecutionService extends Service {
return true;
}
public boolean bolus(double amount, int carbs, Treatment t) {
public boolean bolus(double amount, int carbs, final Treatment t) {
bolusingTreatment = t;
MsgBolusStart start = new MsgBolusStart(amount);
MsgBolusStop stop = new MsgBolusStop(amount, t);
connect("bolus");
if (!isConnected()) return false;
if (carbs > 0) {
@ -414,6 +371,7 @@ public class DanaRKoreanExecutionService extends Service {
}
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
long bolusStart = System.currentTimeMillis();
if (!stop.stopped) {
mSerialIOThread.sendMessage(start);
@ -423,15 +381,56 @@ public class DanaRKoreanExecutionService extends Service {
}
while (!stop.stopped && !start.failed) {
waitMsec(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm
stop.stopped = true;
stop.forced = true;
log.debug("Communication stopped");
}
}
waitMsec(300);
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.t = t;
bolusingEvent.percent = 99;
bolusingTreatment = null;
getPumpStatus();
int speed = 12;
// try to find real amount if bolusing was interrupted or comm failed
if (t.insulin != amount) {
disconnect("bolusingInterrupted");
long bolusDurationInMSec = (long) (amount * speed * 1000);
long expectedEnd = bolusStart + bolusDurationInMSec + 3000;
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
bolusingEvent.status = String.format(MainApp.sResources.getString(R.string.waitingforestimatedbolusend), waitTime / 1000);
MainApp.bus().post(bolusingEvent);
SystemClock.sleep(1000);
}
final Object o = new Object();
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusingInterrupted", new Callback() {
@Override
public void run() {
if (danaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old
t.insulin = danaRPump.lastBolusAmount;
log.debug("Used bolus amount from history: " + danaRPump.lastBolusAmount);
} else {
log.debug("Bolus amount in history too old: " + danaRPump.lastBolusTime.toLocaleString());
}
o.notify();
}
});
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusOK", null);
}
return true;
}
@ -452,7 +451,6 @@ public class DanaRKoreanExecutionService extends Service {
}
public boolean carbsEntry(int amount) {
connect("carbsEntry");
if (!isConnected()) return false;
MsgSetCarbsEntry msg = new MsgSetCarbsEntry(System.currentTimeMillis(), amount);
mSerialIOThread.sendMessage(msg);
@ -461,7 +459,6 @@ public class DanaRKoreanExecutionService extends Service {
public PumpEnactResult loadHistory(byte type) {
PumpEnactResult result = new PumpEnactResult();
connect("loadHistory");
if (!isConnected()) return result;
MessageBase msg = null;
switch (type) {
@ -508,7 +505,6 @@ public class DanaRKoreanExecutionService extends Service {
}
public boolean updateBasalsInPump(final Profile profile) {
connect("updateBasalsInPump");
if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = DanaRPump.buildDanaRProfileRecord(profile);