MDT refactor pass 7

This commit is contained in:
Milos Kozak 2020-04-27 13:24:35 +02:00
parent 7b9247b1a0
commit f686c81115
7 changed files with 90 additions and 162 deletions

View file

@ -37,6 +37,7 @@ public abstract class RileyLinkCommunicationManager {
@Inject MedtronicPumpStatus medtronicPumpStatus; @Inject MedtronicPumpStatus medtronicPumpStatus;
@Inject RileyLinkUtil rileyLinkUtil; @Inject RileyLinkUtil rileyLinkUtil;
@Inject MedtronicUtil medtronicUtil;
private final int SCAN_TIMEOUT = 1500; private final int SCAN_TIMEOUT = 1500;
@ -51,8 +52,6 @@ public abstract class RileyLinkCommunicationManager {
protected RileyLinkServiceData rileyLinkServiceData; protected RileyLinkServiceData rileyLinkServiceData;
private long nextWakeUpRequired = 0L; private long nextWakeUpRequired = 0L;
// internal flag
private boolean showPumpMessages = true;
private int timeoutCount = 0; private int timeoutCount = 0;
@ -84,6 +83,8 @@ public abstract class RileyLinkCommunicationManager {
public <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class<E> clazz) public <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class<E> clazz)
throws RileyLinkCommunicationException { throws RileyLinkCommunicationException {
// internal flag
boolean showPumpMessages = true;
if (showPumpMessages) { if (showPumpMessages) {
aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData()));
} }
@ -152,7 +153,7 @@ public abstract class RileyLinkCommunicationManager {
// **** FIXME: this wakeup doesn't seem to work well... must revisit // **** FIXME: this wakeup doesn't seem to work well... must revisit
// receiverDeviceAwakeForMinutes = duration_minutes; // receiverDeviceAwakeForMinutes = duration_minutes;
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp); medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp);
if (force) if (force)
nextWakeUpRequired = 0L; nextWakeUpRequired = 0L;
@ -193,7 +194,7 @@ public abstract class RileyLinkCommunicationManager {
public double tuneForDevice() { public double tuneForDevice() {
return scanForDevice(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies()); return scanForDevice(rileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies());
} }
@ -207,7 +208,7 @@ public abstract class RileyLinkCommunicationManager {
*/ */
public boolean isValidFrequency(double frequency) { public boolean isValidFrequency(double frequency) {
double[] scanFrequencies = RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies(); double[] scanFrequencies = rileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies();
if (scanFrequencies.length == 1) { if (scanFrequencies.length == 1) {
return RileyLinkUtil.isSame(scanFrequencies[0], frequency); return RileyLinkUtil.isSame(scanFrequencies[0], frequency);

View file

@ -63,14 +63,14 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject MedtronicPumpStatus medtronicPumpStatus; @Inject MedtronicPumpStatus medtronicPumpStatus;
@Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicPumpPlugin medtronicPumpPlugin;
@Inject MedtronicConverter medtronicConverter;
@Inject MedtronicUtil medtronicUtil;
private final int MAX_COMMAND_TRIES = 3; private final int MAX_COMMAND_TRIES = 3;
private final int DEFAULT_TIMEOUT = 2000; private final int DEFAULT_TIMEOUT = 2000;
private final long RILEYLINK_TIMEOUT = 15 * 60 * 1000; // 15 min private final long RILEYLINK_TIMEOUT = 15 * 60 * 1000; // 15 min
static MedtronicCommunicationManager medtronicCommunicationManager; private String errorMessage;
String errorMessage;
private MedtronicConverter medtronicConverter;
private boolean debugSetCommands = false; private boolean debugSetCommands = false;
private MedtronicPumpHistoryDecoder pumpHistoryDecoder; private MedtronicPumpHistoryDecoder pumpHistoryDecoder;
@ -79,25 +79,17 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public MedtronicCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { public MedtronicCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) {
super(injector, rfspy); super(injector, rfspy);
medtronicCommunicationManager = this;
this.medtronicConverter = new MedtronicConverter();
this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder(); this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder();
medtronicPumpStatus.previousConnection = sp.getLong( medtronicPumpStatus.previousConnection = sp.getLong(
RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L);
} }
public static MedtronicCommunicationManager getInstance() {
return medtronicCommunicationManager;
}
@Override @Override
public <E extends RLMessage> E createResponseMessage(byte[] payload, Class<E> clazz) { public <E extends RLMessage> E createResponseMessage(byte[] payload, Class<E> clazz) {
PumpMessage pumpMessage = new PumpMessage(payload); PumpMessage pumpMessage = new PumpMessage(payload);
return (E) pumpMessage; return (E) pumpMessage;
} }
public void setDoWakeUpBeforeCommand(boolean doWakeUp) { public void setDoWakeUpBeforeCommand(boolean doWakeUp) {
this.doWakeUpBeforeCommand = doWakeUp; this.doWakeUpBeforeCommand = doWakeUp;
} }
@ -117,10 +109,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
*/ */
public boolean isDeviceReachable(boolean canPreventTuneUp) { public boolean isDeviceReachable(boolean canPreventTuneUp) {
PumpDeviceState state = MedtronicUtil.getInstance().getPumpDeviceState(); PumpDeviceState state = medtronicUtil.getPumpDeviceState();
if (state != PumpDeviceState.PumpUnreachable) if (state != PumpDeviceState.PumpUnreachable)
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp); medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp);
for (int retry = 0; retry < 5; retry++) { for (int retry = 0; retry < 5; retry++) {
@ -136,7 +128,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
if (state != PumpDeviceState.PumpUnreachable) if (state != PumpDeviceState.PumpUnreachable)
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.PumpUnreachable); medtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable);
if (!canPreventTuneUp) { if (!canPreventTuneUp) {
@ -153,7 +145,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
private boolean connectToDevice() { private boolean connectToDevice() {
PumpDeviceState state = MedtronicUtil.getInstance().getPumpDeviceState(); PumpDeviceState state = medtronicUtil.getPumpDeviceState();
byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple
RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200,
@ -185,8 +177,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
MedtronicDeviceType pumpModel = (MedtronicDeviceType) dataResponse; MedtronicDeviceType pumpModel = (MedtronicDeviceType) dataResponse;
boolean valid = (pumpModel != MedtronicDeviceType.Unknown_Device); boolean valid = (pumpModel != MedtronicDeviceType.Unknown_Device);
if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null && valid) { if (medtronicUtil.getMedtronicPumpModel() == null && valid) {
MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel); medtronicUtil.setMedtronicPumpModel(pumpModel);
} }
aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid,
@ -194,9 +186,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (valid) { if (valid) {
if (state == PumpDeviceState.PumpUnreachable) if (state == PumpDeviceState.PumpUnreachable)
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp); medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp);
else else
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
rememberLastGoodDeviceCommunicationTime(); rememberLastGoodDeviceCommunicationTime();
@ -204,7 +196,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} else { } else {
if (state != PumpDeviceState.PumpUnreachable) if (state != PumpDeviceState.PumpUnreachable)
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.PumpUnreachable); medtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable);
} }
} }
@ -280,7 +272,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
for (List<Byte> frame : frames) { for (List<Byte> frame : frames) {
byte[] frameData = MedtronicUtil.getInstance().createByteArray(frame); byte[] frameData = medtronicUtil.createByteArray(frame);
// aapsLogger.debug(LTag.PUMPBTCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); // aapsLogger.debug(LTag.PUMPBTCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData));
@ -317,9 +309,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (doWakeUpBeforeCommand) if (doWakeUpBeforeCommand)
wakeUp(receiverDeviceAwakeForMinutes, false); wakeUp(receiverDeviceAwakeForMinutes, false);
aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + MedtronicUtil.getInstance().getCurrentCommand()); aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + medtronicUtil.getCurrentCommand());
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); medtronicUtil.setPumpDeviceState(PumpDeviceState.Active);
boolean doneWithError = false; boolean doneWithError = false;
for (int pageNumber = 0; pageNumber < 5; pageNumber++) { for (int pageNumber = 0; pageNumber < 5; pageNumber++) {
@ -336,7 +328,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage firstResponse = null; PumpMessage firstResponse = null;
boolean failed = false; boolean failed = false;
MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null); medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null);
for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) {
@ -351,7 +343,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
if (failed) { if (failed) {
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
} }
@ -379,7 +371,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
rawHistoryPage.appendData(currentResponse.getFrameData()); rawHistoryPage.appendData(currentResponse.getFrameData());
// RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) * // RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) *
// currentResponse.getFrameNumber() + 1)); // currentResponse.getFrameNumber() + 1));
MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber,
currentResponse.getFrameNumber()); currentResponse.getFrameNumber());
aapsLogger.info(LTag.PUMPBTCOMM, "getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber); aapsLogger.info(LTag.PUMPBTCOMM, "getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber);
@ -442,7 +434,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
if (doneWithError) { if (doneWithError) {
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
} }
@ -458,13 +450,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished());
if (pumpTotalResult.isSearchFinished()) { if (pumpTotalResult.isSearchFinished()) {
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
} }
} }
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
@ -480,11 +472,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public byte[] createPumpMessageContent(RLMessageType type) { public byte[] createPumpMessageContent(RLMessageType type) {
switch (type) { switch (type) {
case PowerOn: case PowerOn:
return MedtronicUtil.getInstance().buildCommandPayload(MedtronicCommandType.RFPowerOn, // return medtronicUtil.buildCommandPayload(MedtronicCommandType.RFPowerOn, //
new byte[]{2, 1, (byte) receiverDeviceAwakeForMinutes}); // maybe this is better FIXME new byte[]{2, 1, (byte) receiverDeviceAwakeForMinutes}); // maybe this is better FIXME
case ReadSimpleData: case ReadSimpleData:
return MedtronicUtil.getInstance().buildCommandPayload(MedtronicCommandType.PumpModel, null); return medtronicUtil.buildCommandPayload(MedtronicCommandType.PumpModel, null);
} }
return new byte[0]; return new byte[0];
} }
@ -528,7 +520,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (doWakeUpBeforeCommand) if (doWakeUpBeforeCommand)
wakeUp(receiverDeviceAwakeForMinutes, false); wakeUp(receiverDeviceAwakeForMinutes, false);
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); medtronicUtil.setPumpDeviceState(PumpDeviceState.Active);
// create message // create message
PumpMessage msg; PumpMessage msg;
@ -541,7 +533,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
// send and wait for response // send and wait for response
PumpMessage response = sendAndListen(msg, timeoutMs); PumpMessage response = sendAndListen(msg, timeoutMs);
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return response; return response;
} }
@ -571,12 +563,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) {
try { try {
PumpMessage response = null; PumpMessage response = sendAndGetResponse(commandType, bodyData, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries));
response = sendAndGetResponse(commandType, bodyData, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); String check = checkResponseContent(response, commandType.commandDescription, commandType.expectedLength);
String check = checkResponseContent(response, commandType.commandDescription,
commandType.expectedLength);
if (check == null) { if (check == null) {
@ -664,9 +653,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType); aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType);
MedtronicUtil.getInstance().setCurrentCommand(commandType); medtronicUtil.setCurrentCommand(commandType);
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); medtronicUtil.setPumpDeviceState(PumpDeviceState.Active);
for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) {
@ -677,9 +666,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
msg = makePumpMessage(commandType); msg = makePumpMessage(commandType);
// send and wait for response // send and wait for response
PumpMessage response = null;
response = sendAndListen(msg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); PumpMessage response = sendAndListen(msg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries));
// aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent())); // aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent()));
// aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData())); // aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData()));
@ -723,8 +711,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (basalProfile != null) { if (basalProfile != null) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile);
MedtronicUtil.getInstance().setCurrentCommand(null); medtronicUtil.setCurrentCommand(null);
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return basalProfile; return basalProfile;
} }
@ -735,8 +723,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading profile in max retries."); aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading profile in max retries.");
MedtronicUtil.getInstance().setCurrentCommand(null); medtronicUtil.setCurrentCommand(null);
MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
return null; return null;
@ -795,7 +783,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public Map<String, PumpSettingDTO> getPumpSettings() { public Map<String, PumpSettingDTO> getPumpSettings() {
Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.getSettings(MedtronicUtil.getInstance() Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.getSettings(medtronicUtil
.getMedtronicPumpModel())); .getMedtronicPumpModel()));
return responseObject == null ? null : (Map<String, PumpSettingDTO>) responseObject; return responseObject == null ? null : (Map<String, PumpSettingDTO>) responseObject;
@ -806,7 +794,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
aapsLogger.info(LTag.PUMPBTCOMM, "setBolus: " + units); aapsLogger.info(LTag.PUMPBTCOMM, "setBolus: " + units);
return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getInstance().getBolusStrokes(units)); return setCommand(MedtronicCommandType.SetBolus, medtronicUtil.getBolusStrokes(units));
} }
@ -833,7 +821,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
data[i + 1] = (byte) gc.get(Calendar.MINUTE); data[i + 1] = (byte) gc.get(Calendar.MINUTE);
data[i + 2] = (byte) gc.get(Calendar.SECOND); data[i + 2] = (byte) gc.get(Calendar.SECOND);
byte[] yearByte = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(gc.get(Calendar.YEAR), true); byte[] yearByte = medtronicUtil.getByteArrayFromUnsignedShort(gc.get(Calendar.YEAR), true);
data[i + 3] = yearByte[0]; data[i + 3] = yearByte[0];
data[i + 4] = yearByte[1]; data[i + 4] = yearByte[1];
@ -897,7 +885,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public Boolean setBasalProfile(BasalProfile basalProfile) { public Boolean setBasalProfile(BasalProfile basalProfile) {
List<List<Byte>> basalProfileFrames = MedtronicUtil.getInstance().getBasalProfileFrames(basalProfile.getRawData()); List<List<Byte>> basalProfileFrames = medtronicUtil.getBasalProfileFrames(basalProfile.getRawData());
for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) {

View file

@ -2,13 +2,15 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm;
import org.joda.time.IllegalFieldValueException; import org.joda.time.IllegalFieldValueException;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import info.nightscout.androidaps.logging.L; import javax.inject.Inject;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import javax.inject.Singleton;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil;
@ -26,25 +28,30 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
* High level decoder for data returned through MedtroniUIComm * High level decoder for data returned through MedtroniUIComm
*/ */
@Singleton
public class MedtronicConverter { public class MedtronicConverter {
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); private final AAPSLogger aapsLogger;
private final MedtronicUtil medtronicUtil;
MedtronicDeviceType pumpModel; @Inject
public MedtronicConverter(
AAPSLogger aapsLogger,
MedtronicUtil medtronicUtil
) {
this.aapsLogger = aapsLogger;
this.medtronicUtil = medtronicUtil;
}
Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) {
public Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) {
if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) { if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) {
LOG.warn("Content is empty or too short, no data to convert (type={},isNull={},length={})", aapsLogger.warn(LTag.PUMPBTCOMM, "Content is empty or too short, no data to convert (type={},isNull={},length={})",
commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length); commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length);
return null; return null;
} }
if (isLogEnabled()) aapsLogger.debug(LTag.PUMPBTCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent));
LOG.debug("Raw response before convert: " + ByteUtil.shortHexString(rawContent));
this.pumpModel = MedtronicUtil.getInstance().getMedtronicPumpModel();
switch (commandType) { switch (commandType) {
@ -107,18 +114,17 @@ public class MedtronicConverter {
private MedtronicDeviceType decodeModel(byte[] rawContent) { private MedtronicDeviceType decodeModel(byte[] rawContent) {
if ((rawContent == null || rawContent.length < 4)) { if ((rawContent == null || rawContent.length < 4)) {
LOG.warn("Error reading PumpModel, returning Unknown_Device"); aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading PumpModel, returning Unknown_Device");
return MedtronicDeviceType.Unknown_Device; return MedtronicDeviceType.Unknown_Device;
} }
String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3)); String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3));
MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel); MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel);
if (isLogEnabled()) aapsLogger.debug(LTag.PUMPBTCOMM, "PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name());
LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name());
if (pumpModel != MedtronicDeviceType.Unknown_Device) { if (pumpModel != MedtronicDeviceType.Unknown_Device) {
if (!MedtronicUtil.getInstance().isModelSet()) { if (!medtronicUtil.isModelSet()) {
MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel); medtronicUtil.setMedtronicPumpModel(pumpModel);
} }
} }
@ -154,10 +160,10 @@ public class MedtronicConverter {
} }
protected Float decodeRemainingInsulin(byte[] rawData) { private Float decodeRemainingInsulin(byte[] rawData) {
int startIdx = 0; int startIdx = 0;
this.pumpModel = MedtronicUtil.getInstance().getMedtronicPumpModel(); MedtronicDeviceType pumpModel = medtronicUtil.getMedtronicPumpModel();
int strokes = pumpModel == null ? 10 : pumpModel.getBolusStrokes(); int strokes = pumpModel == null ? 10 : pumpModel.getBolusStrokes();
@ -167,8 +173,7 @@ public class MedtronicConverter {
float value = ByteUtil.toInt(rawData[startIdx], rawData[startIdx + 1]) / (1.0f * strokes); float value = ByteUtil.toInt(rawData[startIdx], rawData[startIdx + 1]) / (1.0f * strokes);
if (isLogEnabled()) aapsLogger.debug(LTag.PUMPBTCOMM, "Remaining insulin: " + value);
LOG.debug("Remaining insulin: " + value);
return value; return value;
} }
@ -185,7 +190,7 @@ public class MedtronicConverter {
LocalDateTime pumpTime = new LocalDateTime(year, month, day, hours, minutes, seconds); LocalDateTime pumpTime = new LocalDateTime(year, month, day, hours, minutes, seconds);
return pumpTime; return pumpTime;
} catch (IllegalFieldValueException e) { } catch (IllegalFieldValueException e) {
LOG.error( aapsLogger.error(LTag.PUMPBTCOMM,
"decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d", "decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d",
year, month, day, hours, minutes, seconds); year, month, day, hours, minutes, seconds);
return null; return null;
@ -194,7 +199,7 @@ public class MedtronicConverter {
} }
public Map<String, PumpSettingDTO> decodeSettingsLoop(byte[] rd) { private Map<String, PumpSettingDTO> decodeSettingsLoop(byte[] rd) {
Map<String, PumpSettingDTO> map = new HashMap<>(); Map<String, PumpSettingDTO> map = new HashMap<>();
@ -271,7 +276,7 @@ public class MedtronicConverter {
addSettingToMap("CFG_BASE_CLOCK_MODE", rd[getSettingIndexTimeDisplayFormat()] == 0 ? "12h" : "24h", addSettingToMap("CFG_BASE_CLOCK_MODE", rd[getSettingIndexTimeDisplayFormat()] == 0 ? "12h" : "24h",
PumpConfigurationGroup.General, map); PumpConfigurationGroup.General, map);
if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_523andHigher)) {
addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + (rd[9] == 0 ? 50 : 100), PumpConfigurationGroup.Insulin, addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + (rd[9] == 0 ? 50 : 100), PumpConfigurationGroup.Insulin,
map); map);
// LOG.debug("Insulin concentration: " + rd[9]); // LOG.debug("Insulin concentration: " + rd[9]);
@ -323,7 +328,7 @@ public class MedtronicConverter {
} }
public void addSettingToMap(String key, String value, PumpConfigurationGroup group, Map<String, PumpSettingDTO> map) { private void addSettingToMap(String key, String value, PumpConfigurationGroup group, Map<String, PumpSettingDTO> map) {
map.put(key, new PumpSettingDTO(key, value, group)); map.put(key, new PumpSettingDTO(key, value, group));
} }
@ -339,7 +344,7 @@ public class MedtronicConverter {
addSettingToMap("CFG_MM_KEYPAD_LOCKED", parseResultEnable(rd[20]), PumpConfigurationGroup.Other, map); addSettingToMap("CFG_MM_KEYPAD_LOCKED", parseResultEnable(rd[20]), PumpConfigurationGroup.Other, map);
if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_523andHigher)) {
addSettingToMap("PCFG_BOLUS_SCROLL_STEP_SIZE", "" + rd[21], PumpConfigurationGroup.Bolus, map); addSettingToMap("PCFG_BOLUS_SCROLL_STEP_SIZE", "" + rd[21], PumpConfigurationGroup.Bolus, map);
addSettingToMap("PCFG_CAPTURE_EVENT_ENABLE", parseResultEnable(rd[22]), PumpConfigurationGroup.Other, map); addSettingToMap("PCFG_CAPTURE_EVENT_ENABLE", parseResultEnable(rd[22]), PumpConfigurationGroup.Other, map);
@ -352,7 +357,7 @@ public class MedtronicConverter {
} }
protected String parseResultEnable(int i) { private String parseResultEnable(int i) {
switch (i) { switch (i) {
case 0: case 0:
return "No"; return "No";
@ -364,19 +369,19 @@ public class MedtronicConverter {
} }
public float getStrokesPerUnit(boolean isBasal) { private float getStrokesPerUnit(boolean isBasal) {
return isBasal ? 40.0f : 10; // pumpModel.getBolusStrokes(); return isBasal ? 40.0f : 10; // pumpModel.getBolusStrokes();
} }
// 512 // 512
public void decodeInsulinActionSetting(byte[] ai, Map<String, PumpSettingDTO> map) { private void decodeInsulinActionSetting(byte[] ai, Map<String, PumpSettingDTO> map) {
if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_512_712)) { if (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_512_712)) {
addSettingToMap("PCFG_INSULIN_ACTION_TYPE", (ai[17] != 0 ? "Regular" : "Fast"), addSettingToMap("PCFG_INSULIN_ACTION_TYPE", (ai[17] != 0 ? "Regular" : "Fast"),
PumpConfigurationGroup.Insulin, map); PumpConfigurationGroup.Insulin, map);
} else { } else {
int i = ai[17]; int i = ai[17];
String s = ""; String s;
if ((i == 0) || (i == 1)) { if ((i == 0) || (i == 1)) {
s = ai[17] != 0 ? "Regular" : "Fast"; s = ai[17] != 0 ? "Regular" : "Fast";
@ -392,12 +397,12 @@ public class MedtronicConverter {
} }
public double decodeBasalInsulin(int i) { private double decodeBasalInsulin(int i) {
return (double) i / (double) getStrokesPerUnit(true); return (double) i / (double) getStrokesPerUnit(true);
} }
public double decodeBolusInsulin(int i) { private double decodeBolusInsulin(int i) {
return (double) i / (double) getStrokesPerUnit(false); return (double) i / (double) getStrokesPerUnit(false);
} }
@ -413,19 +418,13 @@ public class MedtronicConverter {
} }
public double decodeMaxBolus(byte[] ai) { private double decodeMaxBolus(byte[] ai) {
return is523orHigher() ? decodeBolusInsulin(ByteUtil.toInt(ai[5], ai[6])) : decodeBolusInsulin(ByteUtil return is523orHigher() ? decodeBolusInsulin(ByteUtil.toInt(ai[5], ai[6])) : decodeBolusInsulin(ByteUtil
.asUINT8(ai[5])); .asUINT8(ai[5]));
} }
private boolean is523orHigher() { private boolean is523orHigher() {
return (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)); return (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_523andHigher));
} }
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
} }

