most danar code there

This commit is contained in:
Milos Kozak 2016-07-10 15:05:13 +02:00
parent f8ac10cddc
commit 143d347841
31 changed files with 1265 additions and 299 deletions

View file

@ -37,7 +37,7 @@
<ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" /> <ConfirmationsSetting value="0" id="Remove" />
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">

View file

@ -26,6 +26,7 @@ public class Config {
public static final boolean logConstraintsChanges = true; public static final boolean logConstraintsChanges = true;
public static final boolean logTempBasalsCut = true; public static final boolean logTempBasalsCut = true;
public static final boolean logNSUpload = true; public static final boolean logNSUpload = true;
public static final boolean logPumpActions = true;
// DanaR specific // DanaR specific
public static final boolean logDanaBTComm = true; public static final boolean logDanaBTComm = true;

View file

@ -70,10 +70,14 @@ public class TempBasal {
Double basalRate = profile.getBasal(profile.secondsFromMidnight(time)); Double basalRate = profile.getBasal(profile.secondsFromMidnight(time));
Double tempBolusSize = 0.05; Double tempBolusSize = 0.05;
if (this.isAbsolute) { if (isExtended) {
netBasalRate = this.absolute - basalRate; netBasalRate = this.absolute;
} else { } else {
netBasalRate = (this.percent - 100) / 100d * basalRate; if (this.isAbsolute) {
netBasalRate = this.absolute - basalRate;
} else {
netBasalRate = (this.percent - 100) / 100d * basalRate;
}
} }
result.netRatio = netBasalRate; result.netRatio = netBasalRate;

View file

@ -15,8 +15,6 @@ public interface ConstraintsInterface {
boolean isAMAModeEnabled(); boolean isAMAModeEnabled();
APSResult applyBasalConstraints(APSResult request);
Double applyBasalConstraints(Double absoluteRate); Double applyBasalConstraints(Double absoluteRate);
Integer applyBasalConstraints(Integer percentRate); Integer applyBasalConstraints(Integer percentRate);

View file

@ -15,9 +15,6 @@ public interface PumpInterface {
boolean isTempBasalInProgress(); boolean isTempBasalInProgress();
boolean isExtendedBoluslInProgress(); boolean isExtendedBoluslInProgress();
Integer getBatteryPercent();
Integer getReservoirValue();
// Upload to pump new basal profile // Upload to pump new basal profile
void setNewBasalProfile(NSProfile profile); void setNewBasalProfile(NSProfile profile);

View file

@ -166,7 +166,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainActivity.getSpecificPluginsList(PluginBase.APS)); apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainActivity.getSpecificPluginsList(PluginBase.APS));
apsListView.setAdapter(apsDataAdapter); apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView); setListViewHeightBasedOnChildren(apsListView);
constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainActivity.getSpecificPluginsList(PluginBase.CONSTRAINTS)); constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainActivity.getSpecificPluginsListByInterface(ConstraintsInterface.class));
constraintsListView.setAdapter(constraintsDataAdapter); constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView); setListViewHeightBasedOnChildren(constraintsListView);
generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainActivity.getSpecificPluginsList(PluginBase.GENERAL)); generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainActivity.getSpecificPluginsList(PluginBase.GENERAL));
@ -234,16 +234,6 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
return activePump.isExtendedBoluslInProgress(); return activePump.isExtendedBoluslInProgress();
} }
@Override
public Integer getBatteryPercent() {
return activePump.getBatteryPercent();
}
@Override
public Integer getReservoirValue() {
return activePump.getReservoirValue();
}
@Override @Override
public void setNewBasalProfile(NSProfile profile) { public void setNewBasalProfile(NSProfile profile) {
activePump.setNewBasalProfile(profile); activePump.setNewBasalProfile(profile);
@ -309,7 +299,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) { public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
Double rateAfterConstraints = applyBasalConstraints(absoluteRate); Double rateAfterConstraints = applyBasalConstraints(absoluteRate);
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes); PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes);
if (result.enacted) { if (result.enacted && result.success) {
uploadTempBasalStartAbsolute(result.absolute, result.duration); uploadTempBasalStartAbsolute(result.absolute, result.duration);
MainApp.bus().post(new EventTempBasalChange()); MainApp.bus().post(new EventTempBasalChange());
} }
@ -327,7 +317,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
Integer percentAfterConstraints = applyBasalConstraints(percent); Integer percentAfterConstraints = applyBasalConstraints(percent);
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes); PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (result.enacted) { if (result.enacted && result.success) {
uploadTempBasalStartPercent(result.percent, result.duration); uploadTempBasalStartPercent(result.percent, result.duration);
MainApp.bus().post(new EventTempBasalChange()); MainApp.bus().post(new EventTempBasalChange());
} }
@ -338,7 +328,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
Double rateAfterConstraints = applyBolusConstraints(insulin); Double rateAfterConstraints = applyBolusConstraints(insulin);
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes); PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (result.enacted) { if (result.enacted && result.success) {
uploadExtendedBolus(result.bolusDelivered, result.duration); uploadExtendedBolus(result.bolusDelivered, result.duration);
MainApp.bus().post(new EventTreatmentChange()); MainApp.bus().post(new EventTreatmentChange());
} }
@ -348,7 +338,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
@Override @Override
public PumpEnactResult cancelTempBasal() { public PumpEnactResult cancelTempBasal() {
PumpEnactResult result = activePump.cancelTempBasal(); PumpEnactResult result = activePump.cancelTempBasal();
if (result.enacted) { if (result.enacted && result.success) {
uploadTempBasalEnd(); uploadTempBasalEnd();
MainApp.bus().post(new EventTempBasalChange()); MainApp.bus().post(new EventTempBasalChange());
} }
@ -366,7 +356,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
* @param request * @param request
* @return * @return
*/ */
// TODO: logging all actions in configbuilder
public PumpEnactResult applyAPSRequest(APSResult request) { public PumpEnactResult applyAPSRequest(APSResult request) {
request.rate = applyBasalConstraints(request.rate); request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result = null; PumpEnactResult result = null;
@ -386,9 +376,9 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
result.comment = "Basal set correctly"; result.comment = "Basal set correctly";
result.success = true; result.success = true;
} }
} else if (isTempBasalInProgress() && request.rate == getTempBasalAbsoluteRate()) { } else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRate()) < 0.05) {
result = new PumpEnactResult(); result = new PumpEnactResult();
result.absolute = request.rate; result.absolute = getTempBasalAbsoluteRate();
result.duration = activePump.getTempBasal().getPlannedRemainingMinutes(); result.duration = activePump.getTempBasal().getPlannedRemainingMinutes();
result.enacted = false; result.enacted = false;
result.comment = "Temp basal set correctly"; result.comment = "Temp basal set correctly";
@ -779,17 +769,6 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
return result; return result;
} }
@Override
public APSResult applyBasalConstraints(APSResult result) {
ArrayList<PluginBase> constraintsPlugins = MainActivity.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled()) continue;
constrain.applyBasalConstraints(result);
}
return result;
}
@Override @Override
public Double applyBasalConstraints(Double absoluteRate) { public Double applyBasalConstraints(Double absoluteRate) {
Double rateAfterConstrain = absoluteRate; Double rateAfterConstrain = absoluteRate;
@ -797,7 +776,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
for (PluginBase p : constraintsPlugins) { for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p; ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled()) continue; if (!p.isEnabled()) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(rateAfterConstrain), rateAfterConstrain); rateAfterConstrain = Math.min(constrain.applyBasalConstraints(absoluteRate), rateAfterConstrain);
} }
return rateAfterConstrain; return rateAfterConstrain;
} }
@ -809,7 +788,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
for (PluginBase p : constraintsPlugins) { for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p; ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled()) continue; if (!p.isEnabled()) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(rateAfterConstrain), rateAfterConstrain); rateAfterConstrain = Math.min(constrain.applyBasalConstraints(percentRate), rateAfterConstrain);
} }
return rateAfterConstrain; return rateAfterConstrain;
} }
@ -821,7 +800,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
for (PluginBase p : constraintsPlugins) { for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p; ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled()) continue; if (!p.isEnabled()) continue;
insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulinAfterConstrain), insulinAfterConstrain); insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulin), insulinAfterConstrain);
} }
return insulinAfterConstrain; return insulinAfterConstrain;
} }
@ -833,7 +812,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
for (PluginBase p : constraintsPlugins) { for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p; ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled()) continue; if (!p.isEnabled()) continue;
carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbsAfterConstrain), carbsAfterConstrain); carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbs), carbsAfterConstrain);
} }
return carbsAfterConstrain; return carbsAfterConstrain;
} }
@ -845,7 +824,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI
for (PluginBase p : constraintsPlugins) { for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p; ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled()) continue; if (!p.isEnabled()) continue;
maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIobAfterConstrain), maxIobAfterConstrain); maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIob), maxIobAfterConstrain);
} }
return maxIobAfterConstrain; return maxIobAfterConstrain;
} }

View file

