Combo: cleanup code

This commit is contained in:
Milos Kozak 2022-02-20 19:27:01 +01:00
parent c1dc41908b
commit ad8c2297a0
16 changed files with 296 additions and 352 deletions

View file

@ -260,7 +260,7 @@ class DetermineBasalAdapterSMBDynamicISFJS internal constructor(private val scri
this.mealData.put("TDDAIMI7", tddCalculator.averageTDD(tddCalculator.calculate(7)).totalAmount) this.mealData.put("TDDAIMI7", tddCalculator.averageTDD(tddCalculator.calculate(7)).totalAmount)
this.mealData.put("TDDPUMP", tddCalculator.calculateDaily().totalAmount) this.mealData.put("TDDPUMP", tddCalculator.calculateDaily().totalAmount)
this.mealData.put("TDDLast24", tddCalculator!!.calculate24Daily().totalAmount) this.mealData.put("TDDLast24", tddCalculator.calculate24Daily().totalAmount)
if (constraintChecker.isAutosensModeEnabled().value()) { if (constraintChecker.isAutosensModeEnabled().value()) {
autosensData.put("ratio", autosensDataRatio) autosensData.put("ratio", autosensDataRatio)

View file

@ -142,7 +142,7 @@ class TddCalculator @Inject constructor(
//result.put(midnight, tdd) //result.put(midnight, tdd)
} }
val calculationStep = T.mins(5).msecs() val calculationStep = T.mins(5).msecs()
val tempBasals = iobCobCalculator.getTempBasalIncludingConvertedExtendedForRange(startTime, endTime, calculationStep) //val tempBasals = iobCobCalculator.getTempBasalIncludingConvertedExtendedForRange(startTime, endTime, calculationStep)
for (t in startTime until endTime step calculationStep) { for (t in startTime until endTime step calculationStep) {
//val midnight = MidnightTime.calc(t) //val midnight = MidnightTime.calc(t)

View file

@ -40,6 +40,7 @@ public class ComboFragment extends DaggerFragment {
@Inject DateUtil dateUtil; @Inject DateUtil dateUtil;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
@Inject AapsSchedulers aapsSchedulers; @Inject AapsSchedulers aapsSchedulers;
@Inject ComboErrorUtil errorUtil;
private final CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
@ -264,8 +265,6 @@ public class ComboFragment extends DaggerFragment {
private void updateErrorDisplay(boolean forceHide) { private void updateErrorDisplay(boolean forceHide) {
int errorCount = -1; int errorCount = -1;
ComboErrorUtil errorUtil = ComboErrorUtil.getInstance();
if (!forceHide) { if (!forceHide) {
ComboErrorUtil.DisplayType displayType = errorUtil.getDisplayType(); ComboErrorUtil.DisplayType displayType = errorUtil.getDisplayType();

View file

@ -38,9 +38,6 @@ import info.nightscout.androidaps.interfaces.Pump;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.plugins.pump.combo.data.ComboErrorUtil;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
@ -65,6 +62,8 @@ import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.InstanceId; import info.nightscout.androidaps.utils.InstanceId;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.shared.sharedPreferences.SP; import info.nightscout.shared.sharedPreferences.SP;
/** /**
@ -99,10 +98,10 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
private final Context context; private final Context context;
private final PumpSync pumpSync; private final PumpSync pumpSync;
private final DateUtil dateUtil; private final DateUtil dateUtil;
private final RuffyCommands ruffyScripter;
private final static PumpDescription pumpDescription = new PumpDescription(); private final static PumpDescription pumpDescription = new PumpDescription();
private RuffyCommands ruffyScripter;
@NonNull @NonNull
private static final ComboPump pump = new ComboPump(); private static final ComboPump pump = new ComboPump();
@ -154,7 +153,8 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
CommandQueue commandQueue, CommandQueue commandQueue,
Context context, Context context,
PumpSync pumpSync, PumpSync pumpSync,
DateUtil dateUtil DateUtil dateUtil,
RuffyScripter ruffyScripter
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
@ -173,16 +173,13 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
this.context = context; this.context = context;
this.pumpSync = pumpSync; this.pumpSync = pumpSync;
this.dateUtil = dateUtil; this.dateUtil = dateUtil;
this.ruffyScripter = ruffyScripter;
ComboErrorUtil.getInstance().setSP(sp);
ComboErrorUtil.getInstance().clearErrors();
pumpDescription.fillFor(PumpType.ACCU_CHEK_COMBO); pumpDescription.fillFor(PumpType.ACCU_CHEK_COMBO);
} }
@Override protected void onStart() { @Override protected void onStart() {
super.onStart(); super.onStart();
ruffyScripter = new RuffyScripter(context);
OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector()) OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector())
.success(false).enacted(false).comment(R.string.combo_pump_unsupported_operation); .success(false).enacted(false).comment(R.string.combo_pump_unsupported_operation);
} }

View file

@ -1,106 +0,0 @@
package info.nightscout.androidaps.plugins.pump.combo.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import info.nightscout.androidaps.combo.R;
import info.nightscout.shared.sharedPreferences.SP;
/**
* Created by andy on 3/17/18.
*/
public class ComboErrorUtil {
private SP sp;
Map<String, List<ErrorState>> errorMap = new HashMap<>();
private static final ComboErrorUtil comboDataUtil = new ComboErrorUtil();
private ComboErrorUtil() {
}
public static ComboErrorUtil getInstance() {
return comboDataUtil;
}
public void setSP(SP sp) {
this.sp = sp;
}
public void addError(Exception exception) {
String exceptionMsg = exception.getMessage();
if (!errorMap.containsKey(exceptionMsg)) {
List<ErrorState> list = new ArrayList<>();
list.add(createErrorState(exception));
errorMap.put(exceptionMsg, list);
} else {
errorMap.get(exceptionMsg).add(createErrorState(exception));
}
updateErrorCount();
}
private void updateErrorCount() {
int errorCount = 0;
if (!isErrorPresent()) {
for (List<ErrorState> errorStates : errorMap.values()) {
errorCount += errorStates.size();
}
}
if (errorCount==0) {
if (sp.contains(R.string.key_combo_error_count)) {
sp.remove(R.string.key_combo_error_count);
}
} else {
sp.putInt(R.string.key_combo_error_count, errorCount);
}
}
private ErrorState createErrorState(Exception exception) {
ErrorState errorState = new ErrorState();
errorState.setException(exception);
errorState.setTimeInMillis(System.currentTimeMillis());
return errorState;
}
public void clearErrors() {
if (errorMap != null)
this.errorMap.clear();
else
this.errorMap = new HashMap<>();
if (sp.contains(R.string.key_combo_error_count)) {
sp.remove(R.string.key_combo_error_count);
}
}
public boolean isErrorPresent() {
return !this.errorMap.isEmpty();
}
public int getErrorCount() {
return sp.contains(R.string.key_combo_error_count) ?
sp.getInt(R.string.key_combo_error_count, -1) : -1;
}
public DisplayType getDisplayType() {
String displayTypeString = sp.getString(R.string.key_show_comm_error_count, "ON_ERROR");
return DisplayType.valueOf(displayTypeString);
}
public enum DisplayType {
NEVER,
ON_ERROR,
ALWAYS
}
}

View file

@ -0,0 +1,49 @@
package info.nightscout.androidaps.plugins.pump.combo.data
import info.nightscout.androidaps.combo.R
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ComboErrorUtil @Inject constructor(
private val sp: SP
) {
class ErrorState(val exception: Exception, val timeInMillis: Long)
enum class DisplayType {
NEVER, ON_ERROR, ALWAYS
}
private var errorMap: MutableMap<String, MutableList<ErrorState>> = HashMap()
fun addError(exception: Exception) {
val exceptionMsg = exception.message ?: return
if (!errorMap.containsKey(exceptionMsg)) errorMap[exceptionMsg] = ArrayList<ErrorState>().also { it.add(createErrorState(exception)) }
else errorMap[exceptionMsg]?.add(createErrorState(exception))
updateErrorCount()
}
private fun updateErrorCount() {
var errorCount = 0
if (!isErrorPresent) for (errorStates in errorMap.values) errorCount += errorStates.size
if (errorCount == 0) {
if (sp.contains(R.string.key_combo_error_count)) sp.remove(R.string.key_combo_error_count)
} else sp.putInt(R.string.key_combo_error_count, errorCount)
}
private fun createErrorState(exception: Exception) = ErrorState(exception, System.currentTimeMillis())
fun clearErrors() {
errorMap.clear()
if (sp.contains(R.string.key_combo_error_count)) sp.remove(R.string.key_combo_error_count)
}
private val isErrorPresent: Boolean
get() = errorMap.isNotEmpty()
val errorCount: Int
get() = if (sp.contains(R.string.key_combo_error_count)) sp.getInt(R.string.key_combo_error_count, -1) else -1
val displayType: DisplayType
get() = DisplayType.valueOf(sp.getString(R.string.key_show_comm_error_count, "ON_ERROR"))
}

View file

@ -1,17 +0,0 @@
package info.nightscout.androidaps.plugins.pump.combo.data;
public class ErrorState {
private Exception exception;
private long timeInMillis;
public void setException(Exception exception) {
this.exception = exception;
}
public void setTimeInMillis(long timeInMillis) {
this.timeInMillis = timeInMillis;
}
}

View file

@ -7,6 +7,7 @@ import android.content.ServiceConnection;
import android.os.IBinder; import android.os.IBinder;
import android.os.RemoteException; import android.os.RemoteException;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
@ -19,16 +20,15 @@ import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.BolusType; import org.monkey.d.ruffy.ruffy.driver.display.menu.BolusType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.plugins.pump.combo.data.ComboErrorUtil; import info.nightscout.androidaps.plugins.pump.combo.data.ComboErrorUtil;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadQuickInfoCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistoryRequest;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.BolusCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.BolusCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.CancelTbrCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.CancelTbrCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.Command; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.Command;
@ -37,18 +37,24 @@ import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.Conf
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadBasalProfileCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadBasalProfileCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadHistoryCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadHistoryCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadPumpStateCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadPumpStateCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.ReadQuickInfoCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.SetBasalProfileCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.SetBasalProfileCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.SetTbrCommand; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands.SetTbrCommand;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistoryRequest;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
/** /**
* Provides scripting 'runtime' and operations. consider moving operations into a separate * Provides scripting 'runtime' and operations. consider moving operations into a separate
* class and inject that into executing commands, so that commands operately solely on * class and inject that into executing commands, so that commands operately solely on
* operations and are cleanly separated from the thread management, connection management etc * operations and are cleanly separated from the thread management, connection management etc
*/ */
@Singleton
public class RuffyScripter implements RuffyCommands { public class RuffyScripter implements RuffyCommands {
private static final Logger log = StacktraceLoggerWrapper.getLogger(RuffyScripter.class);
private IRuffyService ruffyService; private IRuffyService ruffyService;
private final ComboErrorUtil comboErrorUtil;
private final AAPSLogger aapsLogger;
@Nullable @Nullable
private volatile Menu currentMenu; private volatile Menu currentMenu;
@ -64,30 +70,28 @@ public class RuffyScripter implements RuffyCommands {
private final IRTHandler mHandler = new IRTHandler.Stub() { private final IRTHandler mHandler = new IRTHandler.Stub() {
@Override @Override
public void log(String message) { public void log(String message) {
if (log.isTraceEnabled()) { aapsLogger.debug(LTag.PUMP, "Ruffy says: " + message);
log.trace("Ruffy says: " + message);
}
} }
@Override @Override
public void fail(String message) { public void fail(String message) {
log.warn("Ruffy warns: " + message); aapsLogger.warn(LTag.PUMP, "Ruffy warns: " + message);
} }
@Override @Override
public void requestBluetooth() { public void requestBluetooth() {
log.trace("Ruffy invoked requestBluetooth callback"); aapsLogger.debug(LTag.PUMP, "Ruffy invoked requestBluetooth callback");
} }
@Override @Override
public void rtStopped() { public void rtStopped() {
log.debug("rtStopped callback invoked"); aapsLogger.debug(LTag.PUMP, "rtStopped callback invoked");
currentMenu = null; currentMenu = null;
} }
@Override @Override
public void rtStarted() { public void rtStarted() {
log.debug("rtStarted callback invoked"); aapsLogger.debug(LTag.PUMP, "rtStarted callback invoked");
} }
@Override @Override
@ -101,7 +105,7 @@ public class RuffyScripter implements RuffyCommands {
@Override @Override
public void rtDisplayHandleMenu(Menu menu) { public void rtDisplayHandleMenu(Menu menu) {
// method is called every ~500ms // method is called every ~500ms
log.debug("rtDisplayHandleMenu: " + menu); aapsLogger.debug(LTag.PUMP, "rtDisplayHandleMenu: " + menu);
currentMenu = menu; currentMenu = menu;
menuLastUpdated = System.currentTimeMillis(); menuLastUpdated = System.currentTimeMillis();
@ -113,14 +117,18 @@ public class RuffyScripter implements RuffyCommands {
@Override @Override
public void rtDisplayHandleNoMenu() { public void rtDisplayHandleNoMenu() {
log.warn("rtDisplayHandleNoMenu callback invoked"); aapsLogger.warn(LTag.PUMP, "rtDisplayHandleNoMenu callback invoked");
unparsableMenuEncountered = true; unparsableMenuEncountered = true;
} }
}; };
public RuffyScripter(Context context) { @Inject
public RuffyScripter(Context context, ComboErrorUtil comboErrorUtil, AAPSLogger aapsLogger) {
boolean boundSucceeded = false; boolean boundSucceeded = false;
this.comboErrorUtil = comboErrorUtil;
this.aapsLogger = aapsLogger;
try { try {
Intent intent = new Intent() Intent intent = new Intent()
.setComponent(new ComponentName( .setComponent(new ComponentName(
@ -139,28 +147,28 @@ public class RuffyScripter implements RuffyCommands {
ServiceConnection mRuffyServiceConnection = new ServiceConnection() { ServiceConnection mRuffyServiceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder service) { public void onServiceConnected(ComponentName name, IBinder service) {
log.debug("ruffy service connected"); aapsLogger.debug(LTag.PUMP, "ruffy service connected");
ruffyService = IRuffyService.Stub.asInterface(service); ruffyService = IRuffyService.Stub.asInterface(service);
try { try {
ruffyService.setHandler(mHandler); ruffyService.setHandler(mHandler);
} catch (Exception e) { } catch (Exception e) {
log.error("Ruffy handler has issues", e); aapsLogger.error(LTag.PUMP, "Ruffy handler has issues", e);
} }
started = true; started = true;
} }
@Override @Override
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
log.debug("ruffy service disconnected"); aapsLogger.debug(LTag.PUMP, "ruffy service disconnected");
} }
}; };
boundSucceeded = context.bindService(intent, mRuffyServiceConnection, Context.BIND_AUTO_CREATE); boundSucceeded = context.bindService(intent, mRuffyServiceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) { } catch (Exception e) {
log.error("Binding to ruffy service failed", e); aapsLogger.error(LTag.PUMP, "Binding to ruffy service failed", e);
} }
if (!boundSucceeded) { if (!boundSucceeded) {
log.info("No connection to ruffy. Pump control unavailable."); aapsLogger.info(LTag.PUMP, "No connection to ruffy. Pump control unavailable.");
} }
} }
@ -191,9 +199,9 @@ public class RuffyScripter implements RuffyCommands {
private void addError(Exception e) { private void addError(Exception e) {
try { try {
ComboErrorUtil.getInstance().addError(e); comboErrorUtil.addError(e);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Combo data util problem." + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "Combo data util problem." + ex.getMessage(), ex);
} }
} }
@ -203,17 +211,17 @@ public class RuffyScripter implements RuffyCommands {
return; return;
} }
try { try {
log.debug("Disconnecting"); aapsLogger.debug(LTag.PUMP, "Disconnecting");
ruffyService.doRTDisconnect(); ruffyService.doRTDisconnect();
try { try {
ComboErrorUtil.getInstance().clearErrors(); comboErrorUtil.clearErrors();
} catch (Exception ex) { } catch (Exception ex) {
log.error("Combo data util problem." + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "Combo data util problem." + ex.getMessage(), ex);
} }
} catch (RemoteException e) { } catch (RemoteException e) {
// ignore // ignore
} catch (Exception e) { } catch (Exception e) {
log.warn("Disconnect not happy", e); aapsLogger.warn(LTag.PUMP, "Disconnect not happy", e);
addError(e); addError(e);
} }
} }
@ -225,14 +233,14 @@ public class RuffyScripter implements RuffyCommands {
@Override @Override
public CommandResult readQuickInfo(int numberOfBolusRecordsToRetrieve) { public CommandResult readQuickInfo(int numberOfBolusRecordsToRetrieve) {
return runCommand(new ReadQuickInfoCommand(numberOfBolusRecordsToRetrieve)); return runCommand(new ReadQuickInfoCommand(numberOfBolusRecordsToRetrieve, aapsLogger));
} }
public void returnToRootMenu() { public void returnToRootMenu() {
// returning to main menu using the 'back' key does not cause a vibration // returning to main menu using the 'back' key does not cause a vibration
MenuType menuType = getCurrentMenu().getType(); MenuType menuType = getCurrentMenu().getType();
while (menuType != MenuType.MAIN_MENU && menuType != MenuType.STOP && menuType != MenuType.WARNING_OR_ERROR) { while (menuType != MenuType.MAIN_MENU && menuType != MenuType.STOP && menuType != MenuType.WARNING_OR_ERROR) {
log.debug("Going back to main menu, currently at " + menuType); aapsLogger.debug(LTag.PUMP, "Going back to main menu, currently at " + menuType);
pressBackKey(); pressBackKey();
while (getCurrentMenu().getType() == menuType) { while (getCurrentMenu().getType() == menuType) {
waitForScreenUpdate(); waitForScreenUpdate();
@ -245,11 +253,11 @@ public class RuffyScripter implements RuffyCommands {
* Always returns a CommandResult, never throws * Always returns a CommandResult, never throws
*/ */
private CommandResult runCommand(final Command cmd) { private CommandResult runCommand(final Command cmd) {
log.debug("Attempting to run cmd: " + cmd); aapsLogger.debug(LTag.PUMP, "Attempting to run cmd: " + cmd);
List<String> violations = cmd.validateArguments(); List<String> violations = cmd.validateArguments();
if (!violations.isEmpty()) { if (!violations.isEmpty()) {
log.error("Command argument violations: " + Joiner.on(", ").join(violations)); aapsLogger.error(LTag.PUMP, "Command argument violations: " + Joiner.on(", ").join(violations));
return new CommandResult().success(false).state(new PumpState()); return new CommandResult().success(false).state(new PumpState());
} }
@ -260,27 +268,27 @@ public class RuffyScripter implements RuffyCommands {
unparsableMenuEncountered = false; unparsableMenuEncountered = false;
long connectStart = System.currentTimeMillis(); long connectStart = System.currentTimeMillis();
ensureConnected(); ensureConnected();
log.debug("Connection ready to execute cmd " + cmd); aapsLogger.debug(LTag.PUMP, "Connection ready to execute cmd " + cmd);
cmdThread = new Thread(() -> { cmdThread = new Thread(() -> {
try { try {
if (!runPreCommandChecks(cmd)) { if (!runPreCommandChecks(cmd)) {
return; return;
} }
PumpState pumpState = readPumpStateInternal(); PumpState pumpState = readPumpStateInternal();
log.debug("Pump state before running command: " + pumpState); aapsLogger.debug(LTag.PUMP, "Pump state before running command: " + pumpState);
// execute the command // execute the command
cmd.setScripter(RuffyScripter.this); cmd.setScripter(RuffyScripter.this);
long cmdStartTime = System.currentTimeMillis(); long cmdStartTime = System.currentTimeMillis();
cmd.execute(); cmd.execute();
long cmdEndTime = System.currentTimeMillis(); long cmdEndTime = System.currentTimeMillis();
log.debug("Executing " + cmd + " took " + (cmdEndTime - cmdStartTime) + "ms"); aapsLogger.debug(LTag.PUMP, "Executing " + cmd + " took " + (cmdEndTime - cmdStartTime) + "ms");
} catch (CommandException e) { } catch (CommandException e) {
log.info("CommandException running command", e); aapsLogger.info(LTag.PUMP, "CommandException running command", e);
addError(e); addError(e);
cmd.getResult().success = false; cmd.getResult().success = false;
} catch (Exception e) { } catch (Exception e) {
log.error("Unexpected exception running cmd", e); aapsLogger.error(LTag.PUMP, "Unexpected exception running cmd", e);
addError(e); addError(e);
cmd.getResult().success = false; cmd.getResult().success = false;
} }
@ -294,7 +302,7 @@ public class RuffyScripter implements RuffyCommands {
// on connection loss try to reconnect, confirm warning alerts caused by // on connection loss try to reconnect, confirm warning alerts caused by
// the disconnected and then return the command as failed (the caller // the disconnected and then return the command as failed (the caller
// can retry if needed). // can retry if needed).
log.debug("Connection unusable (ruffy connection: " + ruffyService.isConnected() + ", " aapsLogger.debug(LTag.PUMP, "Connection unusable (ruffy connection: " + ruffyService.isConnected() + ", "
+ "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms, " + "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms, "
+ "aborting command and attempting reconnect ..."); + "aborting command and attempting reconnect ...");
cmdThread.interrupt(); cmdThread.interrupt();
@ -317,46 +325,44 @@ public class RuffyScripter implements RuffyCommands {
} }
if (System.currentTimeMillis() > overallTimeout) { if (System.currentTimeMillis() > overallTimeout) {
log.error("Command " + cmd + " timed out"); aapsLogger.error(LTag.PUMP, "Command " + cmd + " timed out");
cmdThread.interrupt(); cmdThread.interrupt();
activeCmd.getResult().success = false; activeCmd.getResult().success = false;
break; break;
} }
if (unparsableMenuEncountered) { if (unparsableMenuEncountered) {
log.error("UnparsableMenuEncountered flagged, aborting command"); aapsLogger.error(LTag.PUMP, "UnparsableMenuEncountered flagged, aborting command");
cmdThread.interrupt(); cmdThread.interrupt();
activeCmd.getResult().invalidSetup = true; activeCmd.getResult().invalidSetup = true;
activeCmd.getResult().success = false; activeCmd.getResult().success = false;
} }
log.trace("Waiting for running command to complete"); aapsLogger.debug(LTag.PUMP, "Waiting for running command to complete");
SystemClock.sleep(500); SystemClock.sleep(500);
} }
activeCmd.getResult().state = readPumpStateInternal(); activeCmd.getResult().state = readPumpStateInternal();
CommandResult result = activeCmd.getResult(); CommandResult result = activeCmd.getResult();
if (log.isDebugEnabled()) { long connectDurationSec = (executionStart - connectStart) / 1000;
long connectDurationSec = (executionStart - connectStart) / 1000; long executionDurationSec = (System.currentTimeMillis() - executionStart) / 1000;
long executionDurationSec = (System.currentTimeMillis() - executionStart) / 1000; aapsLogger.debug(LTag.PUMP, "Command result: " + result);
log.debug("Command result: " + result); aapsLogger.debug(LTag.PUMP, "Connect: " + connectDurationSec + "s, execution: " + executionDurationSec + "s");
log.debug("Connect: " + connectDurationSec + "s, execution: " + executionDurationSec + "s");
}
return result; return result;
} catch (CommandException e) { } catch (CommandException e) {
log.error("CommandException while executing command", e); aapsLogger.error(LTag.PUMP, "CommandException while executing command", e);
PumpState pumpState = recoverFromCommandFailure(); PumpState pumpState = recoverFromCommandFailure();
addError(e); addError(e);
return activeCmd.getResult().success(false).state(pumpState); return activeCmd.getResult().success(false).state(pumpState);
} catch (Exception e) { } catch (Exception e) {
log.error("Unexpected exception communication with ruffy", e); aapsLogger.error(LTag.PUMP, "Unexpected exception communication with ruffy", e);
PumpState pumpState = recoverFromCommandFailure(); PumpState pumpState = recoverFromCommandFailure();
addError(e); addError(e);
return activeCmd.getResult().success(false).state(pumpState); return activeCmd.getResult().success(false).state(pumpState);
} finally { } finally {
Menu menu = this.currentMenu; Menu menu = this.currentMenu;
if (activeCmd.getResult().success && menu != null && menu.getType() != MenuType.MAIN_MENU) { if (activeCmd.getResult().success && menu != null && menu.getType() != MenuType.MAIN_MENU) {
log.warn("Command " + activeCmd + " successful, but finished leaving pump on menu " + getCurrentMenuName()); aapsLogger.warn(LTag.PUMP, "Command " + activeCmd + " successful, but finished leaving pump on menu " + getCurrentMenuName());
} }
if (cmdThread != null) { if (cmdThread != null) {
try { try {
@ -377,18 +383,18 @@ public class RuffyScripter implements RuffyCommands {
activeCmd.getResult().success = true; activeCmd.getResult().success = true;
} else if (getCurrentMenu().getType() == MenuType.STOP) { } else if (getCurrentMenu().getType() == MenuType.STOP) {
if (cmd.needsRunMode()) { if (cmd.needsRunMode()) {
log.error("Requested command requires run mode, but pump is suspended"); aapsLogger.error(LTag.PUMP, "Requested command requires run mode, but pump is suspended");
activeCmd.getResult().success = false; activeCmd.getResult().success = false;
return false; return false;
} }
} else if (getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) { } else if (getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) {
if (!(cmd instanceof ConfirmAlertCommand)) { if (!(cmd instanceof ConfirmAlertCommand)) {
log.warn("Warning/alert active on pump, but requested command is not ConfirmAlertCommand"); aapsLogger.warn(LTag.PUMP, "Warning/alert active on pump, but requested command is not ConfirmAlertCommand");
activeCmd.getResult().success = false; activeCmd.getResult().success = false;
return false; return false;
} }
} else if (getCurrentMenu().getType() != MenuType.MAIN_MENU) { } else if (getCurrentMenu().getType() != MenuType.MAIN_MENU) {
log.debug("Pump is unexpectedly not on main menu but " + getCurrentMenuName() + ", trying to recover"); aapsLogger.debug(LTag.PUMP, "Pump is unexpectedly not on main menu but " + getCurrentMenuName() + ", trying to recover");
try { try {
recoverFromCommandFailure(); recoverFromCommandFailure();
} catch (Exception e) { } catch (Exception e) {
@ -411,12 +417,12 @@ public class RuffyScripter implements RuffyCommands {
* @return whether the reconnect and return to main menu was successful * @return whether the reconnect and return to main menu was successful
*/ */
private boolean recoverFromConnectionLoss() { private boolean recoverFromConnectionLoss() {
log.debug("Connection was lost, trying to reconnect"); aapsLogger.debug(LTag.PUMP, "Connection was lost, trying to reconnect");
ensureConnected(); ensureConnected();
if (getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) { if (getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) {
WarningOrErrorCode warningOrErrorCode = readWarningOrErrorCode(); WarningOrErrorCode warningOrErrorCode = readWarningOrErrorCode();
if (Objects.equals(activeCmd.getReconnectWarningId(), warningOrErrorCode.warningCode)) { if (Objects.equals(activeCmd.getReconnectWarningId(), warningOrErrorCode.warningCode)) {
log.debug("Confirming warning caused by disconnect: #" + warningOrErrorCode.warningCode); aapsLogger.debug(LTag.PUMP, "Confirming warning caused by disconnect: #" + warningOrErrorCode.warningCode);
// confirm alert // confirm alert
verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR); verifyMenuIsDisplayed(MenuType.WARNING_OR_ERROR);
pressCheckKey(); pressCheckKey();
@ -433,7 +439,7 @@ public class RuffyScripter implements RuffyCommands {
returnToRootMenu(); returnToRootMenu();
} }
} }
log.debug("Recovery from connection loss " + (connected ? "succeeded" : "failed")); aapsLogger.debug(LTag.PUMP, "Recovery from connection loss " + (connected ? "succeeded" : "failed"));
return connected; return connected;
} }
@ -449,17 +455,16 @@ public class RuffyScripter implements RuffyCommands {
MenuType type = menu.getType(); MenuType type = menu.getType();
if (type != MenuType.WARNING_OR_ERROR && type != MenuType.MAIN_MENU) { if (type != MenuType.WARNING_OR_ERROR && type != MenuType.MAIN_MENU) {
try { try {
log.debug("Command execution yielded an error, returning to main menu"); aapsLogger.debug(LTag.PUMP, "Command execution yielded an error, returning to main menu");
returnToRootMenu(); returnToRootMenu();
} catch (Exception e) { } catch (Exception e) {
log.warn("Error returning to main menu, when trying to recover from command failure", e); aapsLogger.warn(LTag.PUMP, "Error returning to main menu, when trying to recover from command failure", e);
} }
} }
try { try {
PumpState pumpState = readPumpStateInternal(); return readPumpStateInternal();
return pumpState;
} catch (Exception e) { } catch (Exception e) {
log.debug("Reading pump state during recovery failed", e); aapsLogger.debug(LTag.PUMP, "Reading pump state during recovery failed", e);
return new PumpState(); return new PumpState();
} }
} }
@ -474,8 +479,8 @@ public class RuffyScripter implements RuffyCommands {
} }
boolean connectInitSuccessful = ruffyService.doRTConnect() == 0; boolean connectInitSuccessful = ruffyService.doRTConnect() == 0;
log.debug("Connect init successful: " + connectInitSuccessful); aapsLogger.debug(LTag.PUMP, "Connect init successful: " + connectInitSuccessful);
log.debug("Waiting for first menu update to be sent"); aapsLogger.debug(LTag.PUMP, "Waiting for first menu update to be sent");
long timeoutExpired = System.currentTimeMillis() + 90 * 1000; long timeoutExpired = System.currentTimeMillis() + 90 * 1000;
long initialUpdateTime = menuLastUpdated; long initialUpdateTime = menuLastUpdated;
while (initialUpdateTime == menuLastUpdated) { while (initialUpdateTime == menuLastUpdated) {
@ -488,14 +493,14 @@ public class RuffyScripter implements RuffyCommands {
try { try {
ruffyService.doRTDisconnect(); ruffyService.doRTDisconnect();
} catch (RemoteException e1) { } catch (RemoteException e1) {
log.warn("Disconnect after connect failure failed", e1); aapsLogger.warn(LTag.PUMP, "Disconnect after connect failure failed", e1);
} }
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
try { try {
ruffyService.doRTDisconnect(); ruffyService.doRTDisconnect();
} catch (RemoteException e1) { } catch (RemoteException e1) {
log.warn("Disconnect after connect failure failed", e1); aapsLogger.warn(LTag.PUMP, "Disconnect after connect failure failed", e1);
} }
throw new CommandException("Unexpected exception while initiating/restoring pump connection", e); throw new CommandException("Unexpected exception while initiating/restoring pump connection", e);
} }
@ -510,11 +515,11 @@ public class RuffyScripter implements RuffyCommands {
state.timestamp = System.currentTimeMillis(); state.timestamp = System.currentTimeMillis();
Menu menu = currentMenu; Menu menu = currentMenu;
if (menu == null) { if (menu == null) {
log.debug("Returning empty PumpState, menu is unavailable"); aapsLogger.debug(LTag.PUMP, "Returning empty PumpState, menu is unavailable");
return state; return state;
} }
log.debug("Parsing menu: " + menu); aapsLogger.debug(LTag.PUMP, "Parsing menu: " + menu);
MenuType menuType = menu.getType(); MenuType menuType = menu.getType();
state.menu = menuType.name(); state.menu = menuType.name();
@ -577,7 +582,7 @@ public class RuffyScripter implements RuffyCommands {
} }
} }
log.debug("State read: " + state); aapsLogger.debug(LTag.PUMP, "State read: " + state);
return state; return state;
} }
@ -615,7 +620,7 @@ public class RuffyScripter implements RuffyCommands {
throw new CommandException("Interrupted"); throw new CommandException("Interrupted");
Menu menu = this.currentMenu; Menu menu = this.currentMenu;
if (menu == null) { if (menu == null) {
log.error("currentMenu == null, bailing"); aapsLogger.error(LTag.PUMP, "currentMenu == null, bailing");
throw new CommandException("Unable to read current menu"); throw new CommandException("Unable to read current menu");
} }
return menu; return menu;
@ -628,39 +633,39 @@ public class RuffyScripter implements RuffyCommands {
} }
public void pressUpKey() { public void pressUpKey() {
log.debug("Pressing up key"); aapsLogger.debug(LTag.PUMP, "Pressing up key");
pressKey(Key.UP); pressKey(Key.UP);
log.debug("Releasing up key"); aapsLogger.debug(LTag.PUMP, "Releasing up key");
} }
public void pressDownKey() { public void pressDownKey() {
log.debug("Pressing down key"); aapsLogger.debug(LTag.PUMP, "Pressing down key");
pressKey(Key.DOWN); pressKey(Key.DOWN);
log.debug("Releasing down key"); aapsLogger.debug(LTag.PUMP, "Releasing down key");
} }
public void pressCheckKey() { public void pressCheckKey() {
log.debug("Pressing check key"); aapsLogger.debug(LTag.PUMP, "Pressing check key");
pressKey(Key.CHECK); pressKey(Key.CHECK);
log.debug("Releasing check key"); aapsLogger.debug(LTag.PUMP, "Releasing check key");
} }
public void pressMenuKey() { public void pressMenuKey() {
log.debug("Pressing menu key"); aapsLogger.debug(LTag.PUMP, "Pressing menu key");
pressKey(Key.MENU); pressKey(Key.MENU);
log.debug("Releasing menu key"); aapsLogger.debug(LTag.PUMP, "Releasing menu key");
} }
private void pressBackKey() { private void pressBackKey() {
log.debug("Pressing back key"); aapsLogger.debug(LTag.PUMP, "Pressing back key");
pressKey(Key.BACK); pressKey(Key.BACK);
log.debug("Releasing back key"); aapsLogger.debug(LTag.PUMP, "Releasing back key");
} }
public void pressKeyMs(final byte key, long ms) { public void pressKeyMs(final byte key, long ms) {
long stepMs = 100; long stepMs = 100;
try { try {
log.debug("Scroll: Pressing key for " + ms + " ms with step " + stepMs + " ms"); aapsLogger.debug(LTag.PUMP, "Scroll: Pressing key for " + ms + " ms with step " + stepMs + " ms");
ruffyService.rtSendKey(key, true); ruffyService.rtSendKey(key, true);
ruffyService.rtSendKey(key, false); ruffyService.rtSendKey(key, false);
while (ms > stepMs) { while (ms > stepMs) {
@ -670,7 +675,7 @@ public class RuffyScripter implements RuffyCommands {
} }
SystemClock.sleep(ms); SystemClock.sleep(ms);
ruffyService.rtSendKey(Key.NO_KEY, true); ruffyService.rtSendKey(Key.NO_KEY, true);
log.debug("Releasing key"); aapsLogger.debug(LTag.PUMP, "Releasing key");
} catch (Exception e) { } catch (Exception e) {
throw new CommandException("Error while pressing buttons"); throw new CommandException("Error while pressing buttons");
} }
@ -709,7 +714,7 @@ public class RuffyScripter implements RuffyCommands {
int moves = 20; int moves = 20;
MenuType lastSeenMenu = getCurrentMenu().getType(); MenuType lastSeenMenu = getCurrentMenu().getType();
while (lastSeenMenu != desiredMenu) { while (lastSeenMenu != desiredMenu) {
log.debug("Navigating to menu " + desiredMenu + ", current menu: " + lastSeenMenu); aapsLogger.debug(LTag.PUMP, "Navigating to menu " + desiredMenu + ", current menu: " + lastSeenMenu);
moves--; moves--;
if (moves == 0) { if (moves == 0) {
throw new CommandException("Menu not found searching for " + desiredMenu throw new CommandException("Menu not found searching for " + desiredMenu
@ -788,7 +793,7 @@ public class RuffyScripter implements RuffyCommands {
@Override @Override
public CommandResult deliverBolus(double amount, BolusProgressReporter bolusProgressReporter) { public CommandResult deliverBolus(double amount, BolusProgressReporter bolusProgressReporter) {
return runCommand(new BolusCommand(amount, bolusProgressReporter)); return runCommand(new BolusCommand(amount, bolusProgressReporter, aapsLogger));
} }
@Override @Override
@ -796,18 +801,18 @@ public class RuffyScripter implements RuffyCommands {
if (activeCmd instanceof BolusCommand) { if (activeCmd instanceof BolusCommand) {
((BolusCommand) activeCmd).requestCancellation(); ((BolusCommand) activeCmd).requestCancellation();
} else { } else {
log.error("cancelBolus called, but active command is not a bolus:" + activeCmd); aapsLogger.error(LTag.PUMP, "cancelBolus called, but active command is not a bolus:" + activeCmd);
} }
} }
@Override @Override
public CommandResult setTbr(int percent, int duration) { public CommandResult setTbr(int percent, int duration) {
return runCommand(new SetTbrCommand(percent, duration)); return runCommand(new SetTbrCommand(percent, duration, aapsLogger));
} }
@Override @Override
public CommandResult cancelTbr() { public CommandResult cancelTbr() {
return runCommand(new CancelTbrCommand()); return runCommand(new CancelTbrCommand(aapsLogger));
} }
@Override @Override
@ -817,17 +822,17 @@ public class RuffyScripter implements RuffyCommands {
@Override @Override
public CommandResult readHistory(PumpHistoryRequest request) { public CommandResult readHistory(PumpHistoryRequest request) {
return runCommand(new ReadHistoryCommand(request)); return runCommand(new ReadHistoryCommand(request, aapsLogger));
} }
@Override @Override
public CommandResult readBasalProfile() { public CommandResult readBasalProfile() {
return runCommand(new ReadBasalProfileCommand()); return runCommand(new ReadBasalProfileCommand(aapsLogger));
} }
@Override @Override
public CommandResult setBasalProfile(BasalProfile basalProfile) { public CommandResult setBasalProfile(BasalProfile basalProfile) {
return runCommand(new SetBasalProfileCommand(basalProfile)); return runCommand(new SetBasalProfileCommand(basalProfile, aapsLogger));
} }
@Override @Override
@ -887,8 +892,8 @@ public class RuffyScripter implements RuffyCommands {
// when a command returns // when a command returns
WarningOrErrorCode displayedWarning = readWarningOrErrorCode(); WarningOrErrorCode displayedWarning = readWarningOrErrorCode();
while (Objects.equals(displayedWarning.warningCode, warningCode)) { while (Objects.equals(displayedWarning.warningCode, warningCode)) {
waitForScreenUpdate(); waitForScreenUpdate();
displayedWarning = readWarningOrErrorCode(); displayedWarning = readWarningOrErrorCode();
} }
return true; return true;
} }

View file

@ -1,39 +1,41 @@
package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands; package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpWarningCodes;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.RuffyScripter;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.WarningOrErrorCode;
import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.DELIVERED; import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.DELIVERED;
import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.DELIVERING; import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.DELIVERING;
import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.PROGRAMMING; import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.PROGRAMMING;
import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.STOPPED; import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.STOPPED;
import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.STOPPING; import static info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter.State.STOPPING;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BolusProgressReporter;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpWarningCodes;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.RuffyScripter;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.WarningOrErrorCode;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class BolusCommand extends BaseCommand { public class BolusCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(BolusCommand.class);
private final AAPSLogger aapsLogger;
protected final double bolus; protected final double bolus;
private final BolusProgressReporter bolusProgressReporter; private final BolusProgressReporter bolusProgressReporter;
private volatile boolean cancelRequested; private volatile boolean cancelRequested;
public BolusCommand(double bolus, BolusProgressReporter bolusProgressReporter) { public BolusCommand(double bolus, BolusProgressReporter bolusProgressReporter, AAPSLogger aapsLogger) {
this.bolus = bolus; this.bolus = bolus;
this.bolusProgressReporter = bolusProgressReporter; this.bolusProgressReporter = bolusProgressReporter;
this.aapsLogger = aapsLogger;
} }
@Override @Override
@ -57,7 +59,7 @@ public class BolusCommand extends BaseCommand {
if (cancelRequested) { if (cancelRequested) {
bolusProgressReporter.report(STOPPED, 0, 0); bolusProgressReporter.report(STOPPED, 0, 0);
result.success = true; result.success = true;
log.debug("Stage 0: cancelled bolus before programming"); aapsLogger.debug(LTag.PUMP, "Stage 0: cancelled bolus before programming");
return; return;
} }
@ -72,26 +74,26 @@ public class BolusCommand extends BaseCommand {
scripter.returnToRootMenu(); scripter.returnToRootMenu();
bolusProgressReporter.report(STOPPED, 0, 0); bolusProgressReporter.report(STOPPED, 0, 0);
result.success = true; result.success = true;
log.debug("Stage 1: cancelled bolus after programming"); aapsLogger.debug(LTag.PUMP, "Stage 1: cancelled bolus after programming");
return; return;
} }
// confirm bolus // confirm bolus
scripter.verifyMenuIsDisplayed(MenuType.BOLUS_ENTER); scripter.verifyMenuIsDisplayed(MenuType.BOLUS_ENTER);
scripter.pressCheckKey(); scripter.pressCheckKey();
log.debug("Stage 2: bolus confirmed"); aapsLogger.debug(LTag.PUMP, "Stage 2: bolus confirmed");
// the pump displays the entered bolus and waits a few seconds to let user check and cancel // the pump displays the entered bolus and waits a few seconds to let user check and cancel
while (scripter.getCurrentMenu().getType() == MenuType.BOLUS_ENTER) { while (scripter.getCurrentMenu().getType() == MenuType.BOLUS_ENTER) {
if (cancelRequested) { if (cancelRequested) {
log.debug("Stage 2: cancelling during confirmation wait"); aapsLogger.debug(LTag.PUMP, "Stage 2: cancelling during confirmation wait");
bolusProgressReporter.report(STOPPING, 0, 0); bolusProgressReporter.report(STOPPING, 0, 0);
scripter.pressUpKey(); scripter.pressUpKey();
// wait up to 1s for a BOLUS_CANCELLED alert, if it doesn't happen we missed // wait up to 1s for a BOLUS_CANCELLED alert, if it doesn't happen we missed
// the window, simply continue and let the next cancel attempt try its luck // the window, simply continue and let the next cancel attempt try its luck
boolean alertWasCancelled = scripter.confirmAlert(PumpWarningCodes.BOLUS_CANCELLED, 1000); boolean alertWasCancelled = scripter.confirmAlert(PumpWarningCodes.BOLUS_CANCELLED, 1000);
if (alertWasCancelled) { if (alertWasCancelled) {
log.debug("Stage 2: successfully cancelled during confirmation wait"); aapsLogger.debug(LTag.PUMP, "Stage 2: successfully cancelled during confirmation wait");
bolusProgressReporter.report(STOPPED, 0, 0); bolusProgressReporter.report(STOPPED, 0, 0);
result.success = true; result.success = true;
return; return;
@ -113,7 +115,7 @@ public class BolusCommand extends BaseCommand {
Thread cancellationThread = null; Thread cancellationThread = null;
while (bolusRemaining != null || scripter.getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) { while (bolusRemaining != null || scripter.getCurrentMenu().getType() == MenuType.WARNING_OR_ERROR) {
if (cancelRequested && !cancelInProgress) { if (cancelRequested && !cancelInProgress) {
log.debug("Stage 3: cancellation while delivering bolus"); aapsLogger.debug(LTag.PUMP, "Stage 3: cancellation while delivering bolus");
bolusProgressReporter.report(STOPPING, 0, 0); bolusProgressReporter.report(STOPPING, 0, 0);
cancelInProgress = true; cancelInProgress = true;
cancellationThread = new Thread(() -> cancellationThread = new Thread(() ->
@ -139,15 +141,15 @@ public class BolusCommand extends BaseCommand {
} }
scripter.confirmAlert(PumpWarningCodes.BOLUS_CANCELLED, 2000); scripter.confirmAlert(PumpWarningCodes.BOLUS_CANCELLED, 2000);
bolusProgressReporter.report(STOPPED, 0, 0); bolusProgressReporter.report(STOPPED, 0, 0);
log.debug("Stage 3: confirmed BOLUS CANCELLED after cancelling bolus during delivery"); aapsLogger.debug(LTag.PUMP, "Stage 3: confirmed BOLUS CANCELLED after cancelling bolus during delivery");
} else if (Objects.equals(warningCode, PumpWarningCodes.CARTRIDGE_LOW)) { } else if (Objects.equals(warningCode, PumpWarningCodes.CARTRIDGE_LOW)) {
scripter.confirmAlert(PumpWarningCodes.CARTRIDGE_LOW, 2000); scripter.confirmAlert(PumpWarningCodes.CARTRIDGE_LOW, 2000);
result.forwardedWarnings.add(PumpWarningCodes.CARTRIDGE_LOW); result.forwardedWarnings.add(PumpWarningCodes.CARTRIDGE_LOW);
log.debug("Stage 3: confirmed low cartridge alert and forwarding to AAPS"); aapsLogger.debug(LTag.PUMP, "Stage 3: confirmed low cartridge alert and forwarding to AAPS");
} else if (Objects.equals(warningCode, PumpWarningCodes.BATTERY_LOW)) { } else if (Objects.equals(warningCode, PumpWarningCodes.BATTERY_LOW)) {
scripter.confirmAlert(PumpWarningCodes.BATTERY_LOW, 2000); scripter.confirmAlert(PumpWarningCodes.BATTERY_LOW, 2000);
result.forwardedWarnings.add(PumpWarningCodes.BATTERY_LOW); result.forwardedWarnings.add(PumpWarningCodes.BATTERY_LOW);
log.debug("Stage 3: confirmed low battery alert and forwarding to AAPS"); aapsLogger.debug(LTag.PUMP, "Stage 3: confirmed low battery alert and forwarding to AAPS");
} else { } else {
// all other warnings or errors; // all other warnings or errors;
// An occlusion error can also occur during bolus. To read the partially delivered // An occlusion error can also occur during bolus. To read the partially delivered
@ -165,7 +167,7 @@ public class BolusCommand extends BaseCommand {
} }
} }
if (bolusRemaining != null && !Objects.equals(bolusRemaining, lastBolusReported)) { if (bolusRemaining != null && !Objects.equals(bolusRemaining, lastBolusReported)) {
log.debug("Delivering bolus, remaining: " + bolusRemaining); aapsLogger.debug(LTag.PUMP, "Delivering bolus, remaining: " + bolusRemaining);
int percentDelivered = (int) (100 - (bolusRemaining / bolus * 100)); int percentDelivered = (int) (100 - (bolusRemaining / bolus * 100));
bolusProgressReporter.report(DELIVERING, percentDelivered, bolus - bolusRemaining); bolusProgressReporter.report(DELIVERING, percentDelivered, bolus - bolusRemaining);
lastBolusReported = bolusRemaining; lastBolusReported = bolusRemaining;
@ -185,9 +187,9 @@ public class BolusCommand extends BaseCommand {
} }
if (cancelInProgress) { if (cancelInProgress) {
log.debug("Stage 4: bolus was cancelled, with unknown amount delivered"); aapsLogger.debug(LTag.PUMP, "Stage 4: bolus was cancelled, with unknown amount delivered");
} else { } else {
log.debug("Stage 4: full bolus of " + bolus + " U was successfully delivered"); aapsLogger.debug(LTag.PUMP, "Stage 4: full bolus of " + bolus + " U was successfully delivered");
bolusProgressReporter.report(DELIVERED, 100, bolus); bolusProgressReporter.report(DELIVERED, 100, bolus);
} }
result.success = true; result.success = true;
@ -219,12 +221,12 @@ public class BolusCommand extends BaseCommand {
double displayedBolus = scripter.readBlinkingValue(Double.class, MenuAttribute.BOLUS); double displayedBolus = scripter.readBlinkingValue(Double.class, MenuAttribute.BOLUS);
long timeout = System.currentTimeMillis() + 10 * 1000; long timeout = System.currentTimeMillis() + 10 * 1000;
while (timeout > System.currentTimeMillis() && bolus - displayedBolus > 0.05) { while (timeout > System.currentTimeMillis() && bolus - displayedBolus > 0.05) {
log.debug("Waiting for pump to process scrolling input for amount, current: " + displayedBolus + ", desired: " + bolus); aapsLogger.debug(LTag.PUMP, "Waiting for pump to process scrolling input for amount, current: " + displayedBolus + ", desired: " + bolus);
SystemClock.sleep(50); SystemClock.sleep(50);
displayedBolus = scripter.readBlinkingValue(Double.class, MenuAttribute.BOLUS); displayedBolus = scripter.readBlinkingValue(Double.class, MenuAttribute.BOLUS);
} }
log.debug("Final bolus: " + displayedBolus); aapsLogger.debug(LTag.PUMP, "Final bolus: " + displayedBolus);
if (Math.abs(displayedBolus - bolus) > 0.01) { if (Math.abs(displayedBolus - bolus) > 0.01) {
throw new CommandException("Failed to set correct bolus. Expected: " + bolus + ", actual: " + displayedBolus); throw new CommandException("Failed to set correct bolus. Expected: " + bolus + ", actual: " + displayedBolus);
} }
@ -240,7 +242,7 @@ public class BolusCommand extends BaseCommand {
} }
public void requestCancellation() { public void requestCancellation() {
log.debug("Bolus cancellation requested"); aapsLogger.debug(LTag.PUMP, "Bolus cancellation requested");
cancelRequested = true; cancelRequested = true;
bolusProgressReporter.report(STOPPING, 0, 0); bolusProgressReporter.report(STOPPING, 0, 0);
} }

View file

@ -3,15 +3,19 @@ package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.slf4j.Logger;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpWarningCodes; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpWarningCodes;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class CancelTbrCommand extends BaseCommand { public class CancelTbrCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(CancelTbrCommand.class); private final AAPSLogger aapsLogger;
public CancelTbrCommand(AAPSLogger aapsLogger) {
this.aapsLogger = aapsLogger;
}
@Override @Override
public Integer getReconnectWarningId() { public Integer getReconnectWarningId() {
return PumpWarningCodes.TBR_CANCELLED; return PumpWarningCodes.TBR_CANCELLED;
@ -28,9 +32,9 @@ public class CancelTbrCommand extends BaseCommand {
return; return;
} }
log.debug("Cancelling active TBR of " + pumpState.tbrPercent aapsLogger.debug(LTag.PUMP, "Cancelling active TBR of " + pumpState.tbrPercent
+ "% with " + pumpState.tbrRemainingDuration + " min remaining"); + "% with " + pumpState.tbrRemainingDuration + " min remaining");
SetTbrCommand setTbrCommand = new SetTbrCommand(100, 0); SetTbrCommand setTbrCommand = new SetTbrCommand(100, 0, aapsLogger);
setTbrCommand.setScripter(scripter); setTbrCommand.setScripter(scripter);
setTbrCommand.execute(); setTbrCommand.execute();
result = setTbrCommand.result; result = setTbrCommand.result;

View file

@ -1,19 +1,25 @@
package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands; package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands;
import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.Menu; import org.monkey.d.ruffy.ruffy.driver.display.Menu;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute; import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import java.util.Arrays; import java.util.Arrays;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BasalProfile; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BasalProfile;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class ReadBasalProfileCommand extends BaseCommand { public class ReadBasalProfileCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(ReadBasalProfileCommand.class); private final AAPSLogger aapsLogger;
public ReadBasalProfileCommand(AAPSLogger aapsLogger) {
this.aapsLogger = aapsLogger;
}
@Override @Override
public void execute() { public void execute() {
@ -44,10 +50,10 @@ public class ReadBasalProfileCommand extends BaseCommand {
throw new CommandException("Attempting to read basal rate for hour " + i + ", but hour " + startTime.getHour() + " is displayed"); throw new CommandException("Attempting to read basal rate for hour " + i + ", but hour " + startTime.getHour() + " is displayed");
} }
basalProfile.hourlyRates[i] = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE); basalProfile.hourlyRates[i] = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE);
log.debug("Read basal profile, hour " + i + ": " + basalProfile.hourlyRates[i]); aapsLogger.debug(LTag.PUMP, "Read basal profile, hour " + i + ": " + basalProfile.hourlyRates[i]);
} }
log.debug("Basal profile read: " + Arrays.toString(basalProfile.hourlyRates)); aapsLogger.debug(LTag.PUMP, "Basal profile read: " + Arrays.toString(basalProfile.hourlyRates));
scripter.returnToRootMenu(); scripter.returnToRootMenu();
scripter.verifyRootMenuIsDisplayed(); scripter.verifyRootMenuIsDisplayed();
@ -55,7 +61,7 @@ public class ReadBasalProfileCommand extends BaseCommand {
result.success(true).basalProfile(basalProfile); result.success(true).basalProfile(basalProfile);
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "ReadBasalProfileCommand{}"; return "ReadBasalProfileCommand{}";
} }

View file

@ -6,27 +6,27 @@ import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuDate; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuDate;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpAlert; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpAlert;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistory; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistory;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistoryRequest; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistoryRequest;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tbr; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tbr;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class ReadHistoryCommand extends BaseCommand { public class ReadHistoryCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(ReadHistoryCommand.class); private final AAPSLogger aapsLogger;
private final PumpHistoryRequest request; private final PumpHistoryRequest request;
private final PumpHistory history = new PumpHistory(); private final PumpHistory history = new PumpHistory();
public ReadHistoryCommand(PumpHistoryRequest request) { public ReadHistoryCommand(PumpHistoryRequest request, AAPSLogger aapsLogger) {
this.request = request; this.request = request;
this.aapsLogger = aapsLogger;
} }
@Override @Override
@ -106,30 +106,28 @@ public class ReadHistoryCommand extends BaseCommand {
} }
} }
if (log.isDebugEnabled()) { if (!history.bolusHistory.isEmpty()) {
if (!history.bolusHistory.isEmpty()) { aapsLogger.debug(LTag.PUMP, "Read bolus history (" + history.bolusHistory.size() + "):");
log.debug("Read bolus history (" + history.bolusHistory.size() + "):"); for (Bolus bolus : history.bolusHistory) {
for (Bolus bolus : history.bolusHistory) { aapsLogger.debug(LTag.PUMP, new Date(bolus.timestamp) + ": " + bolus.toString());
log.debug(new Date(bolus.timestamp) + ": " + bolus.toString());
}
} }
if (!history.pumpAlertHistory.isEmpty()) { }
log.debug("Read error history (" + history.pumpAlertHistory.size() + "):"); if (!history.pumpAlertHistory.isEmpty()) {
for (PumpAlert pumpAlert : history.pumpAlertHistory) { aapsLogger.debug(LTag.PUMP, "Read error history (" + history.pumpAlertHistory.size() + "):");
log.debug(new Date(pumpAlert.timestamp) + ": " + pumpAlert.toString()); for (PumpAlert pumpAlert : history.pumpAlertHistory) {
} aapsLogger.debug(LTag.PUMP, new Date(pumpAlert.timestamp) + ": " + pumpAlert.toString());
} }
if (!history.tddHistory.isEmpty()) { }
log.debug("Read TDD history (" + history.tddHistory.size() + "):"); if (!history.tddHistory.isEmpty()) {
for (Tdd tdd : history.tddHistory) { aapsLogger.debug(LTag.PUMP, "Read TDD history (" + history.tddHistory.size() + "):");
log.debug(new Date(tdd.timestamp) + ": " + tdd.toString()); for (Tdd tdd : history.tddHistory) {
} aapsLogger.debug(LTag.PUMP, new Date(tdd.timestamp) + ": " + tdd.toString());
} }
if (!history.tbrHistory.isEmpty()) { }
log.debug("Read TBR history (" + history.tbrHistory.size() + "):"); if (!history.tbrHistory.isEmpty()) {
for (Tbr tbr : history.tbrHistory) { aapsLogger.debug(LTag.PUMP, "Read TBR history (" + history.tbrHistory.size() + "):");
log.debug(new Date(tbr.timestamp) + ": " + tbr.toString()); for (Tbr tbr : history.tbrHistory) {
} aapsLogger.debug(LTag.PUMP, new Date(tbr.timestamp) + ": " + tbr.toString());
} }
} }
@ -147,9 +145,9 @@ public class ReadHistoryCommand extends BaseCommand {
if (requestedTime != PumpHistoryRequest.FULL && tdd.timestamp < requestedTime) { if (requestedTime != PumpHistoryRequest.FULL && tdd.timestamp < requestedTime) {
break; break;
} }
log.debug("Read TDD record #" + record + "/" + totalRecords); aapsLogger.debug(LTag.PUMP, "Read TDD record #" + record + "/" + totalRecords);
history.tddHistory.add(tdd); history.tddHistory.add(tdd);
log.debug("Parsed " + scripter.getCurrentMenu().toString() + " => " + tdd); aapsLogger.debug(LTag.PUMP, "Parsed " + scripter.getCurrentMenu() + " => " + tdd);
if (record == totalRecords) { if (record == totalRecords) {
break; break;
} }
@ -174,7 +172,7 @@ public class ReadHistoryCommand extends BaseCommand {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.set(year, date.getMonth() - 1, date.getDay(), 0, 0, 0); calendar.set(year, date.getMonth() - 1, date.getDay(), 0, 0, 0);
long time = calendar.getTimeInMillis(); long time = calendar.getTimeInMillis();
time = time - time%1000; time = time - time % 1000;
return new Tdd(time, dailyTotal); return new Tdd(time, dailyTotal);
} }
@ -186,9 +184,9 @@ public class ReadHistoryCommand extends BaseCommand {
if (requestedTime != PumpHistoryRequest.FULL && tbr.timestamp < requestedTime) { if (requestedTime != PumpHistoryRequest.FULL && tbr.timestamp < requestedTime) {
break; break;
} }
log.debug("Read TBR record #" + record + "/" + totalRecords); aapsLogger.debug(LTag.PUMP, "Read TBR record #" + record + "/" + totalRecords);
history.tbrHistory.add(tbr); history.tbrHistory.add(tbr);
log.debug("Parsed " + scripter.getCurrentMenu().toString() + " => " + tbr); aapsLogger.debug(LTag.PUMP, "Parsed " + scripter.getCurrentMenu() + " => " + tbr);
if (record == totalRecords) { if (record == totalRecords) {
break; break;
} }
@ -206,7 +204,7 @@ public class ReadHistoryCommand extends BaseCommand {
Double percentage = (Double) scripter.getCurrentMenu().getAttribute(MenuAttribute.TBR); Double percentage = (Double) scripter.getCurrentMenu().getAttribute(MenuAttribute.TBR);
MenuTime durationTime = (MenuTime) scripter.getCurrentMenu().getAttribute(MenuAttribute.RUNTIME); MenuTime durationTime = (MenuTime) scripter.getCurrentMenu().getAttribute(MenuAttribute.RUNTIME);
int duration = durationTime.getHour() * 60 + durationTime.getMinute(); int duration = durationTime.getHour() * 60 + durationTime.getMinute();
long tbrStartDate = readRecordDate() - duration * 60 * 1000; long tbrStartDate = readRecordDate() - duration * 60L * 1000;
return new Tbr(tbrStartDate, duration, percentage.intValue()); return new Tbr(tbrStartDate, duration, percentage.intValue());
} }
@ -218,9 +216,9 @@ public class ReadHistoryCommand extends BaseCommand {
if (requestedTime != PumpHistoryRequest.FULL && bolus.timestamp < requestedTime) { if (requestedTime != PumpHistoryRequest.FULL && bolus.timestamp < requestedTime) {
break; break;
} }
log.debug("Read bolus record #" + record + "/" + totalRecords); aapsLogger.debug(LTag.PUMP, "Read bolus record #" + record + "/" + totalRecords);
history.bolusHistory.add(bolus); history.bolusHistory.add(bolus);
log.debug("Parsed " + scripter.getCurrentMenu().toString() + " => " + bolus); aapsLogger.debug(LTag.PUMP, "Parsed " + scripter.getCurrentMenu() + " => " + bolus);
if (record == totalRecords) { if (record == totalRecords) {
break; break;
} }
@ -240,9 +238,9 @@ public class ReadHistoryCommand extends BaseCommand {
if (requestedTime != PumpHistoryRequest.FULL && error.timestamp < requestedTime) { if (requestedTime != PumpHistoryRequest.FULL && error.timestamp < requestedTime) {
break; break;
} }
log.debug("Read alert record #" + record + "/" + totalRecords); aapsLogger.debug(LTag.PUMP, "Read alert record #" + record + "/" + totalRecords);
history.pumpAlertHistory.add(error); history.pumpAlertHistory.add(error);
log.debug("Parsed " + scripter.getCurrentMenu().toString() + " => " + error); aapsLogger.debug(LTag.PUMP, "Parsed " + scripter.getCurrentMenu() + " => " + error);
if (record == totalRecords) { if (record == totalRecords) {
break; break;
} }
@ -265,7 +263,7 @@ public class ReadHistoryCommand extends BaseCommand {
return new PumpAlert(recordDate, warningCode, errorCode, message); return new PumpAlert(recordDate, warningCode, errorCode, message);
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "ReadHistoryCommand{" + return "ReadHistoryCommand{" +
"request=" + request + "request=" + request +

View file

@ -1,24 +1,27 @@
package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands; package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands;
import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute; import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistory; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistory;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class ReadQuickInfoCommand extends BaseCommand { public class ReadQuickInfoCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(ReadQuickInfoCommand.class); private final AAPSLogger aapsLogger;
private final int numberOfBolusRecordsToRetrieve; private final int numberOfBolusRecordsToRetrieve;
public ReadQuickInfoCommand(int numberOfBolusRecordsToRetrieve) { public ReadQuickInfoCommand(int numberOfBolusRecordsToRetrieve, AAPSLogger aapsLogger) {
this.numberOfBolusRecordsToRetrieve = numberOfBolusRecordsToRetrieve; this.numberOfBolusRecordsToRetrieve = numberOfBolusRecordsToRetrieve;
this.aapsLogger = aapsLogger;
} }
@Override @Override
@ -53,12 +56,10 @@ public class ReadQuickInfoCommand extends BaseCommand {
record = (int) scripter.getCurrentMenu().getAttribute(MenuAttribute.CURRENT_RECORD); record = (int) scripter.getCurrentMenu().getAttribute(MenuAttribute.CURRENT_RECORD);
} }
} }
if (log.isDebugEnabled()) { if (!result.history.bolusHistory.isEmpty()) {
if (!result.history.bolusHistory.isEmpty()) { aapsLogger.debug(LTag.PUMP, "Read bolus history (" + result.history.bolusHistory.size() + "):");
log.debug("Read bolus history (" + result.history.bolusHistory.size() + "):"); for (Bolus bolus : result.history.bolusHistory) {
for (Bolus bolus : result.history.bolusHistory) { aapsLogger.debug(LTag.PUMP, new Date(bolus.timestamp) + ": " + bolus);
log.debug(new Date(bolus.timestamp) + ": " + bolus.toString());
}
} }
} }
} }
@ -71,7 +72,7 @@ public class ReadQuickInfoCommand extends BaseCommand {
return false; return false;
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "ReadQuickInfoCommand{}"; return "ReadQuickInfoCommand{}";
} }

View file

@ -2,26 +2,29 @@ package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.Menu; import org.monkey.d.ruffy.ruffy.driver.display.Menu;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute; import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BasalProfile; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.BasalProfile;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class SetBasalProfileCommand extends BaseCommand { public class SetBasalProfileCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(SetBasalProfileCommand.class); private final AAPSLogger aapsLogger;
private final BasalProfile basalProfile; private final BasalProfile basalProfile;
public SetBasalProfileCommand(BasalProfile basalProfile) { public SetBasalProfileCommand(BasalProfile basalProfile, AAPSLogger aapsLogger) {
this.basalProfile = basalProfile; this.basalProfile = basalProfile;
this.aapsLogger = aapsLogger;
} }
@Override @Override
@ -52,7 +55,7 @@ public class SetBasalProfileCommand extends BaseCommand {
verifyDisplayedRate(requestedRate, change); verifyDisplayedRate(requestedRate, change);
} }
log.debug("Set basal profile, hour " + i + ": " + requestedRate); aapsLogger.debug(LTag.PUMP, "Set basal profile, hour " + i + ": " + requestedRate);
} }
// move from hourly values to basal total // move from hourly values to basal total
@ -78,9 +81,9 @@ public class SetBasalProfileCommand extends BaseCommand {
private long inputBasalRate(double requestedRate) { private long inputBasalRate(double requestedRate) {
double currentRate = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE); double currentRate = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE);
log.debug("Current rate: " + currentRate + ", requested: " + requestedRate); aapsLogger.debug(LTag.PUMP, "Current rate: " + currentRate + ", requested: " + requestedRate);
// the pump changes steps size from 0.01 to 0.05 when crossing 1.00 U // the pump changes steps size from 0.01 to 0.05 when crossing 1.00 U
long steps = 0; long steps;
if (currentRate == 0) { if (currentRate == 0) {
// edge case of starting from 0.00; // edge case of starting from 0.00;
steps = stepsToOne(0.05) - stepsToOne(requestedRate) + 1; steps = stepsToOne(0.05) - stepsToOne(requestedRate) + 1;
@ -90,10 +93,10 @@ public class SetBasalProfileCommand extends BaseCommand {
if (steps == 0) { if (steps == 0) {
return 0; return 0;
} }
log.debug("Pressing " + (steps > 0 ? "up" : "down") + " " + Math.abs(steps) + " times"); aapsLogger.debug(LTag.PUMP, "Pressing " + (steps > 0 ? "up" : "down") + " " + Math.abs(steps) + " times");
for (int i = 0; i < Math.abs(steps); i++) { for (int i = 0; i < Math.abs(steps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.BASAL_SET); scripter.verifyMenuIsDisplayed(MenuType.BASAL_SET);
log.debug("Push #" + (i + 1) + "/" + Math.abs(steps)); aapsLogger.debug(LTag.PUMP, "Push #" + (i + 1) + "/" + Math.abs(steps));
if (steps > 0) scripter.pressUpKey(); if (steps > 0) scripter.pressUpKey();
else scripter.pressDownKey(); else scripter.pressDownKey();
SystemClock.sleep(50); SystemClock.sleep(50);
@ -119,13 +122,13 @@ public class SetBasalProfileCommand extends BaseCommand {
while (timeout > System.currentTimeMillis() while (timeout > System.currentTimeMillis()
&& ((change > 0 && requestedRate - displayedRate > 0.001) // displayedRate < requestedRate) && ((change > 0 && requestedRate - displayedRate > 0.001) // displayedRate < requestedRate)
|| (change < 0 && displayedRate - requestedRate > 0.001))) { //displayedRate > requestedRate))) { || (change < 0 && displayedRate - requestedRate > 0.001))) { //displayedRate > requestedRate))) {
log.debug("Waiting for pump to process scrolling input for rate, current: " aapsLogger.debug(LTag.PUMP, "Waiting for pump to process scrolling input for rate, current: "
+ displayedRate + ", desired: " + requestedRate + ", scrolling " + displayedRate + ", desired: " + requestedRate + ", scrolling "
+ (change > 0 ? "up" : "down")); + (change > 0 ? "up" : "down"));
scripter.waitForScreenUpdate(); scripter.waitForScreenUpdate();
displayedRate = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE); displayedRate = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE);
} }
log.debug("Final displayed basal rate: " + displayedRate); aapsLogger.debug(LTag.PUMP, "Final displayed basal rate: " + displayedRate);
if (Math.abs(displayedRate - requestedRate) > 0.001) { if (Math.abs(displayedRate - requestedRate) > 0.001) {
throw new CommandException("Failed to set basal rate, requested: " throw new CommandException("Failed to set basal rate, requested: "
+ requestedRate + ", actual: " + displayedRate); + requestedRate + ", actual: " + displayedRate);
@ -153,7 +156,7 @@ public class SetBasalProfileCommand extends BaseCommand {
return violations; return violations;
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "SetBasalProfileCommand{" + return "SetBasalProfileCommand{" +
"basalProfile=" + basalProfile + "basalProfile=" + basalProfile +

View file

@ -2,29 +2,32 @@ package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.commands;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.annotation.NonNull;
import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute; import org.monkey.d.ruffy.ruffy.driver.display.MenuAttribute;
import org.monkey.d.ruffy.ruffy.driver.display.MenuType; import org.monkey.d.ruffy.ruffy.driver.display.MenuType;
import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime; import org.monkey.d.ruffy.ruffy.driver.display.menu.MenuTime;
import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import info.nightscout.shared.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpWarningCodes; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpWarningCodes;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.WarningOrErrorCode; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.WarningOrErrorCode;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
public class SetTbrCommand extends BaseCommand { public class SetTbrCommand extends BaseCommand {
private static final Logger log = StacktraceLoggerWrapper.getLogger(SetTbrCommand.class); private final AAPSLogger aapsLogger;
private final long percentage; private final long percentage;
private final long duration; private final long duration;
public SetTbrCommand(long percentage, long duration) { public SetTbrCommand(long percentage, long duration, AAPSLogger aapsLogger) {
this.percentage = percentage; this.percentage = percentage;
this.duration = duration; this.duration = duration;
this.aapsLogger = aapsLogger;
} }
@Override @Override
@ -116,7 +119,7 @@ public class SetTbrCommand extends BaseCommand {
PumpState state = scripter.readPumpStateInternal(); PumpState state = scripter.readPumpStateInternal();
if (state.tbrRemainingDuration == 1) { if (state.tbrRemainingDuration == 1) {
while (state.tbrActive && System.currentTimeMillis() < timeout) { while (state.tbrActive && System.currentTimeMillis() < timeout) {
log.debug("Waiting for existing TBR to run out to avoid alert while setting TBR"); aapsLogger.debug(LTag.PUMP, "Waiting for existing TBR to run out to avoid alert while setting TBR");
scripter.waitForScreenUpdate(); scripter.waitForScreenUpdate();
state = scripter.readPumpStateInternal(); state = scripter.readPumpStateInternal();
} }
@ -140,14 +143,14 @@ public class SetTbrCommand extends BaseCommand {
private boolean inputTbrPercentage() { private boolean inputTbrPercentage() {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long currentPercent = readDisplayedPercentage(); long currentPercent = readDisplayedPercentage();
log.debug("Current TBR %: " + currentPercent); aapsLogger.debug(LTag.PUMP, "Current TBR %: " + currentPercent);
long percentageChange = percentage - currentPercent; long percentageChange = percentage - currentPercent;
long percentageSteps = percentageChange / 10; long percentageSteps = percentageChange / 10;
boolean increasePercentage = percentageSteps > 0; boolean increasePercentage = percentageSteps > 0;
log.debug("Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times"); aapsLogger.debug(LTag.PUMP, "Pressing " + (increasePercentage ? "up" : "down") + " " + percentageSteps + " times");
for (int i = 0; i < Math.abs(percentageSteps); i++) { for (int i = 0; i < Math.abs(percentageSteps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
log.debug("Push #" + (i + 1) + "/" + Math.abs(percentageSteps)); aapsLogger.debug(LTag.PUMP, "Push #" + (i + 1) + "/" + Math.abs(percentageSteps));
if (increasePercentage) scripter.pressUpKey(); if (increasePercentage) scripter.pressUpKey();
else scripter.pressDownKey(); else scripter.pressDownKey();
SystemClock.sleep(50); SystemClock.sleep(50);
@ -163,13 +166,13 @@ public class SetTbrCommand extends BaseCommand {
while (timeout > System.currentTimeMillis() while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedPercentage < percentage) && ((increasingPercentage && displayedPercentage < percentage)
|| (!increasingPercentage && displayedPercentage > percentage))) { || (!increasingPercentage && displayedPercentage > percentage))) {
log.debug("Waiting for pump to process scrolling input for percentage, current: " aapsLogger.debug(LTag.PUMP, "Waiting for pump to process scrolling input for percentage, current: "
+ displayedPercentage + ", desired: " + percentage + ", scrolling " + displayedPercentage + ", desired: " + percentage + ", scrolling "
+ (increasingPercentage ? "up" : "down")); + (increasingPercentage ? "up" : "down"));
SystemClock.sleep(50); SystemClock.sleep(50);
displayedPercentage = readDisplayedPercentage(); displayedPercentage = readDisplayedPercentage();
} }
log.debug("Final displayed TBR percentage: " + displayedPercentage); aapsLogger.debug(LTag.PUMP, "Final displayed TBR percentage: " + displayedPercentage);
if (displayedPercentage != percentage) { if (displayedPercentage != percentage) {
throw new CommandException("Failed to set TBR percentage, requested: " throw new CommandException("Failed to set TBR percentage, requested: "
+ percentage + ", actual: " + displayedPercentage); + percentage + ", actual: " + displayedPercentage);
@ -179,11 +182,11 @@ public class SetTbrCommand extends BaseCommand {
// value due to due scrolling taking extremely long // value due to due scrolling taking extremely long
SystemClock.sleep(1000); SystemClock.sleep(1000);
scripter.verifyMenuIsDisplayed(MenuType.TBR_SET); scripter.verifyMenuIsDisplayed(MenuType.TBR_SET);
long refreshedDisplayedTbrPecentage = readDisplayedPercentage(); long refreshedDisplayedTbrPercentage = readDisplayedPercentage();
if (displayedPercentage != refreshedDisplayedTbrPecentage) { if (displayedPercentage != refreshedDisplayedTbrPercentage) {
throw new CommandException("Failed to set TBR percentage: " + throw new CommandException("Failed to set TBR percentage: " +
"percentage changed after input stopped from " "percentage changed after input stopped from "
+ displayedPercentage + " -> " + refreshedDisplayedTbrPecentage); + displayedPercentage + " -> " + refreshedDisplayedTbrPercentage);
} }
} }
@ -191,10 +194,10 @@ public class SetTbrCommand extends BaseCommand {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
long durationSteps = calculateDurationSteps(); long durationSteps = calculateDurationSteps();
boolean increaseDuration = durationSteps > 0; boolean increaseDuration = durationSteps > 0;
log.debug("Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times"); aapsLogger.debug(LTag.PUMP, "Pressing " + (increaseDuration ? "up" : "down") + " " + durationSteps + " times");
for (int i = 0; i < Math.abs(durationSteps); i++) { for (int i = 0; i < Math.abs(durationSteps); i++) {
scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION); scripter.verifyMenuIsDisplayed(MenuType.TBR_DURATION);
log.debug("Push #" + (i + 1) + "/" + Math.abs(durationSteps)); aapsLogger.debug(LTag.PUMP, "Push #" + (i + 1) + "/" + Math.abs(durationSteps));
if (increaseDuration) scripter.pressUpKey(); if (increaseDuration) scripter.pressUpKey();
else scripter.pressDownKey(); else scripter.pressDownKey();
SystemClock.sleep(50); SystemClock.sleep(50);
@ -204,7 +207,7 @@ public class SetTbrCommand extends BaseCommand {
private long calculateDurationSteps() { private long calculateDurationSteps() {
long currentDuration = readDisplayedDuration(); long currentDuration = readDisplayedDuration();
log.debug("Initial TBR duration: " + currentDuration); aapsLogger.debug(LTag.PUMP, "Initial TBR duration: " + currentDuration);
long difference = duration - currentDuration; long difference = duration - currentDuration;
long durationSteps = difference / 15; long durationSteps = difference / 15;
@ -224,14 +227,14 @@ public class SetTbrCommand extends BaseCommand {
while (timeout > System.currentTimeMillis() while (timeout > System.currentTimeMillis()
&& ((increasingPercentage && displayedDuration < duration) && ((increasingPercentage && displayedDuration < duration)
|| (!increasingPercentage && displayedDuration > duration))) { || (!increasingPercentage && displayedDuration > duration))) {
log.debug("Waiting for pump to process scrolling input for duration, current: " aapsLogger.debug(LTag.PUMP, "Waiting for pump to process scrolling input for duration, current: "
+ displayedDuration + ", desired: " + duration + displayedDuration + ", desired: " + duration
+ ", scrolling " + (increasingPercentage ? "up" : "down")); + ", scrolling " + (increasingPercentage ? "up" : "down"));
SystemClock.sleep(50); SystemClock.sleep(50);
displayedDuration = readDisplayedDuration(); displayedDuration = readDisplayedDuration();
} }
log.debug("Final displayed TBR duration: " + displayedDuration); aapsLogger.debug(LTag.PUMP, "Final displayed TBR duration: " + displayedDuration);
if (displayedDuration != duration) { if (displayedDuration != duration) {
throw new CommandException("Failed to set TBR duration, requested: " throw new CommandException("Failed to set TBR duration, requested: "
+ duration + ", actual: " + displayedDuration); + duration + ", actual: " + displayedDuration);
@ -264,7 +267,7 @@ public class SetTbrCommand extends BaseCommand {
private long readDisplayedDuration() { private long readDisplayedDuration() {
MenuTime duration = scripter.readBlinkingValue(MenuTime.class, MenuAttribute.RUNTIME); MenuTime duration = scripter.readBlinkingValue(MenuTime.class, MenuAttribute.RUNTIME);
return duration.getHour() * 60 + duration.getMinute(); return duration.getHour() * 60L + duration.getMinute();
} }
private long readDisplayedPercentage() { private long readDisplayedPercentage() {
@ -276,7 +279,7 @@ public class SetTbrCommand extends BaseCommand {
return true; return true;
} }
@Override @NonNull @Override
public String toString() { public String toString() {
return "SetTbrCommand{" + return "SetTbrCommand{" +
"percentage=" + percentage + "percentage=" + percentage +

View file

@ -28,7 +28,7 @@ class ResourceHelperImplementation @Inject constructor(private val context: Cont
} catch (exception: Exception) { } catch (exception: Exception) {
val resourceName = context.resources.getResourceEntryName(id) val resourceName = context.resources.getResourceEntryName(id)
val resourceValue = context.getString(id) val resourceValue = context.getString(id)
val currentLocale: Locale = context.resources.configuration.locale val currentLocale: Locale = context.resources.configuration.locales[0]
fabricPrivacy.logMessage("Failed to get string for resource $resourceName ($id) '$resourceValue' for locale $currentLocale with args ${args.map{it.toString()}}") fabricPrivacy.logMessage("Failed to get string for resource $resourceName ($id) '$resourceValue' for locale $currentLocale with args ${args.map{it.toString()}}")
fabricPrivacy.logException(exception) fabricPrivacy.logException(exception)
try { try {