View file

@ -40,34 +40,8 @@ public class MedtronicUIComm {
medtronicUtil.setCurrentCommand(commandType); medtronicUtil.setCurrentCommand(commandType);
// new Thread(() -> {
// LOG.warn("@@@ Start Thread");
//
// task.execute(getCommunicationManager());
//
// LOG.warn("@@@ End Thread");
// });
task.execute(medtronicCommunicationManager); task.execute(medtronicCommunicationManager);
// for (int i = 0; i < getMaxWaitTime(commandType); i++) {
// synchronized (task) {
// // try {
// //
// // //task.wait(1000);
// // } catch (InterruptedException e) {
// // LOG.error("executeCommand InterruptedException", e);
// // }
//
//
// SystemClock.sleep(1000);
// }
//
// if (task.isReceived()) {
// break;
// }
// }
if (!task.isReceived()) { if (!task.isReceived()) {
aapsLogger.warn(LTag.PUMP, "Reply not received for " + commandType); aapsLogger.warn(LTag.PUMP, "Reply not received for " + commandType);
} }

View file

@ -58,7 +58,7 @@ public class MedtronicUIPostprocessor {
// this is mostly intended for command that return certain statuses (Remaining Insulin, ...), and // this is mostly intended for command that return certain statuses (Remaining Insulin, ...), and
// where responses won't be directly used // where responses won't be directly used
public void postProcessData(MedtronicUITask uiTask) { void postProcessData(MedtronicUITask uiTask) {
switch (uiTask.commandType) { switch (uiTask.commandType) {
@ -203,7 +203,7 @@ public class MedtronicUIPostprocessor {
medtronicUtil.setSettings(settings); medtronicUtil.setSettings(settings);
PumpSettingDTO checkValue = null; PumpSettingDTO checkValue;
medtronicPumpPlugin.getRileyLinkService().verifyConfiguration(); medtronicPumpPlugin.getRileyLinkService().verifyConfiguration();

View file

@ -115,7 +115,6 @@ public class RileyLinkMedtronicService extends RileyLinkService {
medtronicUIComm = new MedtronicUIComm(injector, aapsLogger, medtronicUtil, medtronicUIPostprocessor, medtronicCommunicationManager); medtronicUIComm = new MedtronicUIComm(injector, aapsLogger, medtronicUtil, medtronicUIPostprocessor, medtronicCommunicationManager);
aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed"); aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed");
medtronicUtil.setMedtronicService(this);
} }

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.medtronic.util;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import org.jetbrains.annotations.NotNull;
import org.joda.time.LocalTime; import org.joda.time.LocalTime;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -25,17 +24,13 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus;
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
/** /**
@ -46,12 +41,9 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
public class MedtronicUtil { public class MedtronicUtil {
private int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS] private int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS]
int CRC_SIZE = 1;
private boolean lowLevelDebug = true; private boolean lowLevelDebug = true;
private PumpDeviceState pumpDeviceState; private PumpDeviceState pumpDeviceState;
private MedtronicDeviceType medtronicPumpModel; private MedtronicDeviceType medtronicPumpModel;
private RileyLinkMedtronicService medtronicService;
@Deprecated // TODO remove this reference
private MedtronicCommandType currentCommand; private MedtronicCommandType currentCommand;
private Map<String, PumpSettingDTO> settings; private Map<String, PumpSettingDTO> settings;
private int BIG_FRAME_LENGTH = 65; private int BIG_FRAME_LENGTH = 65;
@ -60,23 +52,20 @@ public class MedtronicUtil {
public Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); public Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
public Gson gsonInstanceCore = new GsonBuilder().create(); public Gson gsonInstanceCore = new GsonBuilder().create();
@NotNull private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
@NotNull private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
@NotNull private final RileyLinkUtil rileyLinkUtil; private final RileyLinkUtil rileyLinkUtil;
@NotNull private final MedtronicPumpStatus medtronicPumpStatus;
@Inject @Inject
public MedtronicUtil( public MedtronicUtil(
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
RileyLinkUtil rileyLinkUtil, RileyLinkUtil rileyLinkUtil
MedtronicPumpStatus medtronicPumpStatus
) { ) {
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus; this.rxBus = rxBus;
this.rileyLinkUtil = rileyLinkUtil; this.rileyLinkUtil = rileyLinkUtil;
this.medtronicPumpStatus = medtronicPumpStatus;
instance = this; instance = this;
} }
@ -445,32 +434,10 @@ public class MedtronicUtil {
this.medtronicPumpModel = medtronicPumpModel; this.medtronicPumpModel = medtronicPumpModel;
} }
public MedtronicCommunicationManager getMedtronicCommunicationManager() {
return (MedtronicCommunicationManager) rileyLinkUtil.rileyLinkCommunicationManager;
}
public RileyLinkMedtronicService getMedtronicService() {
return medtronicService;
}
public void setMedtronicService(RileyLinkMedtronicService medtronicService) {
this.medtronicService = medtronicService;
}
@Deprecated // TODO use singleton
public MedtronicPumpStatus getPumpStatus1() {
return medtronicPumpStatus;
}
public MedtronicCommandType getCurrentCommand() { public MedtronicCommandType getCurrentCommand() {
return this.currentCommand; return this.currentCommand;
} }
public void setCurrentCommand(MedtronicCommandType currentCommand) { public void setCurrentCommand(MedtronicCommandType currentCommand) {
this.currentCommand = currentCommand; this.currentCommand = currentCommand;