@ -43,6 +43,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.plugins.DanaR.comm.*; import info.nightscout.androidaps.plugins.DanaR.comm.*;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -85,7 +86,7 @@ public class DanaConnection {
mHandlerThread = new HandlerThread(DanaConnection.class.getSimpleName()); mHandlerThread = new HandlerThread(DanaConnection.class.getSimpleName());
mHandlerThread.start(); mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper()); mHandler = new Handler(mHandlerThread.getLooper());
getSelectedPump(); getSelectedPump();
this.mBus = bus; this.mBus = bus;
@ -167,6 +168,10 @@ public class DanaConnection {
timeToConnectTimeSoFar = (System.currentTimeMillis() - startTime) / 1000; timeToConnectTimeSoFar = (System.currentTimeMillis() - startTime) / 1000;
mBus.post(new EventDanaRConnectionStatus(true, false, connectionAttemptCount)); mBus.post(new EventDanaRConnectionStatus(true, false, connectionAttemptCount));
connectBT(); connectBT();
if (isConnected()) {
mBus.post(new EventDanaRConnectionStatus(false, true, 0));
break;
}
if (Config.logDanaBTComm) if (Config.logDanaBTComm)
log.debug("connectIfNotConnected waiting " + timeToConnectTimeSoFar + "s attempts:" + connectionAttemptCount + " caller:" + callerName); log.debug("connectIfNotConnected waiting " + timeToConnectTimeSoFar + "s attempts:" + connectionAttemptCount + " caller:" + callerName);
connectionAttemptCount++; connectionAttemptCount++;
@ -180,6 +185,7 @@ public class DanaConnection {
} }
if (Config.logDanaBTComm) if (Config.logDanaBTComm)
log.debug("connectIfNotConnected took " + timeToConnectTimeSoFar + "s attempts:" + connectionAttemptCount); log.debug("connectIfNotConnected took " + timeToConnectTimeSoFar + "s attempts:" + connectionAttemptCount);
pingStatus();
} else { } else {
mBus.post(new EventDanaRConnectionStatus(false, true, 0)); mBus.post(new EventDanaRConnectionStatus(false, true, 0));
} }
@ -222,11 +228,6 @@ public class DanaConnection {
mRfcommSocket = null; mRfcommSocket = null;
} }
} }
if (isConnected()) {
mBus.post(new EventDanaRConnectionStatus(false, true, 0));
pingStatus();
}
} }
public void scheduleDisconnection() { public void scheduleDisconnection() {
@ -243,11 +244,16 @@ public class DanaConnection {
if (scheduledDisconnection != null) if (scheduledDisconnection != null)
scheduledDisconnection.cancel(false); scheduledDisconnection.cancel(false);
Runnable task = new DisconnectRunnable(); Runnable task = new DisconnectRunnable();
scheduledDisconnection = worker.schedule(task, 3, TimeUnit.SECONDS); final int sec = 3;
scheduledDisconnection = worker.schedule(task, sec, TimeUnit.SECONDS);
//if (Config.logDanaBTComm)
// log.debug("Disconnection scheduled in " + sec + "secs");
} }
public void disconnect(String from) { public void disconnect(String from) {
if (mRfcommSocket.isConnected()) { if (mRfcommSocket.isConnected()) {
if (Config.logDanaBTComm)
log.debug("Disconnecting " + from);
try { try {
mInputStream.close(); mInputStream.close();
} catch (Exception e) { } catch (Exception e) {
@ -263,8 +269,6 @@ public class DanaConnection {
} catch (Exception e) { } catch (Exception e) {
log.debug(e.getMessage()); log.debug(e.getMessage());
} }
if (Config.logDanaBTComm)
log.debug("Disconnecting " + from);
} else { } else {
if (Config.logDanaBTComm) if (Config.logDanaBTComm)
log.debug("Already disconnected " + from); log.debug("Already disconnected " + from);
@ -283,10 +287,10 @@ public class DanaConnection {
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(); MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended();
mSerialEngine.sendMessage(tempStatusMsg); // do this before statusBasic because here is temp duration
mSerialEngine.sendMessage(exStatusMsg);
mSerialEngine.sendMessage(statusMsg); mSerialEngine.sendMessage(statusMsg);
mSerialEngine.sendMessage(statusBasicMsg); mSerialEngine.sendMessage(statusBasicMsg);
mSerialEngine.sendMessage(tempStatusMsg);
mSerialEngine.sendMessage(exStatusMsg);
if (danaRPump.isNewPump) { if (danaRPump.isNewPump) {
mSerialEngine.sendMessage(new MsgSettingShippingInfo()); mSerialEngine.sendMessage(new MsgSettingShippingInfo());
@ -316,117 +320,47 @@ public class DanaConnection {
pingStatus(); pingStatus();
return; return;
} }
/* TODO
statusEvent.timeLastSync = statusEvent.time;
if (statusEvent.tempBasalInProgress) { Date now = new Date();
try { if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime()) {
mSerialEngine.sendMessage(new MsgSettingShippingInfo());
Dao<TempBasal, Long> daoTempBasals = MainApp.getDbHelper().getDaoTempBasals(); mSerialEngine.sendMessage(new MsgSettingActiveProfile());
//0x3203
TempBasal tempBasal = new TempBasal(); mSerialEngine.sendMessage(new MsgSettingBasal());
tempBasal.duration = statusEvent.tempBasalTotalSec / 60; //0x3201
tempBasal.percent = statusEvent.tempBasalRatio; mSerialEngine.sendMessage(new MsgSettingMaxValues());
tempBasal.timeStart = statusEvent.tempBasalStart; mSerialEngine.sendMessage(new MsgSettingGlucose());
tempBasal.timeEnd = null; mSerialEngine.sendMessage(new MsgSettingPumpTime());
tempBasal.baseRatio = (int) (statusEvent.currentBasal * 100); mSerialEngine.sendMessage(new MsgSettingActiveProfile());
tempBasal.tempRatio = (int) (statusEvent.currentBasal * 100 * statusEvent.tempBasalRatio / 100d); mSerialEngine.sendMessage(new MsgSettingProfileRatios());
tempBasal.isExtended = false; danaRPump.lastSettingsRead = now;
// log.debug("TempBasal in progress record "+tempBasal);
daoTempBasals.createOrUpdate(tempBasal);
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
} else {
try {
Dao<TempBasal, Long> daoTempBasals = MainApp.getDbHelper().getDaoTempBasals();
TempBasal tempBasalLast = getTempBasalLast(daoTempBasals, false);
if (tempBasalLast != null) {
// log.debug("tempBasalLast " + tempBasalLast);
if (tempBasalLast.timeEnd == null || tempBasalLast.timeEnd.getTime() > new Date().getTime()) {
tempBasalLast.timeEnd = new Date();
if (tempBasalLast.timeEnd.getTime() > tempBasalLast.getPlannedTimeEnd().getTime()) {
tempBasalLast.timeEnd = tempBasalLast.getPlannedTimeEnd();
}
// log.debug("tempBasalLast updated to " + tempBasalLast);
daoTempBasals.update(tempBasalLast);
}
}
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
} }
if (statusEvent.isExtendedInProgress) { danaRPump.lastConnection = now;
try { mBus.post(new EventDanaRNewStatus());
Dao<TempBasal, Long> daoTempBasals = MainApp.getDbHelper().getDaoTempBasals();
TempBasal tempBasal = new TempBasal();
tempBasal.duration = statusEvent.extendedBolusMinutes;
tempBasal.percent = (int) ((statusEvent.extendedBolusAbsoluteRate + statusEvent.currentBasal) / statusEvent.currentBasal * 100);
tempBasal.timeStart = statusEvent.extendedBolusStart;
tempBasal.timeEnd = null;
tempBasal.baseRatio = (int) (statusEvent.currentBasal * 100);
tempBasal.tempRatio = (int) (statusEvent.extendedBolusAbsoluteRate * 100 + statusEvent.currentBasal * 100);
tempBasal.isExtended = true;
// log.debug("TempBasal Extended in progress record "+tempBasal);
daoTempBasals.createOrUpdate(tempBasal);
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
} else {
try {
Dao<TempBasal, Long> daoTempBasals = MainApp.getDbHelper().getDaoTempBasals();
TempBasal tempBasalLast = getTempBasalLast(daoTempBasals, true);
if (tempBasalLast != null) {
log.debug("tempBasalLast Extended " + tempBasalLast);
if (tempBasalLast.timeEnd == null || tempBasalLast.timeEnd.getTime() > new Date().getTime()) {
tempBasalLast.timeEnd = new Date();
if (tempBasalLast.timeEnd.getTime() > tempBasalLast.getPlannedTimeEnd().getTime()) {
tempBasalLast.timeEnd = tempBasalLast.getPlannedTimeEnd();
}
// log.debug("tempBasalLast Extended updated to " + tempBasalLast);
daoTempBasals.update(tempBasalLast);
}
}
} catch (SQLException e) {
log.error(e.getMessage(), e);
}
}
synchronized (this) {
this.notify();
}
mBus.post(statusEvent);
*/
} catch (Exception e) { } catch (Exception e) {
log.error("err", e); log.error("err", e);
} }
} }
public void tempBasal(int percent, int durationInHours) { public void tempBasal(int percent, int durationInHours) {
MsgSetTempBasalStart msg = new MsgSetTempBasalStart(percent, durationInHours); mSerialEngine.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialEngine.sendMessage(msg); mSerialEngine.sendMessage(new MsgStatusTempBasal());
pingStatus();
} }
public void tempBasalStop() { public void tempBasalStop() {
MsgSetTempBasalStop msg = new MsgSetTempBasalStop(); mSerialEngine.sendMessage(new MsgSetTempBasalStop());
mSerialEngine.sendMessage(msg); mSerialEngine.sendMessage(new MsgStatusTempBasal());
pingStatus();
} }
public void extendedBolus(double rate, int durationInHalfHours) { public void extendedBolus(double insulin, int durationInHalfHours) {
MsgSetExtendedBolusStart msgStartExt = new MsgSetExtendedBolusStart(rate / 2 * durationInHalfHours, (byte) (durationInHalfHours & 0xFF)); mSerialEngine.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialEngine.sendMessage(msgStartExt); mSerialEngine.sendMessage(new MsgStatusBolusExtended());
pingStatus();
} }
public void extendedBolusStop() { public void extendedBolusStop() {
MsgSetExtendedBolusStop msg = new MsgSetExtendedBolusStop(); mSerialEngine.sendMessage(new MsgSetExtendedBolusStop());
mSerialEngine.sendMessage(msg); mSerialEngine.sendMessage(new MsgStatusBolusExtended());
pingStatus();
} }
public void stop() { public void stop() {
@ -489,7 +423,6 @@ public class DanaConnection {
public void updateBasalsInPump(final NSProfile profile) { public void updateBasalsInPump(final NSProfile profile) {
double[] basal = buildDanaRProfileRecord(profile); double[] basal = buildDanaRProfileRecord(profile);
connectIfNotConnected("updateBasalsInPump");
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialEngine.sendMessage(msgSet); mSerialEngine.sendMessage(msgSet);
MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0); MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0);

View file

@ -2,9 +2,11 @@ package info.nightscout.androidaps.plugins.DanaR;
import android.app.Activity; import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@ -13,20 +15,38 @@ import android.widget.TextView;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTempBasalStop;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round;
import info.nightscout.utils.SetWarnColor;
public class DanaRFragment extends Fragment implements PluginBase, PumpInterface { public class DanaRFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(DanaRFragment.class); private static Logger log = LoggerFactory.getLogger(DanaRFragment.class);
Handler mHandler; Handler mHandler;
@ -34,11 +54,25 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
private static DanaConnection sDanaConnection = null; private static DanaConnection sDanaConnection = null;
private static DanaRPump sDanaRPump = new DanaRPump(); private static DanaRPump sDanaRPump = new DanaRPump();
private static boolean useExtendedBoluses = false;
boolean fragmentEnabled = true; boolean fragmentEnabled = true;
boolean fragmentVisible = true; boolean fragmentVisible = true;
boolean visibleNow = false; boolean visibleNow = false;
TextView connectionText; Handler loopHandler = new Handler();
Runnable refreshLoop = null;
TextView lastConnectionView;
TextView btConnectionView;
TextView lastBolusView;
TextView dailyUnitsView;
TextView basaBasalRateView;
TextView tempBasalView;
TextView extendedBolusView;
TextView batteryView;
TextView reservoirView;
TextView iobView;
public static DanaConnection getDanaConnection() { public static DanaConnection getDanaConnection() {
return sDanaConnection; return sDanaConnection;
@ -53,6 +87,8 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
} }
public DanaRFragment() { public DanaRFragment() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false);
mHandlerThread = new HandlerThread(DanaRFragment.class.getSimpleName()); mHandlerThread = new HandlerThread(DanaRFragment.class.getSimpleName());
mHandlerThread.start(); mHandlerThread.start();
@ -77,27 +113,59 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (refreshLoop == null) {
refreshLoop = new Runnable() {
@Override
public void run() {
if (visibleNow) {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
updateGUI();
}
});
}
loopHandler.postDelayed(refreshLoop, 60 * 1000l);
}
};
loopHandler.postDelayed(refreshLoop, 60 * 1000l);
}
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.danar_fragment, container, false); View view = inflater.inflate(R.layout.danar_fragment, container, false);
connectionText = (TextView) view.findViewById(R.id.danar_connection); btConnectionView = (TextView) view.findViewById(R.id.danar_btconnection);
connectionText.setOnClickListener(new View.OnClickListener() { lastConnectionView = (TextView) view.findViewById(R.id.danar_lastconnection);
lastBolusView = (TextView) view.findViewById(R.id.danar_lastbolus);
dailyUnitsView = (TextView) view.findViewById(R.id.danar_dailyunits);
basaBasalRateView = (TextView) view.findViewById(R.id.danar_basabasalrate);
tempBasalView = (TextView) view.findViewById(R.id.danar_tempbasal);
extendedBolusView = (TextView) view.findViewById(R.id.danar_extendedbolus);
batteryView = (TextView) view.findViewById(R.id.danar_battery);
reservoirView = (TextView) view.findViewById(R.id.danar_reservoir);
iobView = (TextView) view.findViewById(R.id.danar_iob);
btConnectionView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
mHandler.post(new Runnable() { mHandler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
if (getDanaConnection() != null) if (getDanaConnection() != null)
getDanaConnection().connectIfNotConnected("Connect request from GUI"); getDanaConnection().connectIfNotConnected("Connect request from GUI");
else else
log.error("Connect req from GUI: getDanaConnection() is null"); log.error("Connect req from GUI: getDanaConnection() is null");
}} }
}
); );
} }
}); });
updateGUI();
return view; return view;
} }
@ -109,12 +177,12 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
@Override @Override
public void run() { public void run() {
if (c.sConnecting) { if (c.sConnecting) {
connectionText.setText("{fa-bluetooth-b spin} " + c.sConnectionAttemptNo); btConnectionView.setText("{fa-bluetooth-b spin} " + c.sConnectionAttemptNo);
} else { } else {
if (c.sConnected) { if (c.sConnected) {
connectionText.setText("{fa-bluetooth}"); btConnectionView.setText("{fa-bluetooth}");
} else { } else {
connectionText.setText("{fa-bluetooth-b}"); btConnectionView.setText("{fa-bluetooth-b}");
} }
} }
} }
@ -123,6 +191,28 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
} }
} }
@Subscribe
public void onStatusEvent(final EventDanaRNewStatus s) {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange s) {
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange s) {
boolean previousValue = useExtendedBoluses;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false);
if (useExtendedBoluses != previousValue && isExtendedBoluslInProgress()) {
getDanaConnection().connectIfNotConnected("EventPreferenceChange");
getDanaConnection().extendedBolusStop();
}
updateGUI();
}
// Plugin base interface // Plugin base interface
@Override @Override
public int getType() { public int getType() {
@ -162,94 +252,556 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
// Pump interface // Pump interface
@Override @Override
public boolean isTempBasalInProgress() { public boolean isTempBasalInProgress() {
if (getRealTempBasal() != null) return true;
if (getExtendedBolus() != null && useExtendedBoluses) return true;
return false; return false;
} }
public boolean isRealTempBasalInProgress() {
return getRealTempBasal() != null; //TODO: crosscheck here
}
@Override @Override
public boolean isExtendedBoluslInProgress() { public boolean isExtendedBoluslInProgress() {
return false; return getExtendedBolus() != null; //TODO: crosscheck here
}
@Override
public Integer getBatteryPercent() {
return null;
}
@Override
public Integer getReservoirValue() {
return null;
} }
@Override @Override
public void setNewBasalProfile(NSProfile profile) { public void setNewBasalProfile(NSProfile profile) {
if (getDanaConnection() != null) {
getDanaConnection().connectIfNotConnected("setNewBasalProfile");
getDanaConnection().updateBasalsInPump(profile);
}
} }
@Override @Override
public double getBaseBasalRate() { public double getBaseBasalRate() {
return 0; return getDanaRPump().currentBasal;
} }
@Override @Override
public double getTempBasalAbsoluteRate() { public double getTempBasalAbsoluteRate() {
if (isRealTempBasalInProgress()) {
if (getRealTempBasal().isAbsolute) {
return getRealTempBasal().absolute;
} else {
Double baseRate = getBaseBasalRate();
Double tempRate = baseRate * (getRealTempBasal().percent / 100d);
return baseRate + tempRate;
}
}
if (isExtendedBoluslInProgress() && useExtendedBoluses) {
return getBaseBasalRate() + getExtendedBolus().absolute;
}
return 0; return 0;
} }
@Override @Override
public double getTempBasalRemainingMinutes() { public double getTempBasalRemainingMinutes() {
if (isRealTempBasalInProgress())
return getRealTempBasal().getPlannedRemainingMinutes();
if (isExtendedBoluslInProgress() && useExtendedBoluses)
return getExtendedBolus().getPlannedRemainingMinutes();
return 0; return 0;
} }
@Override @Override
public TempBasal getTempBasal() { public TempBasal getTempBasal() {
if (isRealTempBasalInProgress())
return getRealTempBasal();
if (isExtendedBoluslInProgress() && useExtendedBoluses)
return getExtendedBolus();
return null; return null;
} }
public TempBasal getRealTempBasal() {
return MainApp.getConfigBuilder().getActiveTempBasals().getTempBasal(new Date());
}
@Override @Override
public TempBasal getExtendedBolus() { public TempBasal getExtendedBolus() {
return null; return MainApp.getConfigBuilder().getActiveTempBasals().getExtendedBolus(new Date());
} }
@Override @Override
public PumpEnactResult deliverTreatment(Double insulin, Integer carbs) { public PumpEnactResult deliverTreatment(Double insulin, Integer carbs) {
return null; ConfigBuilderFragment configBuilderFragment = MainApp.getConfigBuilder();
insulin = configBuilderFragment.applyBolusConstraints(insulin);
if (insulin > 0 || carbs > 0) {
getDanaConnection().connectIfNotConnected("deliverTreatment");
Treatment t = new Treatment();
t.insulin = insulin;
if (insulin > 0) getDanaConnection().bolus(insulin, t);
if (carbs > 0) getDanaConnection().carbsEntry(carbs);
PumpEnactResult result = new PumpEnactResult();
result.success = true;
result.bolusDelivered = t.insulin;
result.carbsDelivered = carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + insulin + " Delivered: " + result.bolusDelivered);
return result;
} else {
PumpEnactResult result = new PumpEnactResult();
result.success = false;
result.bolusDelivered = 0d;
result.carbsDelivered = 0;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input");
return result;
}
} }
// This is called from APS
@Override @Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) { public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
return null; PumpEnactResult result = new PumpEnactResult();
ConfigBuilderFragment configBuilderFragment = MainApp.getConfigBuilder();
absoluteRate = configBuilderFragment.applyBasalConstraints(absoluteRate);
final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d;
final boolean doLowTemp = absoluteRate < getBaseBasalRate();
final boolean doHighTemp = absoluteRate > getBaseBasalRate() && !useExtendedBoluses;
final boolean doExtendedTemp = absoluteRate > getBaseBasalRate() && useExtendedBoluses;
if (doTempOff) {
// If extended in progress
if (isExtendedBoluslInProgress() && useExtendedBoluses) {
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Stopping extended bolus (doTempOff)");
return cancelExtendedBolus();
}
// If temp in progress
if (isRealTempBasalInProgress()) {
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)");
return cancelRealTempBasal();
}
result.success = true;
result.enacted = false;
result.percent = 100;
result.isPercent = true;
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: doTempOff OK");
return result;
}
if (doLowTemp || doHighTemp) {
Integer percentRate = new Double(absoluteRate / getBaseBasalRate() * 100).intValue();
if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue();
else percentRate = Round.floorTo((double) percentRate, 10d).intValue();
if (percentRate > 200) {
percentRate = 200;
}
// If extended in progress
if (isExtendedBoluslInProgress() && useExtendedBoluses) {
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)");
result = cancelExtendedBolus();
if (!result.success) {
log.error("setTempBasalAbsolute: Failed to stop previous extended bolus (doLowTemp || doHighTemp)");
return result;
}
}
// Check if some temp is already in progress
if (isRealTempBasalInProgress()) {
// Correct basal already set ?
if (getRealTempBasal().percent == percentRate) {
result.success = true;
result.percent = percentRate;
result.absolute = getTempBasalAbsoluteRate();
result.enacted = false;
result.duration = ((Double) getTempBasalRemainingMinutes()).intValue();
result.isPercent = true;
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)");
return result;
} else {
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Stopping temp basal (doLowTemp || doHighTemp)");
result = cancelRealTempBasal();
// Check for proper result
if (!result.success) {
log.error("setTempBasalAbsolute: Failed to stop previous temp basal (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)");
return setTempBasalPercent(percentRate, durationInMinutes);
}
if (doExtendedTemp) {
// Check if some temp is already in progress
if (isRealTempBasalInProgress()) {
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Stopping temp basal (doExtendedTemp)");
result = cancelRealTempBasal();
// Check for proper result
if (!result.success) {
log.error("setTempBasalAbsolute: Failed to stop previous temp basal (doExtendedTemp)");
return result;
}
}
// Calculate # of halfHours from minutes
Integer durationInHalfHours = Math.max(durationInMinutes / 30, 1);
// We keep current basal running so need to sub current basal
Double extendedRateToSet = absoluteRate - getBaseBasalRate();
extendedRateToSet = configBuilderFragment.applyBasalConstraints(extendedRateToSet);
// needs to be rounded to 0.1
extendedRateToSet = Round.roundTo(extendedRateToSet, 0.1d);
// What is current rate of extended bolusing in u/h?
if (Config.logPumpActions) {
log.debug("setTempBasalAbsolute: Extended bolus in progress: " + isExtendedBoluslInProgress() + " rate: " + getDanaRPump().extendedBolusAbsoluteRate + "U/h duration remaining: " + getDanaRPump().extendedBolusRemainingMinutes + "min");
log.debug("setTempBasalAbsolute: Rate to set: " + extendedRateToSet + "U/h");
}
// Compare with extended rate in progress
if (Math.abs(getDanaRPump().extendedBolusAbsoluteRate - extendedRateToSet) < 0.02D) { // Allow some rounding diff
// correct extended already set
result.success = true;
result.absolute = getDanaRPump().extendedBolusAbsoluteRate;
result.enacted = false;
result.duration = getDanaRPump().extendedBolusRemainingMinutes;
result.isPercent = false;
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Correct extended already set");
return result;
}
// Now set new extended, no need to to stop previous (if running) because it's replaced
Double extendedAmount = extendedRateToSet / 2 * durationInHalfHours;
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Setting extended: " + extendedAmount + "U halfhours: " + durationInHalfHours);
result = setExtendedBolus(extendedAmount, durationInMinutes);
if (!result.success) {
log.error("setTempBasalAbsolute: Failed to set extended bolus");
return result;
}
if (Config.logPumpActions)
log.debug("setTempBasalAbsolute: Extended bolus set ok");
return result;
}
// We should never end here
log.error("setTempBasalAbsolute: Internal error");
result.success = false;
result.comment = "Internal error";
return result;
} }
@Override @Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
return null; PumpEnactResult result = new PumpEnactResult();
ConfigBuilderFragment configBuilderFragment = MainApp.getConfigBuilder();
percent = configBuilderFragment.applyBasalConstraints(percent);
if (percent < 0) {
result.enacted = false;
result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("setTempBasalPercent: Invalid input");
return result;
}
if (percent > 200) percent = 200;
if (getDanaRPump().isTempBasalInProgress && getDanaRPump().tempBasalPercent == percent) {
result.enacted = false;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.duration = getDanaRPump().tempBasalRemainingMin;
result.percent = getDanaRPump().tempBasalPercent;
result.isPercent = true;
if (Config.logPumpActions)
log.debug("setTempBasalPercent: Correct value already set");
return result;
}
getDanaConnection().connectIfNotConnected("setTempBasalPercent");
int durationInHours = Math.max(durationInMinutes / 60, 1);
getDanaConnection().tempBasal(percent, durationInHours);
if (getDanaRPump().isTempBasalInProgress && getDanaRPump().tempBasalPercent == percent) {
result.enacted = true;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.duration = getDanaRPump().tempBasalRemainingMin;
result.percent = getDanaRPump().tempBasalPercent;
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.danar_valuenotsetproperly);
log.error("setTempBasalPercent: Failed to set temp basal");
return result;
} }
@Override @Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
return null; ConfigBuilderFragment configBuilderFragment = MainApp.getConfigBuilder();
insulin = configBuilderFragment.applyBolusConstraints(insulin);
// needs to be rounded to 0.1
insulin = Round.roundTo(insulin, 0.1d);
PumpEnactResult result = new PumpEnactResult();
if (getDanaRPump().isExtendedInProgress && getDanaRPump().extendedBolusAmount - insulin == 0d) {
result.enacted = false;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.duration = getDanaRPump().extendedBolusRemainingMinutes;
result.absolute = getDanaRPump().extendedBolusAbsoluteRate;
result.isPercent = false;
if (Config.logPumpActions)
log.debug("setExtendedBolus: Correct extended bolus already set");
return result;
}
getDanaConnection().connectIfNotConnected("setExtendedBolus");
int durationInHalfHours = Math.max(durationInMinutes / 30, 1);
getDanaConnection().extendedBolus(insulin, durationInHalfHours);
if (getDanaRPump().isExtendedInProgress && getDanaRPump().extendedBolusAmount - insulin == 0) {
result.enacted = true;
result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
result.duration = getDanaRPump().extendedBolusRemainingMinutes;
result.absolute = getDanaRPump().extendedBolusAbsoluteRate;
result.bolusDelivered = getDanaRPump().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 @Override
public PumpEnactResult cancelTempBasal() { public PumpEnactResult cancelTempBasal() {
return null; if (isRealTempBasalInProgress())
return cancelRealTempBasal();
if (isExtendedBoluslInProgress())
return cancelExtendedBolus();
PumpEnactResult result = new PumpEnactResult();
result.success = true;
result.enacted = false;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
return result;
}
public PumpEnactResult cancelRealTempBasal() {
PumpEnactResult result = new PumpEnactResult();
getDanaConnection().connectIfNotConnected("cancelRealTempBasal");
if (getDanaRPump().isTempBasalInProgress) {
getDanaConnection().tempBasalStop();
result.enacted = true;
}
if (!getDanaRPump().isTempBasalInProgress) {
result.success = 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);
log.error("cancelRealTempBasal: Failed to cancel temp basal");
return result;
}
} }
@Override @Override
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
return null; PumpEnactResult result = new PumpEnactResult();
getDanaConnection().connectIfNotConnected("cancelExtendedBolus");
if (getDanaRPump().isExtendedInProgress) {
getDanaConnection().extendedBolusStop();
result.enacted = true;
}
if (!getDanaRPump().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 @Override
public JSONObject getJSONStatus() { public JSONObject getJSONStatus() {
return null; JSONObject pump = new JSONObject();
JSONObject battery = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
try {
battery.put("percent", getDanaRPump().batteryRemaining);
status.put("status", "normal");
status.put("timestamp", DateUtil.toISOString(new Date()));
if (isTempBasalInProgress()) {
extended.put("TempBasalAbsoluteRate", getTempBasalAbsoluteRate());
extended.put("TempBasalStart", DateUtil.toISOString(getTempBasal().timeStart));
extended.put("TempBasalRemaining", getTempBasal().getPlannedRemainingMinutes());
extended.put("IsExtended", getTempBasal().isExtended);
}
extended.put("PumpIOB", getDanaRPump().iob);
extended.put("LastBolus", DateUtil.toISOString(getDanaRPump().lastBolusTime));
extended.put("LastBolusAmount", getDanaRPump().lastBolusAmount);
pump.put("battery", battery);
pump.put("status", status);
pump.put("extended", extended);
pump.put("reservoir", (int) getDanaRPump().reservoirRemainingUnits);
pump.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) {
}
return pump;
} }
@Override @Override
public String deviceID() { public String deviceID() {
return null; return getDanaRPump().serialNumber;
}
// GUI functions
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
visibleNow = true;
updateGUI();
} else
visibleNow = false;
} }
private void updateGUI() { private void updateGUI() {
final DecimalFormat formatNumber0decimalplaces = new DecimalFormat("0");
final DecimalFormat formatNumber1decimalplaces = new DecimalFormat("0.0");
final DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
final DateFormat formatTime = DateFormat.getTimeInstance(DateFormat.SHORT);
Activity activity = getActivity();
if (activity != null && visibleNow && basaBasalRateView != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (getDanaRPump().lastConnection.getTime() != 0) {
Long agoMsec = new Date().getTime() - getDanaRPump().lastConnection.getTime();
int agoMin = (int) (agoMsec / 60d / 1000d);
lastConnectionView.setText(formatTime.format(getDanaRPump().lastConnection) + " (" + agoMin + " " + getString(R.string.minago) + ")");
SetWarnColor.setColor(lastConnectionView, agoMin, 16d, 31d);
}
if (getDanaRPump().lastBolusTime.getTime() != 0) {
Long agoMsec = new Date().getTime() - getDanaRPump().lastBolusTime.getTime();
int agoHours = (int) (agoMsec / 60d / 60d / 1000d);
if (agoHours < 6) // max 6h back
lastBolusView.setText(formatTime.format(getDanaRPump().lastBolusTime) + " (" + formatNumber1decimalplaces.format(agoHours) + " " + getString(R.string.hoursago) + ") " + formatNumber2decimalplaces.format(getDanaRPump().lastBolusAmount) + " U");
else lastBolusView.setText("");
}
dailyUnitsView.setText(formatNumber0decimalplaces.format(getDanaRPump().dailyTotalUnits) + " / " + getDanaRPump().maxDailyTotalUnits + " U");
SetWarnColor.setColor(dailyUnitsView, getDanaRPump().dailyTotalUnits, getDanaRPump().maxDailyTotalUnits * 0.75d, getDanaRPump().maxDailyTotalUnits * 0.9d);
basaBasalRateView.setText("( " + (getDanaRPump().activeProfile + 1) + " ) " + formatNumber2decimalplaces.format(getBaseBasalRate()) + " U/h");
if (isRealTempBasalInProgress()) {
tempBasalView.setText(getRealTempBasal().toString());
} else {
tempBasalView.setText("");
}
if (isExtendedBoluslInProgress()) {
extendedBolusView.setText(getExtendedBolus().toString());
} else {
extendedBolusView.setText("");
}
reservoirView.setText(formatNumber0decimalplaces.format(getDanaRPump().reservoirRemainingUnits) + " / 300 U");
SetWarnColor.setColorInverse(reservoirView, getDanaRPump().reservoirRemainingUnits, 50d, 20d);
batteryView.setText("{fa-battery-" + (getDanaRPump().batteryRemaining / 25) + "}");
SetWarnColor.setColorInverse(reservoirView, getDanaRPump().batteryRemaining, 51d, 26d);
iobView.setText(getDanaRPump().iob + " U");
}
});
} }
/**
* Constraint 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 (getDanaRPump() != null) {
if (absoluteRate > getDanaRPump().maxBasal) {
absoluteRate = getDanaRPump().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 > 200) percentRate = 200;
if (percentRate != origPercentRate && Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit)
log.debug("Limiting percent rate " + origPercentRate + "% to " + percentRate + "%");
return percentRate;
}
@Override
public Double applyBolusConstraints(Double insulin) {
double origInsulin = insulin;
if (getDanaRPump() != null) {
if (insulin > getDanaRPump().maxBolus) {
insulin = getDanaRPump().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;
}
// TODO: daily total constraint
} }

View file

@ -9,6 +9,9 @@ public class DanaRPump {
public static final int UNITS_MGDL = 0; public static final int UNITS_MGDL = 0;
public static final int UNITS_MMOL = 1; public static final int UNITS_MMOL = 1;
Date lastConnection = new Date(0);
Date lastSettingsRead = new Date(0);
// Info // Info
public String serialNumber = ""; public String serialNumber = "";
public Date shippingDate = new Date(0); public Date shippingDate = new Date(0);
@ -68,14 +71,10 @@ public class DanaRPump {
public int nightCF; public int nightCF;
public class PumpProfile {
public double[] basalValue = new double[48];
}
public int activeProfile = 0; public int activeProfile = 0;
public PumpProfile[] pumpProfiles = new PumpProfile[4]; public double[][] pumpProfiles = null;
//Limits //Limits
public double maxBolus; public double maxBolus;
public double maxBasal; public double maxBasal;
public double dailyMax;
} }

View file

@ -6,7 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetExtendedBolusStart extends DanaRMessage { public class MsgSetExtendedBolusStart extends DanaRMessage {
private static Logger log = LoggerFactory.getLogger(MsgBolusStart.class); private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStart.class);
public MsgSetExtendedBolusStart() { public MsgSetExtendedBolusStart() {
SetCommand(0x0407); SetCommand(0x0407);
@ -17,7 +17,7 @@ public class MsgSetExtendedBolusStart extends DanaRMessage {
AddParamInt((int) (amount * 100)); AddParamInt((int) (amount * 100));
AddParamByte(halfhours); AddParamByte(halfhours);
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
log.debug("Set extended bolus start: " + amount + " halfhours " + halfhours); log.debug("Set extended bolus start: " + (((int) (amount * 100)) / 100d) + "U halfhours: " + (int) halfhours);
} }
@Override @Override

View file

@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
@ -17,15 +18,18 @@ public class MsgSettingBasal extends DanaRMessage {
} }
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
DanaRPump pump = DanaRFragment.getDanaRPump();
if (pump.pumpProfiles == null) pump.pumpProfiles = new double[4][];
pump.pumpProfiles[pump.activeProfile] = new double[24];
for (int index = 0; index < 24; index++) { for (int index = 0; index < 24; index++) {
int basal = intFromBuff(bytes, 2 * index, 2); int basal = intFromBuff(bytes, 2 * index, 2);
if (basal < 10) basal = 0; if (basal < 10) basal = 0;
DanaRFragment.getDanaRPump().pumpProfiles[DanaRFragment.getDanaRPump().activeProfile].basalValue[index] = basal / 100d; pump.pumpProfiles[pump.activeProfile][index] = basal / 100d;
} }
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
for (int index = 0; index < 24; index++) { for (int index = 0; index < 24; index++) {
log.debug("Basal " + String.format("%02d", index) + "h: " + DanaRFragment.getDanaRPump().pumpProfiles[DanaRFragment.getDanaRPump().activeProfile].basalValue[index]); log.debug("Basal " + String.format("%02d", index) + "h: " + DanaRFragment.getDanaRPump().pumpProfiles[DanaRFragment.getDanaRPump().activeProfile][index]);
} }
} }
} }

View file

@ -5,10 +5,15 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*
*
* THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE
*
*/ */
public class MsgSettingBasalProfileAll extends DanaRMessage { public class MsgSettingBasalProfileAll extends DanaRMessage {
private static Logger log = LoggerFactory.getLogger(MsgSettingBasalProfileAll.class); private static Logger log = LoggerFactory.getLogger(MsgSettingBasalProfileAll.class);
@ -18,22 +23,29 @@ public class MsgSettingBasalProfileAll extends DanaRMessage {
} }
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
DanaRPump pump = DanaRFragment.getDanaRPump();
if (DanaRFragment.getDanaRPump().basal48Enable) { if (DanaRFragment.getDanaRPump().basal48Enable) {
pump.pumpProfiles = new double[4][];
for (int profile = 0; profile < 4; profile++) { for (int profile = 0; profile < 4; profile++) {
int position = intFromBuff(bytes, 107 * profile, 1); int position = intFromBuff(bytes, 107 * profile, 1);
pump.pumpProfiles[position] = new double[48];
for (int index = 0; index < 48; index++) { for (int index = 0; index < 48; index++) {
int basal = intFromBuff(bytes, 107 * profile + 2 * index + 1, 2); int basal = intFromBuff(bytes, 107 * profile + 2 * index + 1, 2);
if (basal < 10) basal = 0; if (basal < 10) basal = 0;
DanaRFragment.getDanaRPump().pumpProfiles[position].basalValue[index] = basal / 100d; pump.pumpProfiles[position][index] = basal / 100d;
} }
} }
} else { } else {
pump.pumpProfiles = new double[4][];
for (int profile = 0; profile < 4; profile++) { for (int profile = 0; profile < 4; profile++) {
int position = intFromBuff(bytes, 59 * profile, 1); int position = intFromBuff(bytes, 49 * profile, 1);
log.debug("position " + position);
pump.pumpProfiles[position] = new double[24];
for (int index = 0; index < 24; index++) { for (int index = 0; index < 24; index++) {
int basal = intFromBuff(bytes, 59 * profile + 2 * index + 1, 2); int basal = intFromBuff(bytes, 59 * profile + 2 * index + 1, 2);
if (basal < 10) basal = 0; if (basal < 10) basal = 0;
DanaRFragment.getDanaRPump().pumpProfiles[position].basalValue[index] = basal / 100d; log.debug("position " + position + " index " + index);
pump.pumpProfiles[position][index] = basal / 100d;
} }
} }
} }
@ -42,7 +54,7 @@ public class MsgSettingBasalProfileAll extends DanaRMessage {
if (DanaRFragment.getDanaRPump().basal48Enable) { if (DanaRFragment.getDanaRPump().basal48Enable) {
for (int profile = 0; profile < 4; profile++) { for (int profile = 0; profile < 4; profile++) {
for (int index = 0; index < 24; index++) { for (int index = 0; index < 24; index++) {
log.debug("Basal profile " + profile + ": " + String.format("%02d", index) + "h: " + DanaRFragment.getDanaRPump().pumpProfiles[profile].basalValue[index]); log.debug("Basal profile " + profile + ": " + String.format("%02d", index) + "h: " + DanaRFragment.getDanaRPump().pumpProfiles[profile][index]);
} }
} }
} else { } else {
@ -51,7 +63,7 @@ public class MsgSettingBasalProfileAll extends DanaRMessage {
log.debug("Basal profile " + profile + ": " + log.debug("Basal profile " + profile + ": " +
String.format("%02d", (index / 2)) + String.format("%02d", (index / 2)) +
":" + String.format("%02d", (index % 2) * 30) + " : " + ":" + String.format("%02d", (index % 2) * 30) + " : " +
DanaRFragment.getDanaRPump().pumpProfiles[profile].basalValue[index]); DanaRFragment.getDanaRPump().pumpProfiles[profile][index]);
} }
} }
} }

View file

@ -20,12 +20,12 @@ public class MsgSettingMaxValues extends DanaRMessage {
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
DanaRFragment.getDanaRPump().maxBolus = intFromBuff(bytes, 0, 2) / 100d; DanaRFragment.getDanaRPump().maxBolus = intFromBuff(bytes, 0, 2) / 100d;
DanaRFragment.getDanaRPump().maxBasal = intFromBuff(bytes, 2, 2) / 100d; DanaRFragment.getDanaRPump().maxBasal = intFromBuff(bytes, 2, 2) / 100d;
DanaRFragment.getDanaRPump().dailyMax = intFromBuff(bytes, 4, 2) / 100d; DanaRFragment.getDanaRPump().maxDailyTotalUnits = intFromBuff(bytes, 4, 2) / 100;
if (Config.logDanaMessageDetail) { if (Config.logDanaMessageDetail) {
log.debug("Max bolus: " + DanaRFragment.getDanaRPump().maxBolus); log.debug("Max bolus: " + DanaRFragment.getDanaRPump().maxBolus);
log.debug("Max basal: " + DanaRFragment.getDanaRPump().maxBasal); log.debug("Max basal: " + DanaRFragment.getDanaRPump().maxBasal);
log.debug("Max daily max: " + DanaRFragment.getDanaRPump().dailyMax); log.debug("Total daily max units: " + DanaRFragment.getDanaRPump().maxDailyTotalUnits);
} }
} }

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
public class MsgStatusBasic extends DanaRMessage { public class MsgStatusBasic extends DanaRMessage {
private static Logger log = LoggerFactory.getLogger(MsgStatusBasic.class); private static Logger log = LoggerFactory.getLogger(MsgStatusBasic.class);

View file

@ -5,10 +5,16 @@ import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
public class MsgStatusBolusExtended extends DanaRMessage { public class MsgStatusBolusExtended extends DanaRMessage {
private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended.class); private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended.class);
@ -38,6 +44,8 @@ public class MsgStatusBolusExtended extends DanaRMessage {
DanaRFragment.getDanaRPump().extendedBolusStart = extendedBolusStart; DanaRFragment.getDanaRPump().extendedBolusStart = extendedBolusStart;
DanaRFragment.getDanaRPump().extendedBolusRemainingMinutes = extendedBolusRemainingMinutes; DanaRFragment.getDanaRPump().extendedBolusRemainingMinutes = extendedBolusRemainingMinutes;
updateExtendedBolusInDB();
if (Config.logDanaMessageDetail) { if (Config.logDanaMessageDetail) {
log.debug("Is extended bolus running: " + isExtendedInProgress); log.debug("Is extended bolus running: " + isExtendedInProgress);
log.debug("Extended bolus min: " + extendedBolusMinutes); log.debug("Extended bolus min: " + extendedBolusMinutes);
@ -53,4 +61,52 @@ public class MsgStatusBolusExtended extends DanaRMessage {
private Date getDateFromSecAgo(int tempBasalAgoSecs) { private Date getDateFromSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000); return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000);
} }
public static void updateExtendedBolusInDB() {
DanaRFragment danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class);
DanaRPump danaRPump = danaRFragment.getDanaRPump();
Date now = new Date();
try {
if (danaRFragment.isExtendedBoluslInProgress()) {
TempBasal extendedBolus = danaRFragment.getExtendedBolus();
if (danaRPump.isExtendedInProgress) {
if (extendedBolus.absolute != danaRPump.extendedBolusAbsoluteRate) {
// Close current extended
extendedBolus.timeEnd = now;
MainApp.getDbHelper().getDaoTempBasals().update(extendedBolus);
// Create new
TempBasal newExtended = new TempBasal();
newExtended.timeStart = now;
newExtended.absolute = danaRPump.extendedBolusAbsoluteRate;
newExtended.isAbsolute = true;
newExtended.duration = danaRPump.extendedBolusMinutes;
newExtended.isExtended = true;
MainApp.getDbHelper().getDaoTempBasals().create(newExtended);
MainApp.bus().post(new EventTempBasalChange());
}
} else {
// Close curent temp basal
extendedBolus.timeEnd = now;
MainApp.getDbHelper().getDaoTempBasals().update(extendedBolus);
MainApp.bus().post(new EventTempBasalChange());
}
} else {
if (danaRPump.isExtendedInProgress) {
// Create new
TempBasal newExtended = new TempBasal();
newExtended.timeStart = now;
newExtended.absolute = danaRPump.extendedBolusAbsoluteRate;
newExtended.isAbsolute = true;
newExtended.duration = danaRPump.extendedBolusMinutes;
newExtended.isExtended = true;
MainApp.getDbHelper().getDaoTempBasals().create(newExtended);
MainApp.bus().post(new EventTempBasalChange());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} }

View file

@ -5,10 +5,16 @@ import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
public class MsgStatusTempBasal extends DanaRMessage { public class MsgStatusTempBasal extends DanaRMessage {
private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal.class); private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal.class);
@ -21,7 +27,7 @@ public class MsgStatusTempBasal extends DanaRMessage {
boolean isTempBasalInProgress = intFromBuff(bytes, 0, 1) == 1; boolean isTempBasalInProgress = intFromBuff(bytes, 0, 1) == 1;
int tempBasalPercent = intFromBuff(bytes, 1, 1); int tempBasalPercent = intFromBuff(bytes, 1, 1);
int tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60; int tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60;
int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3); int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3);
int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60; int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60;
Date tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : new Date(0); Date tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : new Date(0);
@ -31,6 +37,8 @@ public class MsgStatusTempBasal extends DanaRMessage {
DanaRFragment.getDanaRPump().tempBasalTotalSec = tempBasalTotalSec; DanaRFragment.getDanaRPump().tempBasalTotalSec = tempBasalTotalSec;
DanaRFragment.getDanaRPump().tempBasalStart = tempBasalStart; DanaRFragment.getDanaRPump().tempBasalStart = tempBasalStart;
updateTempBasalInDB();
if (Config.logDanaMessageDetail) { if (Config.logDanaMessageDetail) {
log.debug("Is temp basal running: " + isTempBasalInProgress); log.debug("Is temp basal running: " + isTempBasalInProgress);
log.debug("Current temp basal percent: " + tempBasalPercent); log.debug("Current temp basal percent: " + tempBasalPercent);
@ -44,4 +52,52 @@ public class MsgStatusTempBasal extends DanaRMessage {
private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) { private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000); return new Date((long) (Math.ceil(new Date().getTime() / 1000d) - tempBasalAgoSecs) * 1000);
} }
public static void updateTempBasalInDB() {
DanaRFragment danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class);
DanaRPump danaRPump = danaRFragment.getDanaRPump();
Date now = new Date();
try {
if (danaRFragment.isRealTempBasalInProgress()) {
TempBasal tempBasal = danaRFragment.getRealTempBasal();
if (danaRPump.isTempBasalInProgress) {
if (tempBasal.percent != danaRPump.tempBasalPercent) {
// Close current temp basal
tempBasal.timeEnd = now;
MainApp.getDbHelper().getDaoTempBasals().update(tempBasal);
// Create new
TempBasal newTempBasal = new TempBasal();
newTempBasal.timeStart = now;
newTempBasal.percent = danaRPump.tempBasalPercent;
newTempBasal.isAbsolute = false;
newTempBasal.duration = danaRPump.tempBasalTotalSec / 60;
newTempBasal.isExtended = false;
MainApp.getDbHelper().getDaoTempBasals().create(newTempBasal);
MainApp.bus().post(new EventTempBasalChange());
}
} else {
// Close current temp basal
tempBasal.timeEnd = now;
MainApp.getDbHelper().getDaoTempBasals().update(tempBasal);
MainApp.bus().post(new EventTempBasalChange());
}
} else {
if (danaRPump.isTempBasalInProgress) {
// Create new
TempBasal newTempBasal = new TempBasal();
newTempBasal.timeStart = now;
newTempBasal.percent = danaRPump.tempBasalPercent;
newTempBasal.isAbsolute = false;
newTempBasal.duration = danaRPump.tempBasalTotalSec / 60;
newTempBasal.isExtended = false;
MainApp.getDbHelper().getDaoTempBasals().create(newTempBasal);
MainApp.bus().post(new EventTempBasalChange());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} }

View file

@ -0,0 +1,7 @@
package info.nightscout.androidaps.plugins.DanaR.events;
/**
* Created by mike on 08.07.2016.
*/
public class EventDanaRNewStatus {
}

View file

@ -263,7 +263,7 @@ public class LoopFragment extends Fragment implements View.OnClickListener, Plug
// check rate for constrais // check rate for constrais
APSResult resultAfterConstraints = result.clone(); APSResult resultAfterConstraints = result.clone();
constraintsInterface.applyBasalConstraints(resultAfterConstraints); resultAfterConstraints.rate = constraintsInterface.applyBasalConstraints(resultAfterConstraints.rate);
if (lastRun == null) lastRun = new LastRun(); if (lastRun == null) lastRun = new LastRun();
lastRun.request = result; lastRun.request = result;
@ -332,7 +332,7 @@ public class LoopFragment extends Fragment implements View.OnClickListener, Plug
requestView.setText(lastRun.request != null ? lastRun.request.toString() : ""); requestView.setText(lastRun.request != null ? lastRun.request.toString() : "");
constraintsProcessedView.setText(lastRun.constraintsProcessed != null ? lastRun.constraintsProcessed.toString() : ""); constraintsProcessedView.setText(lastRun.constraintsProcessed != null ? lastRun.constraintsProcessed.toString() : "");
setByPumpView.setText(lastRun.setByPump != null ? lastRun.setByPump.toString() : ""); setByPumpView.setText(lastRun.setByPump != null ? lastRun.setByPump.toString() : "");
sourceView.setText(lastRun.source != null ? lastRun.source.toString() : ""); sourceView.setText(lastRun.source != null ? lastRun.source : "");
lastRunView.setText(lastRun.lastAPSRun != null && lastRun.lastAPSRun.getTime() != 0 ? lastRun.lastAPSRun.toLocaleString() : ""); lastRunView.setText(lastRun.lastAPSRun != null && lastRun.lastAPSRun.getTime() != 0 ? lastRun.lastAPSRun.toLocaleString() : "");
lastEnactView.setText(lastRun.lastEnact != null && lastRun.lastEnact.getTime() != 0 ? lastRun.lastEnact.toLocaleString() : ""); lastEnactView.setText(lastRun.lastEnact != null && lastRun.lastEnact.getTime() != 0 ? lastRun.lastEnact.toLocaleString() : "");
} }

View file

@ -455,11 +455,6 @@ public class ObjectivesFragment extends Fragment implements View.OnClickListener
} }
} }
@Override
public APSResult applyBasalConstraints(APSResult result) {
return result;
}
@Override @Override
public Double applyBasalConstraints(Double absoluteRate) { public Double applyBasalConstraints(Double absoluteRate) {
return absoluteRate; return absoluteRate;

View file

@ -2,6 +2,9 @@ package info.nightscout.androidaps.plugins.Overview.Dialogs;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -33,6 +36,15 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
PlusMinusEditText editInsulin; PlusMinusEditText editInsulin;
Handler mHandler;
public static HandlerThread mHandlerThread;
public NewExtendedBolusDialog() {
mHandlerThread = new HandlerThread(NewExtendedBolusDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
}
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
@ -48,7 +60,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
h40Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_4h); h40Radio = (RadioButton) view.findViewById(R.id.overview_newextendedbolus_4h);
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit); Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
editInsulin = new PlusMinusEditText(view, R.id.overview_newextendedbolus_insulin, R.id.overview_newextendedbolus_insulin_plus, R.id.overview_newextendedbolus_insulin_minus, 0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false); editInsulin = new PlusMinusEditText(view, R.id.overview_newextendedbolus_insulin, R.id.overview_newextendedbolus_insulin_plus, R.id.overview_newextendedbolus_insulin_minus, 0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false);
okButton.setOnClickListener(this); okButton.setOnClickListener(this);
return view; return view;
@ -71,7 +83,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
Double insulinAfterConstraint = MainApp.getConfigBuilder().applyBolusConstraints(insulin); Double insulinAfterConstraint = MainApp.getConfigBuilder().applyBolusConstraints(insulin);
confirmMessage += " " + insulinAfterConstraint + " U "; confirmMessage += " " + insulinAfterConstraint + " U ";
confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?"; confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?";
if (insulinAfterConstraint != insulin) if (insulinAfterConstraint - insulin != 0d)
confirmMessage += "\n" + getString(R.string.constraintapllied); confirmMessage += "\n" + getString(R.string.constraintapllied);
insulin = insulinAfterConstraint; insulin = insulinAfterConstraint;
@ -83,15 +95,20 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); final PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
PumpEnactResult result = pump.setExtendedBolus(finalInsulin, finalDurationInMinutes); mHandler.post(new Runnable() {
if (!result.success) { @Override
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); public void run() {
builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror)); PumpEnactResult result = pump.setExtendedBolus(finalInsulin, finalDurationInMinutes);
builder.setMessage(result.comment); if (!result.success) {
builder.setPositiveButton(getContext().getString(R.string.ok), null); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.show(); builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror));
} builder.setMessage(result.comment);
builder.setPositiveButton(getContext().getString(R.string.ok), null);
builder.show();
}
}
});
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);
@ -103,4 +120,5 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
} }
} }
} }
} }

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.Overview.Dialogs;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -44,6 +46,15 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
PlusMinusEditText basalPercentPM; PlusMinusEditText basalPercentPM;
PlusMinusEditText basalAbsolutePM; PlusMinusEditText basalAbsolutePM;
Handler mHandler;
public static HandlerThread mHandlerThread;
public NewTempBasalDialog() {
mHandlerThread = new HandlerThread(NewExtendedBolusDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
}
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
@ -119,20 +130,26 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); final PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
PumpEnactResult result; mHandler.post(new Runnable() {
if (setAsPercent) { @Override
result = pump.setTempBasalPercent(finalBasalPercent, finalDurationInMinutes); public void run() {
} else { PumpEnactResult result;
result = pump.setTempBasalAbsolute(finalBasal, finalDurationInMinutes); if (setAsPercent) {
} result = pump.setTempBasalPercent(finalBasalPercent, finalDurationInMinutes);
if (!result.success) { } else {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); result = pump.setTempBasalAbsolute(finalBasal, finalDurationInMinutes);
builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror)); }
builder.setMessage(result.comment); if (!result.success) {
builder.setPositiveButton(getContext().getString(R.string.ok), null); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.show(); builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror));
} builder.setMessage(result.comment);
builder.setPositiveButton(getContext().getString(R.string.ok), null);
builder.show();
}
}
});
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.Overview.Dialogs;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.*; import android.view.*;
@ -28,6 +30,15 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
PlusMinusEditText editCarbs; PlusMinusEditText editCarbs;
PlusMinusEditText editInsulin; PlusMinusEditText editInsulin;
Handler mHandler;
public static HandlerThread mHandlerThread;
public NewTreatmentDialog() {
mHandlerThread = new HandlerThread(NewExtendedBolusDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
}
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
@ -66,7 +77,7 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
confirmMessage += getString(R.string.bolus) + ": " + insulinAfterConstraints + "U"; confirmMessage += getString(R.string.bolus) + ": " + insulinAfterConstraints + "U";
confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g"; confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (insulinAfterConstraints - insulin != 0 || carbsAfterConstraints != carbs) if (insulinAfterConstraints - insulin != 0 || carbsAfterConstraints != carbs)
confirmMessage += "\n" + getString(R.string.constraintapllied); confirmMessage += "\n" + getString(R.string.constraintapllied);
final Double finalInsulinAfterConstraints = insulinAfterConstraints; final Double finalInsulinAfterConstraints = insulinAfterConstraints;
@ -78,15 +89,20 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) { if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); final PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
PumpEnactResult result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints); mHandler.post(new Runnable() {
if (!result.success) { @Override
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); public void run() {
builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror)); PumpEnactResult result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints);
builder.setMessage(result.comment); if (!result.success) {
builder.setPositiveButton(getContext().getString(R.string.ok), null); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.show(); builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror));
} builder.setMessage(result.comment);
builder.setPositiveButton(getContext().getString(R.string.ok), null);
builder.show();
}
}
});
} }
} }
}); });

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.Overview.Dialogs;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.text.Editable; import android.text.Editable;
@ -56,6 +58,15 @@ public class WizardDialog extends DialogFragment implements OnClickListener {
Integer calculatedCarbs = 0; Integer calculatedCarbs = 0;
Double calculatedTotalInsulin = 0d; Double calculatedTotalInsulin = 0d;
Handler mHandler;
public static HandlerThread mHandlerThread;
public WizardDialog() {
mHandlerThread = new HandlerThread(NewExtendedBolusDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
}
final private TextWatcher textWatcher = new TextWatcher() { final private TextWatcher textWatcher = new TextWatcher() {
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
@ -157,15 +168,20 @@ public class WizardDialog extends DialogFragment implements OnClickListener {
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) { if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); final PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
PumpEnactResult result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints); mHandler.post(new Runnable() {
if (!result.success) { @Override
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); public void run() {
builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror)); PumpEnactResult result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints);
builder.setMessage(result.comment); if (!result.success) {
builder.setPositiveButton(getContext().getString(R.string.ok), null); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.show(); builder.setTitle(getContext().getString(R.string.treatmentdeliveryerror));
} builder.setMessage(result.comment);
builder.setPositiveButton(getContext().getString(R.string.ok), null);
builder.show();
}
}
});
} }
} }
}); });

View file

@ -87,12 +87,6 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI
return true; return true;
} }
@Override
public APSResult applyBasalConstraints(APSResult result) {
result.rate = Math.min(applyBasalConstraints(result.rate), result.rate);
return result;
}
@Override @Override
public Double applyBasalConstraints(Double absoluteRate) { public Double applyBasalConstraints(Double absoluteRate) {
Double origAbsoluteRate = absoluteRate; Double origAbsoluteRate = absoluteRate;
@ -163,8 +157,8 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI
} }
Integer percentRateAfterConst = new Double(absoluteRate / currentBasal * 100).intValue(); Integer percentRateAfterConst = new Double(absoluteRate / currentBasal * 100).intValue();
if (percentRateAfterConst < 100) Round.ceilTo(absoluteRate, 10d).intValue(); if (percentRateAfterConst < 100) percentRateAfterConst = Round.ceilTo((double) percentRateAfterConst, 10d).intValue();
else Round.floorTo(absoluteRate, 10d).intValue(); else percentRateAfterConst = Round.floorTo((double) percentRateAfterConst, 10d).intValue();
if (Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit) if (Config.logConstraintsChanges && origPercentRate != Constants.basalPercentOnlyForCheckLimit)
log.debug("Recalculated percent rate " + percentRate + "% to " + percentRateAfterConst + "%"); log.debug("Recalculated percent rate " + percentRate + "% to " + percentRateAfterConst + "%");

View file

@ -1,7 +1,9 @@
package info.nightscout.androidaps.plugins.TempBasals; package info.nightscout.androidaps.plugins.TempBasals;
import android.app.Activity; import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v7.widget.*; import android.support.v7.widget.*;
@ -24,14 +26,16 @@ import java.sql.SQLException;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.interfaces.TempBasalsInterface; import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal; import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal;
@ -56,6 +60,8 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
private List<TempBasal> tempBasals; private List<TempBasal> tempBasals;
private List<TempBasal> extendedBoluses; private List<TempBasal> extendedBoluses;
private boolean useExtendedBoluses = false;
boolean fragmentEnabled = true; boolean fragmentEnabled = true;
boolean fragmentVisible = true; boolean fragmentVisible = true;
boolean visibleNow = false; boolean visibleNow = false;
@ -129,10 +135,10 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
// Update ended // Update ended
checkForExpiredExtended(); checkForExpiredExtended();
checkForExpiredTemps(); checkForExpiredTemps();
} catch (SQLException e) { } catch (SQLException e) {
log.debug(e.getMessage(), e); log.debug(e.getMessage(), e);
tempBasals = new ArrayList<TempBasal>(); tempBasals = new ArrayList<TempBasal>();
extendedBoluses = new ArrayList<TempBasal>();
} }
} }
@ -208,7 +214,13 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
IobTotal calc = t.iobCalc(now); IobTotal calc = t.iobCalc(now);
total.plus(calc); total.plus(calc);
} }
if (useExtendedBoluses) {
for (Integer pos = 0; pos < extendedBoluses.size(); pos++) {
TempBasal t = extendedBoluses.get(pos);
IobTotal calc = t.iobCalc(now);
total.plus(calc);
}
}
lastCalculationTimestamp = new Date().getTime(); lastCalculationTimestamp = new Date().getTime();
lastCalculation = total; lastCalculation = total;
} }
@ -234,10 +246,10 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
public static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TempBasalsViewHolder> { public static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TempBasalsViewHolder> {
List<TempBasal> tempBasals; List<TempBasal> tempBasalList;
RecyclerViewAdapter(List<TempBasal> tempBasals) { RecyclerViewAdapter(List<TempBasal> tempBasalList) {
this.tempBasals = tempBasals; this.tempBasalList = tempBasalList;
} }
@Override @Override
@ -251,9 +263,9 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
public void onBindViewHolder(TempBasalsViewHolder holder, int position) { public void onBindViewHolder(TempBasalsViewHolder holder, int position) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
DateFormat enddf = DateFormat.getTimeInstance(DateFormat.SHORT); DateFormat enddf = DateFormat.getTimeInstance(DateFormat.SHORT);
TempBasal tempBasal = tempBasals.get(position); TempBasal tempBasal = tempBasalList.get(position);
if (tempBasal.timeEnd != null) { if (tempBasal.timeEnd != null) {
holder.date.setText(df.format(tempBasal.timeStart) + " - " + enddf.format(tempBasals.get(position).timeEnd)); holder.date.setText(df.format(tempBasal.timeStart) + " - " + enddf.format(tempBasalList.get(position).timeEnd));
} else { } else {
holder.date.setText(df.format(tempBasal.timeStart)); holder.date.setText(df.format(tempBasal.timeStart));
} }
@ -270,6 +282,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
holder.iob.setText(formatNumber2decimalplaces.format(iob.basaliob) + " U"); holder.iob.setText(formatNumber2decimalplaces.format(iob.basaliob) + " U");
holder.netInsulin.setText(formatNumber2decimalplaces.format(iob.netInsulin) + " U"); holder.netInsulin.setText(formatNumber2decimalplaces.format(iob.netInsulin) + " U");
holder.netRatio.setText(formatNumber2decimalplaces.format(iob.netRatio) + " U/h"); holder.netRatio.setText(formatNumber2decimalplaces.format(iob.netRatio) + " U/h");
holder.extendedFlag.setVisibility(tempBasal.isExtended ? View.VISIBLE : View.GONE);
if (tempBasal.isInProgress()) if (tempBasal.isInProgress())
holder.dateLinearLayout.setBackgroundColor(MainApp.instance().getResources().getColor(R.color.colorInProgress)); holder.dateLinearLayout.setBackgroundColor(MainApp.instance().getResources().getColor(R.color.colorInProgress));
else if (tempBasal.timeEnd == null) else if (tempBasal.timeEnd == null)
@ -282,7 +295,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
@Override @Override
public int getItemCount() { public int getItemCount() {
return tempBasals.size(); return tempBasalList.size();
} }
@Override @Override
@ -300,6 +313,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
TextView netRatio; TextView netRatio;
TextView netInsulin; TextView netInsulin;
TextView iob; TextView iob;
TextView extendedFlag;
LinearLayout dateLinearLayout; LinearLayout dateLinearLayout;
TempBasalsViewHolder(View itemView) { TempBasalsViewHolder(View itemView) {
@ -313,6 +327,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
netRatio = (TextView) itemView.findViewById(R.id.tempbasals_netratio); netRatio = (TextView) itemView.findViewById(R.id.tempbasals_netratio);
netInsulin = (TextView) itemView.findViewById(R.id.tempbasals_netinsulin); netInsulin = (TextView) itemView.findViewById(R.id.tempbasals_netinsulin);
iob = (TextView) itemView.findViewById(R.id.tempbasals_iob); iob = (TextView) itemView.findViewById(R.id.tempbasals_iob);
extendedFlag = (TextView) itemView.findViewById(R.id.tempbasals_extendedflag);
dateLinearLayout = (LinearLayout) itemView.findViewById(R.id.tempbasals_datelinearlayout); dateLinearLayout = (LinearLayout) itemView.findViewById(R.id.tempbasals_datelinearlayout);
} }
} }
@ -320,6 +335,8 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
public TempBasalsFragment() { public TempBasalsFragment() {
super(); super();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false);
registerBus(); registerBus();
initializeData(); initializeData();
updateGUI(); updateGUI();
@ -345,7 +362,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
llm = new LinearLayoutManager(view.getContext()); llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm); recyclerView.setLayoutManager(llm);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(tempBasals); RecyclerViewAdapter adapter = new RecyclerViewAdapter(getMergedList());
recyclerView.setAdapter(adapter); recyclerView.setAdapter(adapter);
tempBasalTotalView = (TextView) view.findViewById(R.id.tempbasals_totaltempiob); tempBasalTotalView = (TextView) view.findViewById(R.id.tempbasals_totaltempiob);
@ -362,18 +379,43 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa
MainApp.bus().register(this); MainApp.bus().register(this);
} }
List<TempBasal> getMergedList() {
if (useExtendedBoluses) {
List<TempBasal> merged = new ArrayList<TempBasal>();
merged.addAll(tempBasals);
merged.addAll(extendedBoluses);
class CustomComparator implements Comparator<TempBasal> {
public int compare(TempBasal object1, TempBasal object2) {
return (int) (object2.timeIndex - object1.timeIndex);
}
}
Collections.sort(merged, new CustomComparator());
return merged;
} else {
return tempBasals;
}
}
@Subscribe @Subscribe
public void onStatusEvent(final EventTempBasalChange ev) { public void onStatusEvent(final EventTempBasalChange ev) {
initializeData(); initializeData();
} }
public void onStatusEvent(final EventPreferenceChange s) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false);
initializeData();
}
public void updateGUI() { public void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (visibleNow && activity != null && recyclerView != null) if (visibleNow && activity != null && recyclerView != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
recyclerView.swapAdapter(new RecyclerViewAdapter(tempBasals), false); recyclerView.swapAdapter(new RecyclerViewAdapter(getMergedList()), false);
if (lastCalculation != null) { if (lastCalculation != null) {
String totalText = formatNumber2decimalplaces.format(lastCalculation.basaliob) + "U"; String totalText = formatNumber2decimalplaces.format(lastCalculation.basaliob) + "U";
tempBasalTotalView.setText(totalText); tempBasalTotalView.setText(totalText);

View file

@ -26,7 +26,6 @@ import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
@ -36,7 +35,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
Double defaultBasalValue = 0.2d; Double defaultBasalValue = 0.2d;
Integer batteryPercent = 50; Integer batteryPercent = 50;
Integer resevoirInUnits = 50; Integer reservoirInUnits = 50;
TextView basaBasalRateView; TextView basaBasalRateView;
TextView tempBasalView; TextView tempBasalView;
@ -131,16 +130,6 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
return getExtendedBolus() != null; return getExtendedBolus() != null;
} }
@Override
public Integer getBatteryPercent() {
return batteryPercent;
}
@Override
public Integer getReservoirValue() {
return resevoirInUnits;
}
@Override @Override
public void setNewBasalProfile(NSProfile profile) { public void setNewBasalProfile(NSProfile profile) {
// Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile(); // Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile();
@ -361,7 +350,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
pump.put("battery", battery); pump.put("battery", battery);
pump.put("status", status); pump.put("status", status);
pump.put("reservoir", getReservoirValue()); pump.put("reservoir", reservoirInUnits);
pump.put("clock", DateUtil.toISOString(new Date())); pump.put("clock", DateUtil.toISOString(new Date()));
} catch (JSONException e) { } catch (JSONException e) {
} }
@ -394,7 +383,6 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
basaBasalRateView.setText(getBaseBasalRate() + "U"); basaBasalRateView.setText(getBaseBasalRate() + "U");
if (isTempBasalInProgress()) { if (isTempBasalInProgress()) {
//tempBasalView.setText(tempBasal.toString());
tempBasalView.setText(getTempBasal().toString()); tempBasalView.setText(getTempBasal().toString());
} else { } else {
tempBasalView.setText(""); tempBasalView.setText("");
@ -404,8 +392,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt
} else { } else {
extendedBolusView.setText(""); extendedBolusView.setText("");
} }
batteryView.setText(getBatteryPercent() + "%"); batteryView.setText(batteryPercent + "%");
reservoirView.setText(getReservoirValue() + "U"); reservoirView.setText(reservoirInUnits + "U");
} }
}); });
} }

View file

@ -0,0 +1,25 @@
package info.nightscout.utils;
import android.graphics.Color;
import android.widget.TextView;
/**
* Created by mike on 08.07.2016.
*/
public class SetWarnColor {
static final int normalColor = Color.WHITE;
static final int warnColor = Color.YELLOW;
static final int urgentColor = Color.RED;
public static void setColor(TextView view, double value, double warnLevel, double urgentLevel) {
if (value >= urgentLevel) view.setTextColor(urgentColor);
else if (value >= warnLevel) view.setTextColor(warnColor);
else view.setTextColor(normalColor);
}
public static void setColorInverse(TextView view, double value, double warnLevel, double urgentLevel) {
if (value <= urgentLevel) view.setTextColor(urgentColor);
else if (value <= warnLevel) view.setTextColor(warnColor);
else view.setTextColor(normalColor);
}
}

View file

@ -4,15 +4,252 @@
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context="info.nightscout.androidaps.plugins.DanaR.DanaRFragment"> tools:context="info.nightscout.androidaps.plugins.DanaR.DanaRFragment">
<com.joanzapata.iconify.widget.IconTextView
android:layout_width="wrap_content" <LinearLayout
android:layout_height="wrap_content" android:layout_width="match_parent"
android:paddingLeft="5dp" android:layout_height="match_parent"
android:paddingRight="5dp" android:orientation="vertical">
android:layout_weight="1.02"
android:gravity="center_vertical|right" <LinearLayout
android:text="B" android:layout_width="match_parent"
android:textSize="20dp" android:layout_height="wrap_content"
android:id="@+id/danar_connection" android:orientation="horizontal">
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/virtualpump_lastconnection_label"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_lastconnection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<com.joanzapata.iconify.widget.IconTextView
android:id="@+id/danar_battery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.02"
android:gravity="center_vertical|right"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textSize="20dp" />
<com.joanzapata.iconify.widget.IconTextView
android:id="@+id/danar_btconnection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.02"
android:gravity="center_vertical|right"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text="{fa-bluetooth-b}"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/danar_lastbolus"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_lastbolus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:text="0 U"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/danar_dailyunits"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_dailyunits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:text="0 / 0 U"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/virtualpump_basebasalrate_label"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_basabasalrate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/virtualpump_tempbasal_label"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_tempbasal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/virtualpump_extendedbolus_label"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_extendedbolus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/virtualpump_reservoir_label"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_reservoir"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:singleLine="true"
android:text="@string/danar_iob_label"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorPumpLabel"
android:textStyle="bold" />
<TextView
android:id="@+id/danar_iob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
</FrameLayout> </FrameLayout>

View file

@ -58,6 +58,16 @@
android:textAppearance="?android:attr/textAppearanceSmall" android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/cardObjectiveText" /> android:textColor="@color/cardObjectiveText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E"
android:id="@+id/tempbasals_extendedflag"
android:textColor="@color/colorSetExtendedButton"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="5dp" />
</LinearLayout> </LinearLayout>

View file

@ -20,4 +20,6 @@
<color name="colorAffectingIOB">#830400</color> <color name="colorAffectingIOB">#830400</color>
<color name="colorNotEnded">#190084</color> <color name="colorNotEnded">#190084</color>
<color name="colorPumpLabel">#FF478EFF</color>
</resources> </resources>

View file

@ -227,5 +227,12 @@
<string name="nobtadapter">No bluetooth adapter found</string> <string name="nobtadapter">No bluetooth adapter found</string>
<string name="devicenotfound">Selected device not found</string> <string name="devicenotfound">Selected device not found</string>
<string name="connectionerror">Pump connection error</string> <string name="connectionerror">Pump connection error</string>
<string name="virtualpump_lastconnection_label">Last connection:</string>
<string name="danar_iob_label">Pump IOB:</string>
<string name="danar_dailyunits">Daily units:</string>
<string name="danar_lastbolus">Last bolus:</string>
<string name="hoursago">h ago</string>
<string name="danar_invalidinput">Invalid input data</string>
<string name="danar_valuenotsetproperly">Value not set properly</string>
</resources> </resources>