0.10.1-SNAPSHOT

- Bolus Wizard entries (CH) is processed
- Better RSSI calculation for Tunning
- #124: Added retries to pump command (extended current retry functionality) that should take care of this problem
- Removed all un-needed logging and brining it under correct logging context (PUMP, PUMPCOMM, PUMPBTCOMM)
- added RileyLink Hardware encoding
This commit is contained in:
Andy Rozman 2019-05-15 23:04:44 +01:00
parent ff55b7290d
commit fe73eba2a2
50 changed files with 880 additions and 1397 deletions

View file

@ -105,7 +105,7 @@ android {
multiDexEnabled true
versionCode 1500
// dev_version: 2.3.1-dev
version "medtronic-0.9"
version "medtronic-0.10.0-SNAPSHOT"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'

View file

@ -45,7 +45,7 @@ import info.nightscout.androidaps.utils.DecimalFormatter;
public abstract class PumpPluginAbstract extends PluginBase implements PumpInterface, ConstraintsInterface {
private static final Logger LOG = LoggerFactory.getLogger(PumpPluginAbstract.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false)
.enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver));

View file

@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory;
import android.content.Context;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException;
@ -31,7 +32,7 @@ import info.nightscout.androidaps.utils.SP;
*/
public abstract class RileyLinkCommunicationManager {
private static final Logger LOG = LoggerFactory.getLogger(RileyLinkCommunicationManager.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
private static final int SCAN_TIMEOUT = 1500;
private static final int ALLOWED_PUMP_UNREACHABLE = 10 * 60 * 1000; // 10 minutes
@ -43,9 +44,7 @@ public abstract class RileyLinkCommunicationManager {
protected long lastGoodReceiverCommunicationTime = 0;
protected PumpStatus pumpStatus;
protected RileyLinkServiceData rileyLinkServiceData;
// protected RileyLinkTargetFrequency targetFrequency;
private long nextWakeUpRequired = 0L;
// private double[] scanFrequencies;
// internal flag
private boolean showPumpMessages = true;
@ -55,8 +54,6 @@ public abstract class RileyLinkCommunicationManager {
public RileyLinkCommunicationManager(Context context, RFSpy rfspy) {
this.context = context;
this.rfspy = rfspy;
// this.targetFrequency = RileyLinkUtil.getRileyLinkTargetFrequency();
// this.scanFrequencies = targetFrequency.getScanFrequencies();
this.rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData();
RileyLinkUtil.setRileyLinkCommunicationManager(this);
@ -67,19 +64,12 @@ public abstract class RileyLinkCommunicationManager {
protected abstract void configurePumpSpecificSettings();
// public void refreshRileyLinkTargetFrequency() {
// if (this.targetFrequency != RileyLinkUtil.getRileyLinkTargetFrequency()) {
// this.targetFrequency = RileyLinkUtil.getRileyLinkTargetFrequency();
// this.scanFrequencies = targetFrequency.getScanFrequencies();
// }
//
// }
// All pump communications go through this function.
protected <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, Class<E> clazz)
throws RileyLinkCommunicationException {
if (showPumpMessages) {
if (isLogEnabled())
LOG.info("Sent:" + ByteUtil.shortHexString(msg.getTxData()));
}
@ -93,8 +83,8 @@ public abstract class RileyLinkCommunicationManager {
// Mark this as the last time we heard from the pump.
rememberLastGoodDeviceCommunicationTime();
} else {
LOG.warn("Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(),
rfSpyResponse.wasTimeout());
LOG.warn("isDeviceReachable. Response is invalid ! [interrupted={}, timeout={}, unknownCommand={}, invalidParam={}]", rfSpyResponse.wasInterrupted(),
rfSpyResponse.wasTimeout(), rfSpyResponse.isUnknownCommand(), rfSpyResponse.isInvalidParam());
if (rfSpyResponse.wasTimeout()) {
timeoutCount++;
@ -114,6 +104,7 @@ public abstract class RileyLinkCommunicationManager {
}
if (showPumpMessages) {
if (isLogEnabled())
LOG.info("Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse().getPayload()));
}
@ -134,17 +125,6 @@ public abstract class RileyLinkCommunicationManager {
}
// public boolean changeTargetFrequency(RileyLinkTargetFrequency targetFrequency) {
//
// if (this.targetFrequency == targetFrequency) {
// return false;
// }
//
// this.targetFrequency = targetFrequency;
// this.scanFrequencies = targetFrequency.getScanFrequencies();
//
// return true;
// }
// FIXME change wakeup
// TODO we might need to fix this. Maybe make pump awake for shorter time (battery factor for pump) - Andy
@ -159,17 +139,20 @@ public abstract class RileyLinkCommunicationManager {
nextWakeUpRequired = 0L;
if (System.currentTimeMillis() > nextWakeUpRequired) {
if (isLogEnabled())
LOG.info("Waking pump...");
byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple
RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte)0, (byte)200,
(byte)0, (byte)0, 25000, (byte)0);
if (isLogEnabled())
LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw()));
// FIXME wakeUp successful !!!!!!!!!!!!!!!!!!
nextWakeUpRequired = System.currentTimeMillis() + (receiverDeviceAwakeForMinutes * 60 * 1000);
} else {
if (isLogEnabled())
LOG.trace("Last pump communication was recent, not waking pump.");
}
@ -226,8 +209,8 @@ public abstract class RileyLinkCommunicationManager {
public abstract boolean tryToConnectToDevice();
// FIXME sorting, and time display
public double scanForDevice(double[] frequencies) {
if (isLogEnabled())
LOG.info("Scanning for receiver ({})", receiverDeviceID);
wakeUp(receiverDeviceAwakeForMinutes, false);
FrequencyScanResults results = new FrequencyScanResults();
@ -243,7 +226,7 @@ public abstract class RileyLinkCommunicationManager {
byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData);
RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte)0, (byte)0,
(byte)0, (byte)0, 1500, (byte)0);
(byte)0, (byte)0, 1250, (byte)0);
if (resp.wasTimeout()) {
LOG.error("scanForPump: Failed to find pump at frequency {}", frequencies[i]);
} else if (resp.looksLikeRadioPacket()) {
@ -254,7 +237,7 @@ public abstract class RileyLinkCommunicationManager {
radioResponse.init(resp.getRaw());
if (radioResponse.isValid()) {
sumRSSI += radioResponse.rssi;
sumRSSI += calculateRssi(radioResponse.rssi);
trial.rssiList.add(radioResponse.rssi);
trial.successes++;
} else {
@ -293,7 +276,7 @@ public abstract class RileyLinkCommunicationManager {
+ one.averageRSSI2));
}
LOG.debug(stringBuilder.toString());
LOG.info(stringBuilder.toString());
results.sort(); // sorts in ascending order
@ -301,6 +284,7 @@ public abstract class RileyLinkCommunicationManager {
results.bestFrequencyMHz = bestTrial.frequencyMHz;
if (bestTrial.successes > 0) {
rfspy.setBaseFrequency(results.bestFrequencyMHz);
if (isLogEnabled())
LOG.debug("Best frequency found: " + results.bestFrequencyMHz);
return results.bestFrequencyMHz;
} else {
@ -310,6 +294,19 @@ public abstract class RileyLinkCommunicationManager {
}
private int calculateRssi(int rssiIn) {
int rssiOffset = 73;
int outRssi = 0;
if (rssiIn >= 128) {
outRssi = ((rssiIn - 256) / 2) - rssiOffset;
} else {
outRssi = (rssiIn / 2) - rssiOffset;
}
return outRssi;
}
public abstract byte[] createPumpMessageContent(RLMessageType type);
@ -328,7 +325,7 @@ public abstract class RileyLinkCommunicationManager {
if (radioResponse.isValid()) {
LOG.warn("tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz);
return radioResponse.rssi;
return calculateRssi(radioResponse.rssi);
} else {
LOG.warn("tune_tryFrequency: invalid radio response:"
+ ByteUtil.shortHexString(radioResponse.getPayload()));
@ -362,12 +359,15 @@ public abstract class RileyLinkCommunicationManager {
}
if (betterFrequency == 0.0) {
// we've failed... caller should try a full scan for pump
if (isLogEnabled())
LOG.error("quickTuneForPump: failed to find pump");
} else {
rfspy.setBaseFrequency(betterFrequency);
if (betterFrequency != startFrequencyMHz) {
if (isLogEnabled())
LOG.info("quickTuneForPump: new frequency is {}MHz", betterFrequency);
} else {
if (isLogEnabled())
LOG.info("quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz);
}
}
@ -376,6 +376,7 @@ public abstract class RileyLinkCommunicationManager {
private double quickTunePumpStep(double startFrequencyMHz, double stepSizeMHz) {
if (isLogEnabled())
LOG.info("Doing quick radio tune for receiver ({})", receiverDeviceID);
wakeUp(false);
int startRssi = tune_tryFrequency(startFrequencyMHz);
@ -414,6 +415,7 @@ public abstract class RileyLinkCommunicationManager {
// Might still be zero, but that's fine.
}
double minutesAgo = (System.currentTimeMillis() - lastGoodReceiverCommunicationTime) / (1000.0 * 60.0);
if (isLogEnabled())
LOG.trace("Last good pump communication was " + minutesAgo + " minutes ago.");
return lastGoodReceiverCommunicationTime;
}
@ -429,4 +431,9 @@ public abstract class RileyLinkCommunicationManager {
rfspy.notConnectedCount = 0;
}
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -12,7 +12,6 @@ public class RileyLinkConst {
public static final String RileyLinkReady = Prefix + "RileyLink_Ready";
public static final String RileyLinkGattFailed = Prefix + "RileyLink_Gatt_Failed";
// public static final String RileyLinkBLEError = Prefix + "RileyLink_Ready";
public static final String BluetoothConnected = Prefix + "Bluetooth_Connected";
public static final String BluetoothReconnected = Prefix + "Bluetooth_Reconnected";

View file

@ -15,6 +15,7 @@ import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding.Encoding4b6b;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding.Encoding4b6bGeoff;
@ -41,23 +42,16 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDe
public class RileyLinkUtil {
private static final Logger LOG = LoggerFactory.getLogger(RileyLinkUtil.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
protected static List<RLHistoryItem> historyRileyLink = new ArrayList<>();
protected static RileyLinkCommunicationManager rileyLinkCommunicationManager;
static ServiceTask currentTask;
private static Context context;
private static RileyLinkBLE rileyLinkBLE;
private static RileyLinkServiceData rileyLinkServiceData;
// private static PumpType pumpType;
// private static MedtronicPumpStatus medtronicPumpStatus;
private static RileyLinkService rileyLinkService;
// private static RileyLinkIPCConnection rileyLinkIPCConnection;
// private static MedtronicDeviceType medtronicPumpModel;
// BAD dependencies in Classes: RileyLinkService
private static RileyLinkTargetFrequency rileyLinkTargetFrequency;
// Broadcasts: RileyLinkBLE, RileyLinkService,
// private static RileyLinkIPCConnection rileyLinkIPCConnection;
private static RileyLinkTargetDevice targetDevice;
private static RileyLinkEncodingType encoding;
private static RileyLinkSelectPreference rileyLinkSelectPreference;
@ -72,7 +66,6 @@ public class RileyLinkUtil {
public static RileyLinkEncodingType getEncoding() {
return encoding;
}
@ -121,7 +114,8 @@ public class RileyLinkUtil {
RileyLinkUtil.rileyLinkServiceData.serviceState = newState;
RileyLinkUtil.rileyLinkServiceData.errorCode = errorCode;
LOG.warn("RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: "
if (L.isEnabled(L.PUMP))
LOG.info("RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: "
+ errorCode.name());
RileyLinkUtil.historyRileyLink.add(new RLHistoryItem(RileyLinkUtil.rileyLinkServiceData.serviceState,
@ -184,7 +178,6 @@ public class RileyLinkUtil {
public static boolean sendNotification(ServiceNotification notification, Integer clientHashcode) {
// return RileyLinkUtil.rileyLinkIPCConnection.sendNotification(notification, clientHashcode);
return false;
}
@ -194,14 +187,14 @@ public class RileyLinkUtil {
if (currentTask == null) {
currentTask = task;
} else {
LOG.error("setCurrentTask: Cannot replace current task");
//LOG.error("setCurrentTask: Cannot replace current task");
}
}
public static void finishCurrentTask(ServiceTask task) {
if (task != currentTask) {
LOG.error("finishCurrentTask: task does not match");
//LOG.error("finishCurrentTask: task does not match");
}
// hack to force deep copy of transport contents
ServiceTransport transport = task.getServiceTransport().clone();
@ -224,14 +217,6 @@ public class RileyLinkUtil {
}
// public static void setRileyLinkIPCConnection(RileyLinkIPCConnection rileyLinkIPCConnection) {
// RileyLinkUtil.rileyLinkIPCConnection = rileyLinkIPCConnection;
// }
// public static RileyLinkIPCConnection getRileyLinkIPCConnection() {
// return RileyLinkUtil.rileyLinkIPCConnection;
// }
public static RileyLinkTargetFrequency getRileyLinkTargetFrequency() {
return RileyLinkUtil.rileyLinkTargetFrequency;
}

View file

@ -46,7 +46,7 @@ public class RFSpy {
public static final long RILEYLINK_FREQ_XTAL = 24000000;
public static final int EXPECTED_MAX_BLUETOOTH_LATENCY_MS = 7500; // 1500
private static final Logger LOG = LoggerFactory.getLogger(RFSpy.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
public int notConnectedCount = 0;
private RileyLinkBLE rileyLinkBle;
private RFSpyReader reader;
@ -95,12 +95,6 @@ public class RFSpy {
bleVersion = getVersion();
firmwareVersion = getFirmwareVersion();
RileyLinkUtil.setFirmwareVersion(firmwareVersion);
if (RileyLinkFirmwareVersion.isSameVersion(firmwareVersion, RileyLinkFirmwareVersion.Version2AndHigher)) {
if (RileyLinkUtil.getRileyLinkServiceData().targetDevice == RileyLinkTargetDevice.MedtronicPump) {
//MedtronicPumpPlugin.getPlugin().setEnableCustomAction(MedtronicCustomActionType.ResetRileyLink, true);
}
}
}
@ -117,6 +111,7 @@ public class RFSpy {
BLECommOperationResult result = rileyLinkBle.readCharacteristic_blocking(radioServiceUUID, radioVersionUUID);
if (result.resultCode == BLECommOperationResult.RESULT_SUCCESS) {
String version = StringUtil.fromBytes(result.value);
if (isLogEnabled())
LOG.debug("BLE Version: " + version);
return version;
} else {
@ -128,6 +123,7 @@ public class RFSpy {
public RileyLinkFirmwareVersion getFirmwareVersion() {
if (isLogEnabled())
LOG.debug("Firmware Version. Get Version - Start");
for (int i = 0; i < 5; i++) {
@ -137,6 +133,7 @@ public class RFSpy {
byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code);
byte[] response = writeToDataRaw(getVersionRaw, 5000);
if (isLogEnabled())
LOG.debug("Firmware Version. GetVersion [response={}]", ByteUtil.getHex(response));
if (response != null) { // && response[0] == (byte) 0xDD) {
@ -146,6 +143,7 @@ public class RFSpy {
RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(StringUtil
.fromBytes(response));
if (isLogEnabled())
LOG.trace("Firmware Version string: {}, resolved to {}.", versionString, version);
if (version != RileyLinkFirmwareVersion.UnknownVersion)
@ -218,6 +216,7 @@ public class RFSpy {
if (resp.looksLikeRadioPacket()) {
// RadioResponse radioResp = resp.getRadioResponse();
// byte[] responsePayload = radioResp.getPayload();
if (isLogEnabled())
LOG.trace("writeToData: received radio response. Will decode at upper level");
resetNotConnectedCount();
}
@ -255,35 +254,6 @@ public class RFSpy {
}
// public RFSpyResponse transmit(RadioPacket radioPacket) {
//
// return transmit(radioPacket, (byte) 0, (byte) 0, (byte) 0xFF);
// }
//
//
// public RFSpyResponse transmit(RadioPacket radioPacket, byte sendChannel, byte repeatCount, byte delay_ms) {
// // append checksum, encode data, send it.
// byte[] fullPacket = ByteUtil.concat(getByteArray(sendChannel, repeatCount, delay_ms), radioPacket.getEncoded());
// RFSpyResponse response = writeToData(RileyLinkCommandType.Send, fullPacket, delay_ms +
// EXPECTED_MAX_BLUETOOTH_LATENCY_MS);
// return response;
// }
// public RFSpyResponse receive(byte listenChannel, int timeout_ms, byte retryCount) {
// int receiveDelay = timeout_ms * (retryCount + 1);
// byte[] listen = getByteArray(listenChannel, (byte) ((timeout_ms >> 24) & 0x0FF), (byte) ((timeout_ms >> 16) &
// 0x0FF), (byte) ((timeout_ms >> 8) & 0x0FF), (byte) (timeout_ms & 0x0FF), retryCount);
// return writeToData(RileyLinkCommandType.GetPacket, listen, receiveDelay);
// }
// public RFSpyResponse transmitThenReceive(RadioPacket pkt, int timeout_ms) {
// return transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, timeout_ms, (byte) 0);
// }
// public RFSpyResponse transmitThenReceive(RadioPacket pkt, int timeout_ms, int repeatCount, int extendPreamble_ms)
// {
// return transmitThenReceive(pkt, (byte) 0, (byte) repeatCount, (byte) 0, (byte) 0, timeout_ms, (byte) 0);
// }
public RFSpyResponse transmitThenReceive(RadioPacket pkt, byte sendChannel, byte repeatCount, byte delay_ms,
byte listenChannel, int timeout_ms, byte retryCount) {
return transmitThenReceive(pkt, sendChannel, repeatCount, delay_ms, listenChannel, timeout_ms, retryCount, null);
@ -319,7 +289,7 @@ public class RFSpy {
updateRegister(CC111XRegister.freq0, (byte)(value & 0xff));
updateRegister(CC111XRegister.freq1, (byte)((value >> 8) & 0xff));
updateRegister(CC111XRegister.freq2, (byte)((value >> 16) & 0xff));
LOG.info("Set frequency to {}", freqMHz);
LOG.info("Set frequency to {} MHz", freqMHz);
configureRadioForRegion(RileyLinkUtil.getRileyLinkTargetFrequency());
}
@ -381,14 +351,13 @@ public class RFSpy {
r = updateRegister(CC111XRegister.sync1, 0xA5);
r = updateRegister(CC111XRegister.sync0, 0x5A);
r = setSoftwareEncoding(RileyLinkEncodingType.Manchester);
// RileyLinkUtil.setEncoding(RileyLinkEncodingType.Manchester);
r = setRileyLinkEncoding(RileyLinkEncodingType.Manchester);
r = setPreamble(0x6665);
}
break;
default:
LOG.debug("No region configuration for RfSpy and {}", frequency.name());
LOG.warn("No region configuration for RfSpy and {}", frequency.name());
break;
}
@ -398,15 +367,18 @@ public class RFSpy {
private void setMedtronicEncoding() {
RileyLinkEncodingType encoding = RileyLinkEncodingType.FourByteSixByteLocal;
if (RileyLinkFirmwareVersion.isSameVersion(this.firmwareVersion, RileyLinkFirmwareVersion.Version2AndHigher)) {
if (SP.getString(MedtronicConst.Prefs.Encoding, "None").equals(MainApp.gs(R.string.medtronic_pump_encoding_4b6b_rileylink))) {
// setSoftwareEncoding(RileyLinkEncodingType.FourByteSixByteRileyLink);
// RileyLinkUtil.setEncoding(RileyLinkEncodingType.FourByteSixByteRileyLink);
encoding = RileyLinkEncodingType.FourByteSixByteRileyLink;
}
}
LOG.debug("Set Encoding for Medtronic: " + RileyLinkUtil.getEncoding().name());
setRileyLinkEncoding(encoding);
if (isLogEnabled())
LOG.debug("Set Encoding for Medtronic: " + encoding.name());
}
@ -421,8 +393,14 @@ public class RFSpy {
}
private RFSpyResponse setSoftwareEncoding(RileyLinkEncodingType encoding) {
private RFSpyResponse setRileyLinkEncoding(RileyLinkEncodingType encoding) {
RFSpyResponse resp = writeToData(new SetHardwareEncoding(encoding), EXPECTED_MAX_BLUETOOTH_LATENCY_MS);
if (resp.isOK()) {
reader.setRileyLinkEncodingType(encoding);
RileyLinkUtil.setEncoding(encoding);
}
return resp;
}
@ -435,6 +413,10 @@ public class RFSpy {
updateRegister(CC111XRegister.mdmcfg4, (byte)(chanbw | drate_e));
}
/**
* This command while implemented doesn't work correctly, and is of dubious action.
* @return
*/
public RFSpyResponse resetRileyLinkDevice() {
// FIXME not working correctly yet
RFSpyResponse resp = null;
@ -449,6 +431,6 @@ public class RFSpy {
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
return L.isEnabled(L.PUMPBTCOMM);
}
}

View file

@ -11,6 +11,7 @@ import org.slf4j.LoggerFactory;
import android.os.AsyncTask;
import android.os.SystemClock;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType;
@ -23,13 +24,14 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil;
*/
public class RFSpyReader {
private static final Logger LOG = LoggerFactory.getLogger(RFSpyReader.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
private static AsyncTask<Void, Void, Void> readerTask;
private RileyLinkBLE rileyLinkBle;
private Semaphore waitForRadioData = new Semaphore(0, true);
private LinkedBlockingQueue<byte[]> mDataQueue = new LinkedBlockingQueue<>();
private int acquireCount = 0;
private int releaseCount = 0;
private boolean stopAtNull = true;
public RFSpyReader(RileyLinkBLE rileyLinkBle) {
@ -49,20 +51,29 @@ public class RFSpyReader {
this.rileyLinkBle = rileyLinkBle;
}
public void setRileyLinkEncodingType(RileyLinkEncodingType encodingType) {
stopAtNull = !(encodingType == RileyLinkEncodingType.Manchester || //
encodingType == RileyLinkEncodingType.FourByteSixByteRileyLink);
}
// This timeout must be coordinated with the length of the RFSpy radio operation or Bad Things Happen.
public byte[] poll(int timeout_ms) {
if (isLogEnabled())
LOG.trace(ThreadUtil.sig() + "Entering poll at t==" + SystemClock.uptimeMillis() + ", timeout is " + timeout_ms
+ " mDataQueue size is " + mDataQueue.size());
if (mDataQueue.isEmpty())
try {
// block until timeout or data available.
// returns null if timeout.
byte[] dataFromQueue = mDataQueue.poll(timeout_ms, TimeUnit.MILLISECONDS);
if (dataFromQueue != null) {
if (isLogEnabled())
LOG.debug("Got data [" + ByteUtil.shortHexString(dataFromQueue) + "] at t=="
+ SystemClock.uptimeMillis());
} else {
if (isLogEnabled())
LOG.debug("Got data [null] at t==" + SystemClock.uptimeMillis());
}
return dataFromQueue;
@ -77,6 +88,7 @@ public class RFSpyReader {
public void newDataIsAvailable() {
releaseCount++;
if (isLogEnabled())
LOG.trace(ThreadUtil.sig() + "waitForRadioData released(count=" + releaseCount + ") at t="
+ SystemClock.uptimeMillis());
waitForRadioData.release();
@ -91,13 +103,11 @@ public class RFSpyReader {
UUID serviceUUID = UUID.fromString(GattAttributes.SERVICE_RADIO);
UUID radioDataUUID = UUID.fromString(GattAttributes.CHARA_RADIO_DATA);
BLECommOperationResult result;
boolean stopAtNull = true;
if (RileyLinkUtil.getEncoding() == RileyLinkEncodingType.Manchester)
stopAtNull = false;
while (true) {
try {
acquireCount++;
waitForRadioData.acquire();
if (isLogEnabled())
LOG.trace(ThreadUtil.sig() + "waitForRadioData acquired (count=" + acquireCount + ") at t="
+ SystemClock.uptimeMillis());
SystemClock.sleep(100);
@ -133,4 +143,8 @@ public class RFSpyReader {
}.execute();
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPBTCOMM);
}
}

View file

@ -19,6 +19,7 @@ import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.SystemClock;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes;
@ -38,7 +39,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil;
*/
public class RileyLinkBLE {
private static final Logger LOG = LoggerFactory.getLogger(RileyLinkBLE.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
private final Context context;
public boolean gattDebugEnabled = true;
@ -57,6 +58,7 @@ public class RileyLinkBLE {
this.context = context;
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (isLogEnabled())
LOG.debug("BT Adapter: " + this.bluetoothAdapter);
bluetoothGattCallback = new BluetoothGattCallback() {
@ -64,7 +66,7 @@ public class RileyLinkBLE {
public void onCharacteristicChanged(final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.trace(ThreadUtil.sig() + "onCharacteristicChanged "
+ GattAttributes.lookup(characteristic.getUuid()) + " "
+ HexDump.toHexString(characteristic.getValue()));
@ -84,7 +86,7 @@ public class RileyLinkBLE {
super.onCharacteristicRead(gatt, characteristic, status);
final String statusMessage = getGattStatusMessage(status);
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.trace(ThreadUtil.sig() + "onCharacteristicRead ("
+ GattAttributes.lookup(characteristic.getUuid()) + ") " + statusMessage + ":"
+ HexDump.toHexString(characteristic.getValue()));
@ -99,7 +101,7 @@ public class RileyLinkBLE {
super.onCharacteristicWrite(gatt, characteristic, status);
final String uuidString = GattAttributes.lookup(characteristic.getUuid());
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.trace(ThreadUtil.sig() + "onCharacteristicWrite " + getGattStatusMessage(status) + " "
+ uuidString + " " + HexDump.toHexString(characteristic.getValue()));
}
@ -133,6 +135,7 @@ public class RileyLinkBLE {
stateMessage = "UNKNOWN newState (" + newState + ")";
}
if (isLogEnabled())
LOG.warn("onConnectionStateChange " + getGattStatusMessage(status) + " " + stateMessage);
}
@ -140,6 +143,7 @@ public class RileyLinkBLE {
if (status == BluetoothGatt.GATT_SUCCESS) {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected);
} else {
if (isLogEnabled())
LOG.debug("BT State connected, GATT status {} ({})", status, getGattStatusMessage(status));
}
@ -161,7 +165,7 @@ public class RileyLinkBLE {
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.warn("onDescriptorWrite " + GattAttributes.lookup(descriptor.getUuid()) + " "
+ getGattStatusMessage(status) + " written: " + HexDump.toHexString(descriptor.getValue()));
}
@ -173,7 +177,7 @@ public class RileyLinkBLE {
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
mCurrentOperation.gattOperationCompletionCallback(descriptor.getUuid(), descriptor.getValue());
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.warn("onDescriptorRead " + getGattStatusMessage(status) + " status " + descriptor);
}
}
@ -182,7 +186,7 @@ public class RileyLinkBLE {
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.warn("onMtuChanged " + mtu + " status " + status);
}
}
@ -191,7 +195,7 @@ public class RileyLinkBLE {
@Override
public void onReadRemoteRssi(final BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.warn("onReadRemoteRssi " + getGattStatusMessage(status) + ": " + rssi);
}
}
@ -200,7 +204,7 @@ public class RileyLinkBLE {
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.warn("onReliableWriteCompleted status " + status);
}
}
@ -227,11 +231,11 @@ public class RileyLinkBLE {
}
}
if (gattDebugEnabled) {
if (gattDebugEnabled && isLogEnabled()) {
LOG.warn("onServicesDiscovered " + getGattStatusMessage(status));
}
LOG.warn("Gatt device is RileyLink device: " + rileyLinkFound);
LOG.info("Gatt device is RileyLink device: " + rileyLinkFound);
if (rileyLinkFound) {
mIsConnected = true;
@ -245,7 +249,8 @@ public class RileyLinkBLE {
}
} else {
LOG.error("onServicesDiscovered " + getGattStatusMessage(status));
if (isLogEnabled())
LOG.debug("onServicesDiscovered " + getGattStatusMessage(status));
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed);
}
}
@ -336,6 +341,7 @@ public class RileyLinkBLE {
}
if (bluetoothConnectionGatt.discoverServices()) {
if (isLogEnabled())
LOG.warn("Starting to discover GATT Services.");
return true;
} else {
@ -357,6 +363,7 @@ public class RileyLinkBLE {
public void findRileyLink(String RileyLinkAddress) {
if (isLogEnabled())
LOG.debug("RileyLink address: " + RileyLinkAddress);
// Must verify that this is a valid MAC, or crash.
@ -372,9 +379,9 @@ public class RileyLinkBLE {
// , BluetoothDevice.TRANSPORT_LE
if (bluetoothConnectionGatt == null) {
LOG.error("Failed to connect to Bluetooth Low Energy device at " + bluetoothAdapter.getAddress());
// Toast.makeText(context, "No Rileylink at " + bluetoothAdapter.getAddress(), Toast.LENGTH_SHORT).show();
} else {
if (gattDebugEnabled) {
if (isLogEnabled())
LOG.debug("Gatt Connected?");
}
}
@ -383,14 +390,13 @@ public class RileyLinkBLE {
public void disconnect() {
mIsConnected = false;
if (isLogEnabled())
LOG.warn("Closing GATT connection");
// Close old conenction
if (bluetoothConnectionGatt != null) {
// Not sure if to disconnect or to close first..
bluetoothConnectionGatt.disconnect();
manualDisconnect = true;
// bluetoothConnectionGatt.close();
// bluetoothConnectionGatt = null;
}
}
@ -430,6 +436,7 @@ public class RileyLinkBLE {
List<BluetoothGattDescriptor> list = chara.getDescriptors();
if (gattDebugEnabled) {
for (int i = 0; i < list.size(); i++) {
if (isLogEnabled())
LOG.debug("Found descriptor: " + list.get(i).toString());
}
}
@ -558,4 +565,8 @@ public class RileyLinkBLE {
return statusMessage;
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPBTCOMM);
}
}

View file

@ -46,7 +46,7 @@ public class RadioPacket {
}
case FourByteSixByteRileyLink: {
return pkt;
return getWithCRC();
}
default:

View file

@ -4,6 +4,7 @@ import org.apache.commons.lang3.NotImplementedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.RileyLinkCommand;
@ -18,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.CRC;
*/
public class RadioResponse {
private static final Logger LOG = LoggerFactory.getLogger(RadioResponse.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
public boolean decodedOK = false;
public int rssi;

View file

@ -4,7 +4,7 @@ import org.slf4j.Logger;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.FabricUtil;
/**
* Created by andy on 11/24/18.
@ -53,13 +53,14 @@ public abstract class Encoding4b6bAbstract implements Encoding4b6b {
public void writeError(Logger LOG, byte[] raw, String errorData) {
LOG.error("=============================================================================");
LOG.error(" Decoded payload length is zero.");
LOG.error(" encodedPayload: {}", ByteUtil.getHex(raw));
LOG.error(" errors: {}", errorData);
LOG.error("=============================================================================");
LOG.error("\n=============================================================================\n" + //
" Decoded payload length is zero.\n" +
" encodedPayload: {}\n" +
" errors: {}\n" +
"=============================================================================", //
ByteUtil.getHex(raw), errorData);
FabricUtil.createEvent("MedtronicDecode4b6bError", null);
//FabricUtil.createEvent("MedtronicDecode4b6bError", null);
return;

View file

@ -5,7 +5,7 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs;
*/
public enum RileyLinkBLEError {
CodingErrors("Coding Errors encpountered during decode of RileyLink packet."), //
CodingErrors("Coding Errors encountered during decode of RileyLink packet."), //
Timeout("Timeout"), //
Interrupted("Interrupted"),
TooShortOrNullResponse("Too short or null decoded response.");

View file

@ -1,17 +1,42 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs;
import java.util.HashMap;
import java.util.Map;
import info.nightscout.androidaps.R;
public enum RileyLinkEncodingType {
None(0x00), // No encoding on RL
Manchester(0x01), // Manchester encoding on RL (for Omnipod)
FourByteSixByteRileyLink(0x02), // 4b6b encoding on RL (for Medtronic)
FourByteSixByteLocal(0x00), // No encoding on RL, but 4b6b encoding in code
None(0x00, null), // No encoding on RL
Manchester(0x01, null), // Manchester encoding on RL (for Omnipod)
FourByteSixByteRileyLink(0x02, R.string.medtronic_pump_encoding_4b6b_rileylink), // 4b6b encoding on RL (for Medtronic)
FourByteSixByteLocal(0x00, R.string.medtronic_pump_encoding_4b6b_local), // No encoding on RL, but 4b6b encoding in code
;
public byte value;
public Integer resourceId;
public String description;
private static Map<String, RileyLinkEncodingType> encodingTypeMap;
static {
encodingTypeMap = new HashMap<>();
for (RileyLinkEncodingType encType : values()) {
if (encType.resourceId!=null) {
}
}
}
RileyLinkEncodingType(int value) {
this.value = (byte)value;
}
RileyLinkEncodingType(int value, Integer resourceId) {
this.value = (byte)value;
this.resourceId = resourceId;
}
}

View file

@ -10,6 +10,7 @@ import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.SystemClock;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes;
@ -18,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Gatt
*/
public class CharacteristicReadOperation extends BLECommOperation {
private static final Logger LOG = LoggerFactory.getLogger(CharacteristicReadOperation.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
private BluetoothGattCharacteristic characteristic;
@ -44,6 +45,7 @@ public class CharacteristicReadOperation extends BLECommOperation {
timedOut = true;
}
} catch (InterruptedException e) {
if (isLogEnabled())
LOG.error("Interrupted while waiting for gatt write operation to complete");
interrupted = true;
}
@ -62,4 +64,8 @@ public class CharacteristicReadOperation extends BLECommOperation {
operationComplete.release();
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPBTCOMM);
}
}

View file

@ -10,6 +10,7 @@ import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.SystemClock;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes;
@ -18,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Gatt
*/
public class CharacteristicWriteOperation extends BLECommOperation {
private static final Logger LOG = LoggerFactory.getLogger(CharacteristicWriteOperation.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
private BluetoothGattCharacteristic characteristic;
@ -65,4 +66,9 @@ public class CharacteristicWriteOperation extends BLECommOperation {
operationComplete.release();
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPBTCOMM);
}
}

View file

@ -118,7 +118,10 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
this.deviceModel.setText(medtronicPumpStatus.pumpType.getDescription());
this.serialNumber.setText(medtronicPumpStatus.serialNumber);
this.pumpFrequency.setText(medtronicPumpStatus.pumpFrequency);
if (MedtronicUtil.getMedtronicPumpModel() != null) // FIXME change this when we have omnipod
// TODO extend when Omnipod used
if (MedtronicUtil.getMedtronicPumpModel() != null)
this.connectedDevice.setText("Medtronic " + MedtronicUtil.getMedtronicPumpModel().getPumpModel());
else
this.connectedDevice.setText("???");
@ -127,7 +130,6 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
this.lastUsedFrequency.setText(String.format(Locale.ENGLISH, "%.2f MHz",
rileyLinkServiceData.lastGoodFrequency));
// FIXME
if (medtronicPumpStatus.lastConnection != 0)
this.lastDeviceContact.setText(StringUtil.toDateTimeString(new LocalDateTime(
medtronicPumpStatus.lastDataTime)));

View file

@ -25,14 +25,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState;
public class RileyLinkStatusHistory extends Fragment implements RefreshableInterface {
// @BindView(R.id.rileylink_history_list)
// ListView listView;
RecyclerView recyclerView;
RecyclerViewAdapter recyclerViewAdapter;
// RileyLinkHistoryListAdapter adapter;
LinearLayoutManager llm;
List<RLHistoryItem> filteredHistoryList = new ArrayList<>();
@ -41,8 +36,6 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rileylink_status_history, container, false);
// adapter = new RileyLinkHistoryListAdapter();
recyclerView = (RecyclerView)rootView.findViewById(R.id.rileylink_history_list);
recyclerView.setHasFixedSize(true);
@ -60,10 +53,6 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
public void onStart() {
super.onStart();
// this.listView = (ListView)getActivity().findViewById(R.id.rileylink_history_list);
// listView.setAdapter(adapter);
refreshData();
}
@ -73,12 +62,6 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
recyclerViewAdapter.addItemsAndClean(RileyLinkUtil.getRileyLinkHistory());
}
// static class ViewHolder {
//
// TextView itemTime;
// TextView itemSource;
// TextView itemDescription;
// }
public static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder> {
@ -173,108 +156,4 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
}
}
// private class RileyLinkHistoryListAdapter extends BaseAdapter {
//
// private List<RLHistoryItem> historyItemList;
// private LayoutInflater mInflator;
//
//
// public RileyLinkHistoryListAdapter() {
// super();
// historyItemList = new ArrayList<>();
// mInflator = RileyLinkStatusHistory.this.getLayoutInflater();
// }
//
//
// public void addItem(RLHistoryItem item) {
// if (!historyItemList.contains(item)) {
// historyItemList.add(item);
// notifyDataSetChanged();
// }
// }
//
//
// public RLHistoryItem getHistoryItem(int position) {
// return historyItemList.get(position);
// }
//
//
// public void addItemsAndClean(List<RLHistoryItem> items) {
// this.historyItemList.clear();
//
// for (RLHistoryItem item : items) {
//
// if (!historyItemList.contains(item) && isValidItem(item)) {
// historyItemList.add(item);
// }
// }
//
// notifyDataSetChanged();
// }
//
//
// private boolean isValidItem(RLHistoryItem item) {
//
// PumpDeviceState pumpState = item.getPumpDeviceState();
//
// if ((pumpState != null) && //
// (pumpState == PumpDeviceState.Sleeping || //
// pumpState == PumpDeviceState.Active || //
// pumpState == PumpDeviceState.WakingUp //
// ))
// return false;
//
// return true;
//
// }
//
//
// public void clear() {
// historyItemList.clear();
// notifyDataSetChanged();
// }
//
//
// @Override
// public int getCount() {
// return historyItemList.size();
// }
//
//
// @Override
// public Object getItem(int i) {
// return historyItemList.get(i);
// }
//
//
// @Override
// public long getItemId(int i) {
// return i;
// }
//
//
// @Override
// public View getView(int i, View view, ViewGroup viewGroup) {
// RileyLinkStatusHistory.ViewHolder viewHolder;
// // General ListView optimization code.
// if (view == null) {
// view = mInflator.inflate(R.layout.rileylink_status_history_item, null);
// viewHolder = new RileyLinkStatusHistory.ViewHolder();
// viewHolder.itemTime = (TextView)view.findViewById(R.id.rileylink_history_time);
// viewHolder.itemSource = (TextView)view.findViewById(R.id.rileylink_history_source);
// viewHolder.itemDescription = (TextView)view.findViewById(R.id.rileylink_history_description);
// view.setTag(viewHolder);
// } else {
// viewHolder = (RileyLinkStatusHistory.ViewHolder)view.getTag();
// }
//
// RLHistoryItem item = historyItemList.get(i);
// viewHolder.itemTime.setText(StringUtil.toDateTimeString(item.getDateTime()));
// viewHolder.itemSource.setText(item.getSource().getDesc()); // for now
// viewHolder.itemDescription.setText(item.getDescription());
//
// return view;
// }
// }
}

View file

@ -19,6 +19,7 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion;
@ -38,10 +39,9 @@ import info.nightscout.androidaps.utils.SP;
*/
public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
private static final Logger LOG = LoggerFactory.getLogger(RileyLinkBroadcastReceiver.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
RileyLinkService serviceInstance;
// protected RileyLinkIPCConnection rileyLinkIPCConnection;
protected Map<String, List<String>> broadcastIdentifiers = null;
String deviceSpecificPrefix;
Context context;
@ -51,10 +51,6 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
this.serviceInstance = serviceInstance;
this.context = context;
// TODO remove in AAPS -- Andy
// rileyLinkIPCConnection = new RileyLinkIPCConnection(context);
// RileyLinkUtil.setRileyLinkIPCConnection(rileyLinkIPCConnection);
createBroadcastIdentifiers();
}
@ -71,8 +67,6 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
// TuneUp
this.broadcastIdentifiers.put("TuneUp", Arrays.asList( //
// RT2Const.IPC.MSG_PUMP_tunePump, //
// RT2Const.IPC.MSG_PUMP_quickTune, //
RileyLinkConst.IPC.MSG_PUMP_tunePump, //
RileyLinkConst.IPC.MSG_PUMP_quickTune));
@ -88,10 +82,6 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
deviceSpecificPrefix = serviceInstance.getDeviceSpecificBroadcastsIdentifierPrefix();
// Application specific
// this.broadcastIdentifiers.put("AppSpecific", Arrays.asList( //
// RT2Const.serviceLocal.ipcBound, //
// RT2Const.IPC.MSG_ServiceCommand, //
// RT2Const.serviceLocal.INTENT_sessionCompleted));
}
@ -106,6 +96,7 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
if (action == null) {
LOG.error("onReceive: null action");
} else {
if (isLoggingEnabled())
LOG.debug("Received Broadcast: " + action);
if (!processBluetoothBroadcasts(action) && //
@ -128,7 +119,6 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
for (Map.Entry<String, List<String>> stringListEntry : broadcastIdentifiers.entrySet()) {
for (String intentKey : stringListEntry.getValue()) {
System.out.println("Intent: " + intentKey);
intentFilter.addAction(intentKey);
}
}
@ -138,7 +128,6 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
}
LocalBroadcastManager.getInstance(context).registerReceiver(this, intentFilter);
}
@ -154,8 +143,14 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
return true;
} else if (action.equals(RileyLinkConst.Intents.RileyLinkReady)) {
if (isLoggingEnabled())
LOG.warn("MedtronicConst.Intents.RileyLinkReady");
// sendIPCNotification(RT2Const.IPC.MSG_note_WakingPump);
if (this.serviceInstance.rileyLinkBLE==null)
return false;
this.serviceInstance.rileyLinkBLE.enableNotifications();
this.serviceInstance.rfspy.startReader(); // call startReader from outside?
@ -163,14 +158,17 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
String bleVersion = this.serviceInstance.rfspy.getBLEVersionCached();
RileyLinkFirmwareVersion rlVersion = this.serviceInstance.rfspy.getRLVersionCached();
// if (isLoggingEnabled())
LOG.debug("RfSpy version (BLE113): " + bleVersion);
this.serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion;
// if (isLoggingEnabled())
LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name());
this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion;
ServiceTask task = new InitializePumpManagerTask(RileyLinkUtil.getTargetDevice());
ServiceTaskExecutor.startTask(task);
if (isLoggingEnabled())
LOG.info("Announcing RileyLink open For business");
return true;
@ -200,22 +198,16 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
public boolean processBluetoothBroadcasts(String action) {
if (action.equals(RileyLinkConst.Intents.BluetoothConnected)) {
if (isLoggingEnabled())
LOG.debug("Bluetooth - Connected");
// sendIPCNotification(RT2Const.IPC.MSG_note_FindingRileyLink);
ServiceTaskExecutor.startTask(new DiscoverGattServicesTask());
return true;
} else if (action.equals(RileyLinkConst.Intents.BluetoothReconnected)) {
if (isLoggingEnabled())
LOG.debug("Bluetooth - Reconnecting");
// sendIPCNotification(RT2Const.IPC.MSG_note_FindingRileyLink);
serviceInstance.bluetoothInit();
ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(true));
return true;
} else if (action.equals(RileyLinkConst.Intents.BluetoothReconnected)) {
LOG.debug("Bluetooth - Reconnected");
// sendIPCNotification(RT2Const.IPC.MSG_note_FindingRileyLink);
serviceInstance.bluetoothInit();
ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(true));
@ -255,33 +247,12 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
public boolean processApplicationSpecificBroadcasts(String action, Intent intent) {
// if (action.equals(RT2Const.serviceLocal.ipcBound)) {
// // If we still need permission for bluetooth, ask now.
// // if (needBluetoothPermission) {
// // sendBLERequestForAccess();
// // }
// return true;
// } else if (RT2Const.IPC.MSG_ServiceCommand.equals(action)) {
// serviceInstance.handleIncomingServiceTransport(intent);
// return true;
// } else if (RT2Const.serviceLocal.INTENT_sessionCompleted.equals(action)) {
// Bundle bundle = intent.getBundleExtra(RT2Const.IPC.bundleKey);
// if (bundle != null) {
// ServiceTransport transport = new ServiceTransport(bundle);
// rileyLinkIPCConnection.sendTransport(transport, transport.getSenderHashcode());
// } else {
// LOG.error("sessionCompleted: no bundle!");
// }
// return true;
// } else {
// return false;
// }
return false;
}
public void sendIPCNotification(String notification) {
// rileyLinkIPCConnection.sendNotification(new ServiceNotification(notification), null);
public boolean isLoggingEnabled() {
return (L.isEnabled(L.PUMPCOMM));
}
}

View file

@ -11,6 +11,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
@ -32,7 +33,7 @@ import info.nightscout.androidaps.utils.SP;
*/
public abstract class RileyLinkService extends Service {
private static final Logger LOG = LoggerFactory.getLogger(RileyLinkService.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
public RileyLinkBLE rileyLinkBLE; // android-bluetooth management
protected BluetoothAdapter bluetoothAdapter;
@ -41,23 +42,11 @@ public abstract class RileyLinkService extends Service {
protected RileyLinkBroadcastReceiver mBroadcastReceiver;
protected RileyLinkServiceData rileyLinkServiceData;
// protected RileyLinkTargetFrequency rileyLinkTargetFrequency;
// protected static final String WAKELOCKNAME = "com.gxwtech.roundtrip2.RoundtripServiceWakeLock";
// protected static volatile PowerManager.WakeLock lockStatic = null;
// Our hardware/software connection
// protected boolean needBluetoothPermission = true;
// protected RileyLinkIPCConnection rileyLinkIPCConnection;
// public RileyLinkCommunicationManager pumpCommunicationManager;
public RileyLinkService(Context context) {
super();
this.context = context;
RileyLinkUtil.setContext(this.context);
determineRileyLinkTargetFrequency();
RileyLinkUtil.setRileyLinkService(this);
// RileyLinkUtil.setRileyLinkTargetFrequency(rileyLinkTargetFrequency);
RileyLinkUtil.setEncoding(getEncoding());
initRileyLinkServiceData();
}
@ -69,12 +58,6 @@ public abstract class RileyLinkService extends Service {
public abstract RileyLinkEncodingType getEncoding();
/**
* You need to determine which frequencies RileyLink will use, and set rileyLinkTargetFrequency
*/
protected abstract void determineRileyLinkTargetFrequency();
/**
* If you have customized RileyLinkServiceData you need to override this
*/
@ -83,14 +66,14 @@ public abstract class RileyLinkService extends Service {
@Override
public boolean onUnbind(Intent intent) {
LOG.warn("onUnbind");
//LOG.warn("onUnbind");
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
LOG.warn("onRebind");
//LOG.warn("onRebind");
super.onRebind(intent);
}
@ -98,7 +81,7 @@ public abstract class RileyLinkService extends Service {
@Override
public void onDestroy() {
super.onDestroy();
LOG.error("I die! I die!");
//LOG.error("I die! I die!");
if (rileyLinkBLE != null) {
rileyLinkBLE.disconnect(); // dispose of Gatt (disconnect and close)
@ -110,12 +93,12 @@ public abstract class RileyLinkService extends Service {
@Override
public void onCreate() {
super.onCreate();
LOG.debug("onCreate");
//LOG.debug("onCreate");
mBroadcastReceiver = new RileyLinkBroadcastReceiver(this, this.context);
mBroadcastReceiver.registerBroadcasts();
LOG.debug("onCreate(): It's ALIVE!");
//LOG.debug("onCreate(): It's ALIVE!");
}
@ -144,13 +127,13 @@ public abstract class RileyLinkService extends Service {
// We've received a service startCommand, we grab the lock.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LOG.debug("onStartCommand");
RileyLinkUtil.setContext(getApplicationContext());
return (START_STICKY);
}
public boolean bluetoothInit() {
if (isLogEnabled())
LOG.debug("bluetoothInit: attempting to get an adapter");
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing);
@ -162,9 +145,6 @@ public abstract class RileyLinkService extends Service {
} else {
if (!bluetoothAdapter.isEnabled()) {
// sendBLERequestForAccess();
LOG.error("Bluetooth is not enabled.");
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled);
} else {
@ -189,11 +169,14 @@ public abstract class RileyLinkService extends Service {
if (rileyLinkBLE.isConnected()) {
if (deviceAddress.equals(rileyLinkServiceData.rileylinkAddress)) {
if (isLogEnabled())
LOG.info("No change to RL address. Not reconnecting.");
return false;
} else {
if (isLogEnabled())
LOG.warn("Disconnecting from old RL (" + rileyLinkServiceData.rileylinkAddress
+ "), reconnecting to new: " + deviceAddress);
rileyLinkBLE.disconnect();
// prolly need to shut down listening thread too?
// SP.putString(MedtronicConst.Prefs.RileyLinkAddress, deviceAddress);
@ -203,8 +186,8 @@ public abstract class RileyLinkService extends Service {
return true;
}
} else {
// Toast.makeText(context, "Using RL " + deviceAddress, Toast.LENGTH_SHORT).show();
LOG.debug("handleIPCMessage: Using RL " + deviceAddress);
if (isLogEnabled())
LOG.debug("Using RL " + deviceAddress);
if (RileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) {
if (!bluetoothInit()) {
@ -222,16 +205,6 @@ public abstract class RileyLinkService extends Service {
public void sendServiceTransportResponse(ServiceTransport transport, ServiceResult serviceResult) {
// get the key (hashcode) of the client who requested this
/*
* Integer clientHashcode = transport.getSenderHashcode();
* // make a new bundle to send as the message data
* transport.setServiceResult(serviceResult);
* // FIXME
* transport.setTransportType(RT2Const.IPC.MSG_ServiceResult);
*/
// rileyLinkIPCConnection.sendTransport(transport, clientHashcode);
LOG.error("sendServiceTransportResponse not implemented.");
}
@ -250,24 +223,11 @@ public abstract class RileyLinkService extends Service {
}
double newFrequency;
// if ((lastGoodFrequency > 0.0d) && getRileyLinkCommunicationManager().isValidFrequency(lastGoodFrequency)) {
// LOG.info("Checking for pump near last saved frequency of {}MHz", lastGoodFrequency);
// // we have an old frequency, so let's start there.
// newFrequency = getDeviceCommunicationManager().quickTuneForPump(lastGoodFrequency);
// if (newFrequency == 0.0) {
// // quick scan failed to find pump. Try full scan
// LOG.warn("Failed to find pump near last saved frequency, doing full scan");
// newFrequency = getDeviceCommunicationManager().tuneForDevice();
// }
// } else {
// LOG.warn("No saved frequency for pump, doing full scan.");
// // we don't have a saved frequency, so do the full scan.
// newFrequency = getDeviceCommunicationManager().tuneForDevice();
// }
newFrequency = getDeviceCommunicationManager().tuneForDevice();
if ((newFrequency != 0.0) && (newFrequency != lastGoodFrequency)) {
if (isLogEnabled())
LOG.info("Saving new pump frequency of {} MHz", newFrequency);
SP.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, newFrequency);
rileyLinkServiceData.lastGoodFrequency = newFrequency;
@ -303,4 +263,9 @@ public abstract class RileyLinkService extends Service {
public RileyLinkTargetDevice getRileyLinkTargetDevice() {
return this.rileyLinkServiceData.targetDevice;
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -39,4 +39,5 @@ public class RileyLinkServiceData {
this.pumpID = pumpId;
this.pumpIDBytes = pumpIdBytes;
}
}

View file

@ -2,6 +2,10 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.task
import android.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError;
@ -20,7 +24,7 @@ public class InitializePumpManagerTask extends ServiceTask {
private static final String TAG = "InitPumpManagerTask";
private RileyLinkTargetDevice targetDevice;
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
public InitializePumpManagerTask(RileyLinkTargetDevice targetDevice) {
super();
@ -51,22 +55,21 @@ public class InitializePumpManagerTask extends ServiceTask {
RileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkReady);
Log.i(TAG, String.format("Setting radio frequency to %.2fMHz", lastGoodFrequency));
if (L.isEnabled(L.PUMPCOMM))
LOG.info("Setting radio frequency to {} MHz", lastGoodFrequency);
RileyLinkUtil.getRileyLinkCommunicationManager().setRadioFrequencyForPump(lastGoodFrequency);
boolean foundThePump = RileyLinkUtil.getRileyLinkCommunicationManager().tryToConnectToDevice();
if (foundThePump) {
RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady);
// RileyLinkUtil.sendNotification(new ServiceNotification(RT2Const.IPC.MSG_PUMP_pumpFound), null);
} else {
RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError,
RileyLinkError.NoContactWithDevice);
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump);
// RileyLinkUtil.sendNotification(new ServiceNotification(RT2Const.IPC.MSG_PUMP_pumpLost), null);
}
// RileyLinkUtil.sendNotification(new ServiceNotification(RT2Const.IPC.MSG_note_Idle), null);
} else {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump);
}

View file

@ -7,16 +7,22 @@ package info.nightscout.androidaps.plugins.pump.common.utils;
import android.util.Log;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import info.nightscout.androidaps.logging.L;
/**
* This is simple version of ATechDate, limited only to one format (yyyymmddHHMIss)
*/
public class DateTimeUtil {
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
/**
* DateTime is packed as long: yyyymmddHHMMss
*
@ -44,7 +50,8 @@ public class DateTimeUtil {
try {
return new LocalDateTime(year, month, dayOfMonth, hourOfDay, minute, second);
} catch (Exception ex) {
Log.e("DateTimeUtil", String.format("Error creating LocalDateTime from values [atechDateTime=%d, year=%d, month=%d, day=%d, hour=%d, minute=%d, second=%d]", atechDateTime, year, month, dayOfMonth, hourOfDay, minute, second));
if (L.isEnabled(L.PUMPCOMM))
LOG.error("DateTimeUtil", String.format("Error creating LocalDateTime from values [atechDateTime=%d, year=%d, month=%d, day=%d, hour=%d, minute=%d, second=%d]", atechDateTime, year, month, dayOfMonth, hourOfDay, minute, second));
//return null;
throw ex;
}

View file

@ -31,6 +31,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
@ -55,7 +56,7 @@ import info.nightscout.androidaps.utils.SetWarnColor;
public class MedtronicFragment extends SubscriberFragment {
private static Logger LOG = LoggerFactory.getLogger(MedtronicFragment.class);
private static Logger LOG = LoggerFactory.getLogger(L.PUMP);
@BindView(R.id.medtronic_lastconnection)
TextView lastConnectionView;
@ -205,6 +206,7 @@ public class MedtronicFragment extends SubscriberFragment {
@Subscribe
public void onStatusEvent(final EventMedtronicDeviceStatusChange eventStatusChange) {
if (isLogEnabled())
LOG.info("onStatusEvent(EventMedtronicDeviceStatusChange): {}", eventStatusChange);
Activity activity = getActivity();
@ -266,7 +268,6 @@ public class MedtronicFragment extends SubscriberFragment {
if (pumpStatusIconView != null) {
if (pumpStatus.pumpDeviceState != null) {
// TODO Pump State
switch (pumpStatus.pumpDeviceState) {
case Sleeping:
@ -282,7 +283,6 @@ public class MedtronicFragment extends SubscriberFragment {
pumpStatusIconView.setText(" " + getTranslation(pumpStatus.pumpDeviceState.getResourceId()));
break;
// FIXME
case Active: {
MedtronicCommandType cmd = MedtronicUtil.getCurrentCommand();
@ -305,7 +305,7 @@ public class MedtronicFragment extends SubscriberFragment {
} else {
if (resourceId == null) {
pumpStatusIconView.setText(" " + cmd.name());
pumpStatusIconView.setText(" " + cmd.getCommandDescription());
} else {
pumpStatusIconView.setText(" " + getTranslation(resourceId));
}
@ -316,15 +316,6 @@ public class MedtronicFragment extends SubscriberFragment {
}
break;
// // FIXME
//
// pumpStatusIconView.setText(" " + pumpStatus.pumpDeviceState.name());
// break;
//
// // FIXME
//
// pumpStatusIconView.setText(" " + pumpStatus.pumpDeviceState.name());
// break;
default:
LOG.warn("Unknown pump state: " + pumpStatus.pumpDeviceState);
}
@ -376,7 +367,8 @@ public class MedtronicFragment extends SubscriberFragment {
@Subscribe
public void onStatusEvent(final EventMedtronicPumpConfigurationChanged s) {
LOG.error("EventMedtronicPumpConfigurationChanged triggered");
if (isLogEnabled())
LOG.debug("EventMedtronicPumpConfigurationChanged triggered");
MedtronicPumpStatus pumpStatus = MedtronicUtil.getPumpStatus();
pumpStatus.verifyConfiguration();
updateGUI();
@ -471,7 +463,6 @@ public class MedtronicFragment extends SubscriberFragment {
basaBasalRateView.setText("(" + (pumpStatus.activeProfileName) + ") "
+ MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate()));
// FIXME temp basal - check - maybe set as combo ??
if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) {
if (TreatmentsPlugin.getPlugin().isInHistoryRealTempBasalInProgress()) {
tempBasalView.setText(TreatmentsPlugin.getPlugin()
@ -503,4 +494,10 @@ public class MedtronicFragment extends SubscriberFragment {
});
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMP);
}
}

View file

@ -106,6 +106,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
public static boolean isBusy = false;
private List<Long> busyTimestamps = new ArrayList<>();
private boolean sendIdToFirebase = false;
private MedtronicPumpPlugin() {
@ -565,6 +566,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
pumpState = PumpDriverState.Initialized;
}
if (!sendIdToFirebase) {
sendIdToFirebase = true;
}
// FIXME andy!!!
// MainApp.getFirebaseAnalytics().logCustomEvent(FirebaseAnalytics.Event.SELECT_CONTENT, event);
//
@ -1388,15 +1397,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private CustomAction customActionClearBolusBlock = new CustomAction(
R.string.medtronic_custom_action_clear_bolus_block, MedtronicCustomActionType.ClearBolusBlock, false);
private CustomAction customActionReset = new CustomAction(
R.string.medtronic_custom_action_reset_rileylink, MedtronicCustomActionType.ResetRileyLink, false);
// private CustomAction customActionReset = new CustomAction(
// R.string.medtronic_custom_action_reset_rileylink, MedtronicCustomActionType.ResetRileyLink, false);
@Override
public List<CustomAction> getCustomActions() {
if (customActions == null) {
this.customActions = Arrays.asList(customActionWakeUpAndTune, customActionClearBolusBlock, customActionReset);
this.customActions = Arrays.asList(customActionWakeUpAndTune, customActionClearBolusBlock);
}
return this.customActions;
@ -1442,7 +1451,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (customAction == MedtronicCustomActionType.ClearBolusBlock) {
this.customActionClearBolusBlock.setEnabled(isEnabled);
} else if (customAction == MedtronicCustomActionType.ResetRileyLink) {
this.customActionReset.setEnabled(isEnabled);
//this.customActionReset.setEnabled(isEnabled);
}
refreshCustomActionsList();

View file

@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
import android.content.Context;
import android.os.SystemClock;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy;
@ -53,7 +54,7 @@ import info.nightscout.androidaps.utils.SP;
*/
public class MedtronicCommunicationManager extends RileyLinkCommunicationManager {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicCommunicationManager.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
private static final int MAX_COMMAND_TRIES = 3;
private static final int DEFAULT_TIMEOUT = 2000;
private static final long RILEYLINK_TIMEOUT = 15 * 60 * 1000; // 15 min
@ -61,7 +62,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
static MedtronicCommunicationManager medtronicCommunicationManager;
String errorMessage;
private MedtronicConverter medtronicConverter;
private boolean debugSetCommands = true;
private boolean debugSetCommands = isLogEnabled();
private MedtronicPumpHistoryDecoder pumpHistoryDecoder;
private boolean doWakeUpBeforeCommand = true;
private boolean firstConnection = true;
@ -75,7 +77,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder();
MedtronicUtil.getPumpStatus().previousConnection = SP.getLong(
RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L);
}
@ -122,6 +123,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
for (int retry = 0; retry < 5; retry++) {
if (isLogEnabled())
LOG.debug("isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : ""));
boolean connected = connectToDevice();
@ -156,9 +158,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple
RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte)0, (byte)200,
(byte)0, (byte)0, 25000, (byte)0);
if (isLogEnabled())
LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw()));
if (rfSpyResponse.wasTimeout()) {
if (isLogEnabled())
LOG.error("isDeviceReachable. Failed to find pump (timeout).");
} else if (rfSpyResponse.looksLikeRadioPacket()) {
RadioResponse radioResponse = new RadioResponse();
@ -172,6 +176,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload(), PumpMessage.class);
if (!pumpResponse.isValid()) {
if (isLogEnabled())
LOG.warn("Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(),
rfSpyResponse.wasTimeout());
} else {
@ -187,6 +192,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
MedtronicUtil.setMedtronicPumpModel(pumpModel);
}
if (isLogEnabled())
LOG.debug("isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid,
radioResponse.rssi);
@ -196,8 +202,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
else
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
if (firstConnection)
checkFirstConnectionTime();
// if (firstConnection)
// checkFirstConnectionTime();
rememberLastGoodDeviceCommunicationTime();
@ -211,16 +217,19 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
} else {
if (isLogEnabled())
LOG.warn("isDeviceReachable. Failed to parse radio response: "
+ ByteUtil.shortHexString(rfSpyResponse.getRaw()));
}
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.warn("isDeviceReachable. Failed to decode radio response: "
+ ByteUtil.shortHexString(rfSpyResponse.getRaw()));
}
} else {
if (isLogEnabled())
LOG.warn("isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw()));
}
@ -228,55 +237,12 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
// FIXME must not call getPumpModel !!!!!!!!!!!!!
@Override
public boolean tryToConnectToDevice() {
return isDeviceReachable(true);
// wakeUp(true);
//
// MedtronicDeviceType pumpModel = getPumpModel();
//
// // Andy (4.6.2018): we do retry if no data returned. We might need to do that everywhere, but that might
// require
// // little bit of rewrite of RF Code.
// if (pumpModel == MedtronicDeviceType.Unknown_Device) {
//
// SystemClock.sleep(1000);
//
// pumpModel = getPumpModel();
// }
//
// boolean connected = (pumpModel != MedtronicDeviceType.Unknown_Device);
//
// if (connected) {
// checkFirstConnectionTime();
// rememberLastGoodDeviceCommunicationTime();
// }
//
// return (pumpModel != MedtronicDeviceType.Unknown_Device);
}
private void setLastConnectionTime() {
// FIXME rename
this.pumpStatus.setLastCommunicationToNow();
// FIXME set to SP
}
private void checkFirstConnectionTime() {
// FIXME set to SP
firstConnection = false;
}
// FIXME remove debugs - Andy
private PumpMessage runCommandWithArgs(PumpMessage msg) throws RileyLinkCommunicationException {
if (debugSetCommands)
@ -296,82 +262,18 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
return rval;
} else {
if (isLogEnabled())
LOG.error("runCommandWithArgs: Pump did not ack Attention packet");
return new PumpMessage("No ACK after Attention packet.");
}
}
// @Deprecated
// private PumpMessage runCommandWithArgsLong(MedtronicCommandType commandType, byte[] content) {
//
// LOG.debug("Run command with Args (Long): {}", commandType.name());
//
// PumpMessage rval = null;
// PumpMessage shortMessage = makePumpMessage(commandType, new CarelinkShortMessageBody(new byte[] { 0 }));
// // look for ack from short message
// PumpMessage shortResponse = sendAndListen(shortMessage);
//
// if (shortResponse.commandType != MedtronicCommandType.CommandACK) {
// LOG.error("runCommandWithArgs: Pump did not ack Attention packet");
//
// return new PumpMessage("No ACK after start message.");
// }
//
// int start = 0;
// int frameNr = 1;
// int len = 0;
//
// do {
//
// if (start == 0)
// LOG.debug("Run command with Args(Long): Got ACK response for Attention packet");
// else
// LOG.debug("Run command with Args(Long): Got ACK response for frame #{}", (frameNr - 1));
//
// if (start + 64 > content.length) {
// len = content.length - start;
//
// if (len == 0)
// break;
// } else {
// len = 64;
// }
//
// byte frame[] = new byte[65];
//
// frame[0] = (byte)frameNr;
//
// System.arraycopy(content, start, frame, 1, len);
//
// PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(frame));
//
// rval = sendAndListen(msg);
//
// if (rval.commandType != MedtronicCommandType.CommandACK) {
// LOG.error("runCommandWithArgs(Long): Pump did not ACK frame #{}", frameNr);
//
// return new PumpMessage("No ACK after frame #" + frameNr);
// }
//
// if (len != 64) {
// LOG.debug("Run command with Args(Long): Got ACK response for frame #{}", (frameNr));
// break;
// }
//
// start += 64;
// frameNr++;
//
// } while (true);
//
// return rval;
//
// // return new PumpMessage("No ACK");
// }
private PumpMessage runCommandWithFrames(MedtronicCommandType commandType, List<List<Byte>> frames)
throws RileyLinkCommunicationException {
if (isLogEnabled())
LOG.debug("Run command with Frames: {}", commandType.name());
PumpMessage rval = null;
@ -380,10 +282,12 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage shortResponse = sendAndListen(shortMessage);
if (shortResponse.commandType != MedtronicCommandType.CommandACK) {
if (isLogEnabled())
LOG.error("runCommandWithFrames: Pump did not ack Attention packet");
return new PumpMessage("No ACK after start message.");
} else {
if (isLogEnabled())
LOG.debug("Run command with Frames: Got ACK response for Attention packet");
}
@ -402,13 +306,16 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
// LOG.debug("PumpResponse: " + rval);
if (rval.commandType != MedtronicCommandType.CommandACK) {
if (isLogEnabled())
LOG.error("runCommandWithFrames: Pump did not ACK frame #{}", frameNr);
if (isLogEnabled())
LOG.error("Run command with Frames FAILED (command={}, response={})", commandType.name(),
rval.toString());
return new PumpMessage("No ACK after frame #" + frameNr);
} else {
if (isLogEnabled())
LOG.debug("Run command with Frames: Got ACK response for frame #{}", (frameNr));
}
@ -428,6 +335,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (doWakeUpBeforeCommand)
wakeUp(receiverDeviceAwakeForMinutes, false);
if (isLogEnabled())
LOG.debug("Current command: " + MedtronicUtil.getCurrentCommand());
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Active);
@ -440,6 +348,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData,
new GetHistoryPageCarelinkMessageBody(pageNumber));
if (isLogEnabled())
LOG.info("getPumpHistory: Page {}", pageNumber);
// LOG.info("getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData()));
// Ask the pump to transfer history (we get first frame?)
@ -456,6 +365,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
failed = false;
break;
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.error("First call for PumpHistory failed (retry={})", retries);
failed = true;
}
@ -483,6 +393,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
&& currentResponse.getFrameNumber() == expectedFrameNum) {
// success! got a frame.
if (frameData.length != 64) {
if (isLogEnabled())
LOG.warn("Expected frame of length 64, got frame of length " + frameData.length);
// but append it anyway?
}
@ -493,6 +404,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
MedtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber,
currentResponse.getFrameNumber());
if (isLogEnabled())
LOG.info("getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber);
// Do we need to ask for the next frame?
if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722
@ -502,15 +414,19 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
} else {
if (frameData == null) {
if (isLogEnabled())
LOG.error("null frame data, retrying");
} else if (currentResponse.getFrameNumber() != expectedFrameNum) {
if (isLogEnabled())
LOG.warn("Expected frame number {}, received {} (retrying)", expectedFrameNum,
currentResponse.getFrameNumber());
} else if (frameData.length == 0) {
if (isLogEnabled())
LOG.warn("Frame has zero length, retrying");
}
failures++;
if (failures == 6) {
if (isLogEnabled())
LOG.error(
"getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.",
expectedFrameNum, pageNumber);
@ -529,24 +445,29 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
nextMsg = sendAndListen(ackMsg);
break;
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.error("Problem acknowledging frame response. (retry={})", retries);
}
}
if (nextMsg != null)
currentResponse = new GetHistoryPageCarelinkMessageBody(nextMsg.getMessageBody().getTxData());
else
else {
if (isLogEnabled())
LOG.error("We couldn't acknowledge frame from pump, aborting operation.");
}
}
}
if (rawHistoryPage.getLength() != 1024) {
if (isLogEnabled())
LOG.warn("getPumpHistory: short page. Expected length of 1024, found length of "
+ rawHistoryPage.getLength());
doneWithError = true;
}
if (!rawHistoryPage.isChecksumOK()) {
if (isLogEnabled())
LOG.error("getPumpHistory: checksum is wrong");
doneWithError = true;
}
@ -563,11 +484,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
List<PumpHistoryEntry> medtronicHistoryEntries = pumpHistoryDecoder
.processPageAndCreateRecords(rawHistoryPage);
if (isLogEnabled())
LOG.debug("getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size());
// PumpHistoryResult pumpHistoryResult = new PumpHistoryResult(lastEntry, targetDate);
pumpTotalResult.addHistoryEntries(medtronicHistoryEntries);
if (isLogEnabled())
LOG.debug("getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished());
if (pumpTotalResult.isSearchFinished()) {
@ -585,109 +508,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
// @Deprecated
// public Page getPumpHistoryPage(int pageNumber) {
// RawHistoryPage rval = new RawHistoryPage();
//
// if (doWakeUpBeforeCommand)
// wakeUp(receiverDeviceAwakeForMinutes, false);
//
// PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData,
// new GetHistoryPageCarelinkMessageBody(pageNumber));
// // LOG.info("getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData()));
// // Ask the pump to transfer history (we get first frame?)
// PumpMessage firstResponse = runCommandWithArgs(getHistoryMsg);
// // LOG.info("getPumpHistoryPage("+pageNumber+"): " + ByteUtil.shortHexString(firstResponse.getContents()));
//
// PumpMessage ackMsg = makePumpMessage(MedtronicCommandType.CommandACK, new PumpAckMessageBody());
// GetHistoryPageCarelinkMessageBody currentResponse = new GetHistoryPageCarelinkMessageBody(firstResponse
// .getMessageBody().getTxData());
// int expectedFrameNum = 1;
// boolean done = false;
// // while (expectedFrameNum == currentResponse.getFrameNumber()) {
// int failures = 0;
// while (!done) {
// // examine current response for problems.
// byte[] frameData = currentResponse.getFrameData();
// if ((frameData != null) && (frameData.length > 0) && currentResponse.getFrameNumber() == expectedFrameNum) {
// // success! got a frame.
// if (frameData.length != 64) {
// LOG.warn("Expected frame of length 64, got frame of length " + frameData.length);
// // but append it anyway?
// }
// // handle successful frame data
// rval.appendData(currentResponse.getFrameData());
// RileyLinkMedtronicService.getInstance().announceProgress(
// ((100 / 16) * currentResponse.getFrameNumber() + 1));
// LOG.info("getPumpHistoryPage: Got frame " + currentResponse.getFrameNumber());
// // Do we need to ask for the next frame?
// if (expectedFrameNum < 16) { // This number may not be correct for pumps other than 522/722
// expectedFrameNum++;
// } else {
// done = true; // successful completion
// }
// } else {
// if (frameData == null) {
// LOG.error("null frame data, retrying");
// } else if (currentResponse.getFrameNumber() != expectedFrameNum) {
// LOG.warn("Expected frame number {}, received {} (retrying)", expectedFrameNum,
// currentResponse.getFrameNumber());
// } else if (frameData.length == 0) {
// LOG.warn("Frame has zero length, retrying");
// }
// failures++;
// if (failures == 6) {
// LOG.error("6 failures in attempting to download frame {} of page {}, giving up.", expectedFrameNum,
// pageNumber);
// done = true; // failure completion.
// }
// }
// if (!done) {
// // ask for next frame
// PumpMessage nextMsg = sendAndListen(ackMsg);
// currentResponse = new GetHistoryPageCarelinkMessageBody(nextMsg.getMessageBody().getTxData());
// }
// }
// if (rval.getLength() != 1024) {
// LOG.warn("getPumpHistoryPage: short page. Expected length of 1024, found length of " + rval.getLength());
// }
// if (!rval.isChecksumOK()) {
// LOG.error("getPumpHistoryPage: checksum is wrong");
// }
//
// rval.dumpToDebug();
//
// Page page = new Page();
// // page.parseFrom(rval.getData(),PumpModel.MM522);
// // FIXME
// page.parseFrom(rval.getData(), MedtronicDeviceType.Medtronic_522);
//
// return page;
// }
// public ArrayList<Page> getAllHistoryPages() {
// ArrayList<Page> pages = new ArrayList<>();
//
// for (int pageNum = 0; pageNum < 16; pageNum++) {
// pages.add(getPumpHistoryPage(pageNum));
// }
//
// return pages;
// }
// public ArrayList<Page> getHistoryEventsSinceDate(Instant when) {
// ArrayList<Page> pages = new ArrayList<>();
// for (int pageNum = 0; pageNum < 16; pageNum++) {
// pages.add(getPumpHistoryPage(pageNum));
// for (Page page : pages) {
// for (Record r : page.mRecordList) {
// LocalDateTime timestamp = r.getTimestamp().getLocalDateTime();
// LOG.info("Found record: (" + r.getClass().getSimpleName() + ") " + timestamp.toString());
// }
// }
// }
// return pages;
// }
public String getErrorResponse() {
return this.errorMessage;
@ -784,6 +604,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
private Object sendAndGetResponseWithCheck(MedtronicCommandType commandType, byte[] bodyData) {
if (isLogEnabled())
LOG.debug("getDataFromPump: {}", commandType);
for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) {
@ -800,6 +621,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
Object dataResponse = medtronicConverter.convertResponse(commandType, response.getRawContent());
if (isLogEnabled())
LOG.debug("Converted response for {} is {}.", commandType.name(), dataResponse);
return dataResponse;
@ -809,6 +631,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1);
}
@ -822,6 +645,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (!response.isValid()) {
String responseData = String.format("%s: Invalid response.", method);
if (isLogEnabled())
LOG.warn(responseData);
return responseData;
}
@ -838,6 +662,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
"%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, ""
+ expectedLength, "" + contents.length);
if (isLogEnabled())
LOG.warn(responseData);
return responseData;
}
@ -863,10 +688,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.PumpModel);
// if (!MedtronicUtil.isModelSet()) {
// MedtronicUtil.setMedtronicPumpModel((MedtronicDeviceType)responseObject);
// }
return responseObject == null ? null : (MedtronicDeviceType)responseObject;
}
@ -879,6 +700,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
MedtronicCommandType commandType = MedtronicCommandType.GetBasalProfileSTD;
if (isLogEnabled())
LOG.debug("getDataFromPump: {}", commandType);
MedtronicUtil.setCurrentCommand(commandType);
@ -899,8 +721,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
response = sendAndListen(msg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries));
LOG.debug("1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent()));
LOG.debug("1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData()));
// LOG.debug("1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent()));
// LOG.debug("1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData()));
String check = checkResponseContent(response, commandType.commandDescription, 1);
@ -920,9 +742,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage response2 = sendAndListen(ackMsg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries));
LOG.debug("{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent()));
LOG.debug("{} Response: {}", runs,
HexDump.toHexStringDisplayable(response2.getMessageBody().getTxData()));
// LOG.debug("{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent()));
// LOG.debug("{} Response: {}", runs,
// HexDump.toHexStringDisplayable(response2.getMessageBody().getTxData()));
String check2 = checkResponseContent(response2, commandType.commandDescription, 1);
@ -932,6 +754,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} else {
this.errorMessage = check2;
if (isLogEnabled())
LOG.debug("Error message: " + check2);
}
}
@ -942,6 +765,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
BasalProfile basalProfile = (BasalProfile)medtronicConverter.convertResponse(commandType, data);
if (isLogEnabled())
LOG.debug("Converted response for {} is {}.", commandType.name(), basalProfile);
MedtronicUtil.setCurrentCommand(null);
@ -950,10 +774,12 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
return basalProfile;
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1);
}
}
if (isLogEnabled())
LOG.warn("Error reading profile in max retries.");
MedtronicUtil.setCurrentCommand(null);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
@ -972,6 +798,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
int last = responseRaw.length - 1;
if (isLogEnabled())
LOG.debug("Length: " + data.length);
if (data.length >= BasalProfile.MAX_RAW_DATA_SIZE) {
@ -1024,6 +851,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public Boolean setBolus(double units) {
if (isLogEnabled())
LOG.info("setBolus: " + units);
return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getBolusStrokes(units));
@ -1033,6 +861,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public boolean setTBR(TempBasalPair tbr) {
if (isLogEnabled())
LOG.info("setTBR: " + tbr.getDescription());
return setCommand(MedtronicCommandType.SetTemporaryBasal, tbr.getAsRawData());
@ -1058,9 +887,14 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (debugSetCommands)
LOG.debug("{}: {}", commandType.getCommandDescription(), pumpMessage.getResponseContent());
return pumpMessage.commandType == MedtronicCommandType.CommandACK;
if (pumpMessage.commandType == MedtronicCommandType.CommandACK) {
return true;
} else {
LOG.warn("We received non-ACK response from pump: {}" , pumpMessage.getResponseContent());
}
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1);
}
}
@ -1095,6 +929,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
return responseMessage.commandType == MedtronicCommandType.CommandACK;
} catch (RileyLinkCommunicationException e) {
if (isLogEnabled())
LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1);
}
@ -1107,54 +942,16 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
}
// FIXME --- After this line commands in development --- REMOVE THIS COMMANDS
// TODO test
// TODO remove, we will see state from History
// public PumpMessage getPumpState() {
// PumpMessage response = sendAndGetResponse(MedtronicCommandType.PumpState);
//
// byte[] data = response.getRawContent();
//
// LOG.debug("Pump State: {}", HexDump.toHexStringDisplayable(data));
//
// // 3 TBR running ?
//
// return null;
// }
// TODO remove, we will see bolus status from History
// public PumpMessage getBolusStatus() {
// PumpMessage response = sendAndGetResponse(MedtronicCommandType.SetBolus, new byte[] { 0x03, 0x00, 0x00, 0x00 },
// 4000);
//
// byte[] data = response.getRawContent();
//
// LOG.debug("Detect bolus: {}", HexDump.toHexStringDisplayable(data));
//
// // 3 TBR running ?
//
// return null;
// }
public PumpMessage cancelBolus() {
// ? maybe suspend and resume
return null;
}
// Set TBR 100%
// Cancel TBR (set TBR 100%) 100%
// Get Status (40%)
// Set Bolus 100%
// Set Extended Bolus 20%
// Cancel Bolus 0% -- NOT SUPPORTED
// Cancel Extended Bolus 0% -- NOT SUPPORTED
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
// Get Basal Profile (0x92) Read STD 100%
// Set Basal Profile 0% -- NOT SUPPORTED
// Read History 60%
// Load TDD ?
}

View file

@ -9,6 +9,7 @@ import org.joda.time.LocalTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.HexDump;
import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil;
@ -27,7 +28,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
public class MedtronicConverter {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicConverter.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
MedtronicDeviceType pumpModel;
@ -35,11 +36,12 @@ public class MedtronicConverter {
public Object convertResponse(MedtronicCommandType commandType, byte[] rawContent) {
if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) {
LOG.warn("Content is empty or too shor, no data to convert (type={},isNull={},length={})",
LOG.warn("Content is empty or too short, no data to convert (type={},isNull={},length={})",
commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length);
return null;
}
if (isLogEnabled())
LOG.debug("Raw response before convert: " + HexDump.toHexStringDisplayable(rawContent));
this.pumpModel = MedtronicUtil.getMedtronicPumpModel();
@ -102,6 +104,7 @@ public class MedtronicConverter {
String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3));
MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel);
if (isLogEnabled())
LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name());
if (pumpModel != MedtronicDeviceType.Unknown_Device) {
@ -192,7 +195,9 @@ public class MedtronicConverter {
protected Float decodeRemainingInsulin(byte[] rawData) {
int startIdx = 0;
int strokes = pumpModel.getBolusStrokes();
this.pumpModel = MedtronicUtil.getMedtronicPumpModel();
int strokes = pumpModel==null ? 10 : pumpModel.getBolusStrokes();
if (strokes == 40) {
startIdx = 2;
@ -200,6 +205,7 @@ public class MedtronicConverter {
float value = ByteUtil.toInt(rawData[startIdx], rawData[startIdx + 1]) / (1.0f * strokes);
if (isLogEnabled())
LOG.debug("Remaining insulin: " + value);
return value;
}
@ -229,7 +235,6 @@ public class MedtronicConverter {
public Map<String, PumpSettingDTO> decodeSettings512(byte[] rd) {
Map<String, PumpSettingDTO> map = new HashMap<>();
// List<PumpSettingDTO> outList = new ArrayList<>();
addSettingToMap("PCFG_AUTOOFF_TIMEOUT", "" + rd[0], PumpConfigurationGroup.General, map);
@ -260,11 +265,11 @@ public class MedtronicConverter {
if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)) {
addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + (rd[9] == 0 ? 50 : 100), PumpConfigurationGroup.Insulin,
map);
LOG.debug("Insulin concentration: " + rd[9]);
// LOG.debug("Insulin concentration: " + rd[9]);
} else {
addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + (rd[9] != 0 ? 50 : 100), PumpConfigurationGroup.Insulin,
map);
LOG.debug("Insulin concentration: " + rd[9]);
// LOG.debug("Insulin concentration: " + rd[9]);
}
addSettingToMap("PCFG_BASAL_PROFILES_ENABLED", parseResultEnable(rd[10]), PumpConfigurationGroup.Basal, map);
@ -409,4 +414,9 @@ public class MedtronicConverter {
return (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher));
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -9,6 +9,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType;
@ -36,7 +37,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
*/
public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> implements MedtronicHistoryDecoderInterface<T> {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicHistoryDecoder.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
protected ByteUtil bitUtils;
@ -58,35 +59,6 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
public abstract void postProcess();
// public abstract void refreshOutputWriter();
// public List<? extends MedtronicHistoryEntry> decodePage(RawHistoryPage dataPage) throws Exception {
// // refreshOutputWriter();
//
// List<? extends MedtronicHistoryEntry> minimedHistoryRecords = processPageAndCreateRecords(dataPage);
//
// for (MedtronicHistoryEntry record : minimedHistoryRecords) {
// decodeRecord(record);
// }
//
// runPostDecodeTasks();
//
// return minimedHistoryRecords;
// }
// public List<? extends MedtronicHistoryEntry> decodePartialPage(RawHistoryPage dataPage) throws Exception {
// // refreshOutputWriter();
//
// List<? extends MedtronicHistoryEntry> minimedHistoryRecords = processPageAndCreateRecords(dataPage, true);
//
// for (MedtronicHistoryEntry record : minimedHistoryRecords) {
// decodeRecord(record);
// }
//
// runPostDecodeTasks();
//
// return minimedHistoryRecords;
// }
protected abstract void runPostDecodeTasks();
@ -118,9 +90,6 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
}
// public abstract List<? extends MedtronicHistoryEntry> processPageAndCreateRecords(RawHistoryPage page,
// boolean partial) throws Exception;
public List<T> processPageAndCreateRecords(RawHistoryPage rawHistoryPage) {
return processPageAndCreateRecords(rawHistoryPage, false);
}
@ -164,10 +133,11 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
StringUtil.appendToStringBuilder(sb, "" + unknownEntry.getKey(), ", ");
}
if (isLogEnabled())
LOG.debug("STATISTICS OF PUMP DECODE");
if (unknownOpCodes.size() > 0) {
LOG.debug("Unknown Op Codes: {}", sb.toString());
LOG.warn("Unknown Op Codes: {}", sb.toString());
}
for (Map.Entry<RecordDecodeStatus, Map<String, String>> entry : mapStatistics.entrySet()) {
@ -183,9 +153,11 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
String spaces = StringUtils.repeat(" ", 14 - entry.getKey().name().length());
if (isLogEnabled())
LOG.debug(" {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(),
sb.toString());
} else {
if (isLogEnabled())
LOG.debug(" {} - {}", entry.getKey().name(), entry.getValue().size());
}
}
@ -213,14 +185,6 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
}
// public List<T> processPageAndCreateRecords(RawHistoryPage rawHistoryPage) {
// return processPageAndCreateRecords(rawHistoryPage, false, getHistoryEntryClass());
// }
// public List<T> processPageAndCreateRecords(RawHistoryPage rawHistoryPage, boolean partial) {
// return processPageAndCreateRecords(rawHistoryPage, partial, getHistoryEntryClass());
// }
private List<T> processPageAndCreateRecords(RawHistoryPage rawHistoryPage, boolean partial) {
List<Byte> dataClear = checkPage(rawHistoryPage, partial);
List<T> records = createRecords(dataClear);
@ -234,6 +198,8 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
return records;
}
// public abstract List<T> createRecords(List<Byte> dataClear);
protected boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -148,6 +148,16 @@ public abstract class MedtronicHistoryEntry implements MedtronicHistoryEntryInte
}
public Object getDecodedDataEntry(String key) {
return this.decodedData.get(key);
}
public boolean hasDecodedDataEntry(String key) {
return this.decodedData.containsKey(key);
}
public boolean showRaw() {
return getEntryTypeName().equals("EndResultTotals");
}
@ -283,16 +293,6 @@ public abstract class MedtronicHistoryEntry implements MedtronicHistoryEntryInte
}
// public LocalDateTime getLocalDateTime() {
// return this.dateTime;
// }
//
//
// public void setLocalDateTime(LocalDateTime atdate) {
// this.dateTime = atdate;
// // this.DT = atdate.toString(dateTimeFormatter);
// }
public void setAtechDateTime(long dt) {
this.atechDateTime = dt;
this.DT = DateTimeUtil.toString(this.atechDateTime);
@ -315,6 +315,13 @@ public abstract class MedtronicHistoryEntry implements MedtronicHistoryEntryInte
}
}
public boolean containsDecodedData(String key) {
if (decodedData == null)
return false;
return decodedData.containsKey(key);
}
// if we extend to CGMS this need to be changed back
// public abstract PumpHistoryEntryType getEntryType();

View file

@ -5,6 +5,7 @@ import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.CRC;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
@ -14,7 +15,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
*/
public class RawHistoryPage {
private static final Logger LOG = LoggerFactory.getLogger(RawHistoryPage.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPBTCOMM);
private byte[] data = new byte[0];

View file

@ -8,6 +8,7 @@ import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryDecoder;
@ -21,7 +22,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDeco
public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHistoryEntry> {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicCGMSHistoryDecoder.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
// CGMSValuesWriter cgmsValuesWriter = null;
@ -120,20 +121,12 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
public List<CGMSHistoryEntry> createRecords(List<Byte> dataClearInput) {
// List<MinimedHistoryEntry> listRecords = new
// ArrayList<MinimedHistoryEntry>();
LOG.debug("createRecords not implemented... WIP");
// return listRecords;
List<Byte> dataClear = reverseList(dataClearInput, Byte.class);
System.out.println("Reversed:" + ByteUtil.getHex(ByteUtil.getByteArrayFromList(dataClear)));
prepareStatistics();
int counter = 0;
// int record = 0;
List<CGMSHistoryEntry> outList = new ArrayList<CGMSHistoryEntry>();
@ -215,6 +208,7 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
entry.setDateTime(dateTime, getIndex);
}
if (isLogEnabled())
LOG.debug("Record: {}", entry);
}
@ -236,35 +230,21 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
private int parseMinutes(int one) {
// minute = (one & 0b111111 )
// return minute
// int yourInteger = Integer.parseInt("100100101", 2);
return (one & Integer.parseInt("0111111", 2));
}
private int parseHours(int one) {
// def parse_hours (one):
// return (one & 0x1F )
return (one & 0x1F);
}
private int parseDay(int one) {
// def parse_day (one):
// return one & 0x1F
return one & 0x1F;
}
private int parseMonths(int first_byte, int second_byte) {
// def parse_months (first_byte, second_byte):
// first_two_bits = first_byte >> 6
// second_two_bits = second_byte >> 6
// return (first_two_bits << 2) + second_two_bits
int first_two_bits = first_byte >> 6;
int second_two_bits = second_byte >> 6;
@ -274,67 +254,22 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
private int parseYear(int year) {
// def parse_years_lax(year):
// """
// simple mask plus correction
// """
// y = (year & Mask.year) + 2000
// return y
return (year & 0x0F) + 2000;
}
private Long parseDate(CGMSHistoryEntry entry) {
// System.out.println("parseDate [entryType=" + entry.getEntryType() + ",hasDate="
// + entry.getEntryType().hasDate() + "]");
if (!entry.getEntryType().hasDate())
return null;
byte data[] = entry.getDatetime();
// System.out.println("parseDate: " + data);
// def parse_date (data, unmask=False, strict=False,
// minute_specific=False):
// """
// Some dates are formatted/stored down to the second (Sensor
// CalBGForPH) while
// others are stored down to the minute (CGM SensorTimestamp dates).
// """
// data = data[:]
// seconds = 0
// minutes = 0
// hours = 0
//
// year = times.parse_years(data[0])
// day = parse_day(data[1])
// minutes = parse_minutes(data[2])
//
// hours = parse_hours(data[3])2015parse
//
// month = parse_months(data[3], data[2])
// 2015-04-11T14:02:00
// date is reversed
if (entry.getEntryType().getDateType() == CGMSHistoryEntryType.DateType.MinuteSpecific) {
// LocalDateTime date = new LocalDateTime(parseDay(data[2]), parseMonths(data[0], data[1]),
// parseHours(data[0]), parseMinutes(data[1]), 0);
// ATechDate date = new ATechDate(parseDay(data[0]),
// parseMonths(data[2], data[1]), parseYear(data[2]),
// parseHours(data[2]), parseMinutes(data[1]), 0,
// ATechDateType.DateAndTimeSec);
Long atechDateTime = DateTimeUtil.toATechDate(parseYear(data[3]), parseMonths(data[0], data[1]),
parseDay(data[2]), parseHours(data[0]), parseMinutes(data[1]), 0);
// System.out.println("atechDateTime: " + atechDateTime);
entry.setAtechDateTime(atechDateTime);
return atechDateTime;

View file

@ -7,6 +7,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.HexDump;
@ -29,13 +30,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHistoryEntry> {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicPumpHistoryDecoder.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
// PumpValuesWriter pumpValuesWriter = null;
// DataAccessPlugInBase dataAccess = DataAccessPump.getInstance();
// Map<String, BolusDTO> bolusHistory = new HashMap<>();
// Temporary records for processing
private PumpHistoryEntry tbrPreviousRecord;
private PumpHistoryEntry changeTimeRecord;
private MedtronicDeviceType deviceType;
@ -133,20 +129,8 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
if (entryType == PumpHistoryEntryType.None) {
LOG.error("Error in code. We should have not come into this branch.");
// System.out.println("!!! Unknown Entry: 0x" +
// bitUtils.getCorrectHexValue(opCode) + "[" + opCode + "]");
//
// addToStatistics(null, null, opCode);
// counter += 6; // we assume this is unknown packet with size
// // 2,5,0 (standard packet)
//
// pe.setEntryType(PumpHistoryEntryType.UnknownBasePacket);
// pe.setOpCode(opCode);
} else {
// System.out.println(pe.getEntryType());
if (pe.getEntryType() == PumpHistoryEntryType.UnknownBasePacket) {
pe.setOpCode(opCode);
}
@ -246,7 +230,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
case ChangeWatchdogEnable:
case ChangeOtherDeviceID:
case ReadOtherDevicesIDs:
case BolusWizard512:
case BolusWizardEstimate512:
case BGReceived512:
case SensorStatus:
case ReadCaptureEventEnabled:
@ -254,9 +238,6 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
case ReadOtherDevicesStatus:
return RecordDecodeStatus.OK;
// case ChangeWatchdogMarriageProfile:
// case DeleteOtherDeviceID:
// case ChangeCaptureEventEnable:
case Sensor54:
case Sensor55:
case Sensor51:
@ -281,7 +262,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
case EventUnknown_0x4d:
case EventUnknown_MM522_0x25:
case EventUnknown_MM522_0x05:
LOG.debug(" -- ignored Pump Entry: " + entry);
LOG.debug(" -- ignored Unknown Pump Entry: " + entry);
return RecordDecodeStatus.Ignored;
case UnabsorbedInsulin:
@ -342,7 +323,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
case SaveSettings:
return RecordDecodeStatus.OK;
case BolusWizardBolusEstimate:
case BolusWizardEstimate:
decodeBolusWizard(entry);
return RecordDecodeStatus.OK;
@ -374,9 +355,6 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
entry.addDecodedData("Raw Data", ByteUtil.getHex(entry.getRawData()));
//LOG.debug("{} - {}", entry.getEntryType().name(), ByteUtil.getHex(entry.getRawData()));
//LOG.debug("{}", entry);
DailyTotalsDTO totals = new DailyTotalsDTO(entry);
entry.addDecodedData("Object", totals);
@ -396,8 +374,6 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
entry.addDecodedData("Object", basalProfile);
// FIXME displayable ??
return RecordDecodeStatus.OK;
}
@ -492,24 +468,16 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
dto.atechDateTime = entry.atechDateTime;
entry.addDecodedData("Object", dto);
entry.setDisplayableValue(dto.toString());
entry.setDisplayableValue(dto.getDisplayableValue());
// this.writeData(PumpBaseType.Event, PumpEventType.BolusWizard, dto.getValue(), entry.getATechDate());
}
// FIXME
private void decodeLowReservoir(PumpHistoryEntry entry) {
float amount = (getUnsignedInt(entry.getHead()[0]) * 1.0f / 10.0f) * 2;
// LOG.debug("LowReservoir: rawData={}", entry.getRawData());
// LOG.debug("LowReservoir: {}, object={}", entry.getHead()[0], entry);
// this.writeData(PumpBaseType.Event, PumpEventType.ReservoirLowDesc, getFormattedFloat(amount, 1),
// entry.getATechDate());
entry.setDisplayableValue(getFormattedValue(amount, 1));
}
@ -523,22 +491,11 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
entry.setDisplayableValue("Amount=" + getFormattedValue(amount, 2) + ", Fixed Amount="
+ getFormattedValue(fixed, 2));
// amount = (double) (asUINT8(data[4]) << 2) / 40.0;
// programmedAmount = (double) (asUINT8(data[2]) << 2) / 40.0;
// primeType = programmedAmount == 0 ? "manual" : "fixed";
// return true;
// this.writeData(PumpBaseType.Event, PumpEventType.PrimeInfusionSet, fixed > 0 ? getFormattedFloat(fixed, 1) :
// getFormattedFloat(amount, 1), entry.getATechDate());
}
@Override
public void postProcess() {
// if (bolusEntry != null) {
// writeBolus(pumpHistoryEntry4BolusEntry, bolusEntry);
// }
}
@ -569,25 +526,9 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
: PumpBolusType.Normal);
bolus.setAtechDateTime(entry.atechDateTime);
// String dateTime = entry.DT;
// if (bolus.getBolusType() == PumpBolusType.Extended) {
// // we check if we have coresponding normal entry
// if (bolusHistory.containsKey(dateTime)) {
// BolusDTO bolusDTO = bolusHistory.get(dateTime);
//
// bolusDTO.setImmediateAmount(bolus.getDeliveredAmount());
// bolusDTO.setBolusType(PumpBolusType.Multiwave);
//
// return;
// }
// }
entry.addDecodedData("Object", bolus);
entry.setDisplayableValue(bolus.getDisplayableValue());
// bolusHistory.put(dateTime, bolus);
}
@ -670,17 +611,10 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
int minutes = 0;
int seconds = 0;
// LocalDate rval = new LocalDate(year, month, dayOfMonth);
// int dayOfMonth = dt[0] & 0x1F;
// int month = (((dt[0] & 0xE0) >> 4) + ((dt[1] & 0x80) >> 7));
// int year = fix2DigitYear(dt[1] & 0x3F);
LOG.debug("DT: {} {} {}", year, month, dayOfMonth);
//LOG.debug("DT: {} {} {}", year, month, dayOfMonth);
if (dayOfMonth == 32) {
// FIXME remove
LOG.debug("Entry: Day 32 {} = [{}] {}", entry.getEntryType().name(),
LOG.warn("Entry: Day 32 {} = [{}] {}", entry.getEntryType().name(),
ByteUtil.getHex(entry.getRawData()), entry);
}

View file

@ -60,7 +60,7 @@ public enum PumpHistoryEntryType // implements CodeEnum
ChangeMaxBasal(0x2c, "Change Max Basal", PumpHistoryEntryGroup.Configuration), //
BolusWizardEnabled(0x2d, "Bolus Wizard Enabled", PumpHistoryEntryGroup.Configuration), // V3 ?
/**/EventUnknown_MM512_0x2e(0x2e, "Unknown Event 0x2e", PumpHistoryEntryGroup.Unknown), //
/**/BolusWizard512(0x2f, "Bolus Wizard (512)", PumpHistoryEntryGroup.Configuration), //
/**/BolusWizardEstimate512(0x2f, "Bolus Wizard Estimate (512)", PumpHistoryEntryGroup.Configuration), //
UnabsorbedInsulin512(0x30, "Unabsorbed Insulin (512)", PumpHistoryEntryGroup.Statistic), //
ChangeBGReminderOffset(0x31, "Change BG Reminder Offset", PumpHistoryEntryGroup.Configuration), //
ChangeAlarmClockTime(0x32, "Change Alarm Clock Time", PumpHistoryEntryGroup.Configuration), //
@ -108,7 +108,7 @@ public enum PumpHistoryEntryType // implements CodeEnum
// Andy58(0x58, "Unknown", 13, 5, 0), // TO DO is this one really there ???
BolusWizardChange(0x5a, "Bolus Wizard Change", PumpHistoryEntryGroup.Configuration, 2, 5, 117), // V2: 522+[B=143] // V6 124/144
BolusWizardBolusEstimate(0x5b, "Bolus Wizard Estimate", PumpHistoryEntryGroup.Configuration, 2, 5, 13), // 15 //
BolusWizardEstimate(0x5b, "Bolus Wizard Estimate", PumpHistoryEntryGroup.Configuration, 2, 5, 13), // 15 //
UnabsorbedInsulin(0x5c, "Unabsorbed Insulin", PumpHistoryEntryGroup.Statistic, 5, 0, 0), // head[1] -> body
// length
SaveSettings(0x5d, "Save Settings", PumpHistoryEntryGroup.Configuration), //
@ -225,7 +225,7 @@ public enum PumpHistoryEntryType // implements CodeEnum
// has
// old
// form
BolusWizardBolusEstimate.addSpecialRuleBody(new SpecialRule(MedtronicDeviceType.Medtronic_523andHigher, 15));
BolusWizardEstimate.addSpecialRuleBody(new SpecialRule(MedtronicDeviceType.Medtronic_523andHigher, 15));
BolusReminder.addSpecialRuleBody(new SpecialRule(MedtronicDeviceType.Medtronic_523andHigher, 2));
}

View file

@ -7,8 +7,8 @@ import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
/**
* Created by andy on 9/23/18.
@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
*/
public class PumpHistoryResult {
private static final Logger LOG = LoggerFactory.getLogger(PumpHistoryResult.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
private boolean searchFinished = false;
private PumpHistoryEntry searchEntry = null;
@ -41,10 +41,12 @@ public class PumpHistoryResult {
*/
this.searchDate = searchEntry.atechDateTime;
this.searchType = SearchType.Date;
if (isLogEnabled())
LOG.debug("PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate);
} else if (targetDate != null) {
this.searchDate = targetDate;
this.searchType = SearchType.Date;
if (isLogEnabled())
LOG.debug("PumpHistoryResult. Search parameters: Date: " + targetDate);
}
@ -55,7 +57,7 @@ public class PumpHistoryResult {
public void addHistoryEntries(List<PumpHistoryEntry> entries) {
this.unprocessedEntries = entries;
LOG.debug("PumpHistoryResult. Unprocessed entries: {}", MedtronicPumpPlugin.gsonInstance.toJson(entries));
//LOG.debug("PumpHistoryResult. Unprocessed entries: {}", MedtronicUtil.getGsonInstance().toJson(entries));
processEntries();
}
@ -65,41 +67,34 @@ public class PumpHistoryResult {
switch (searchType) {
case None:
LOG.debug("PE. None search");
// clearOrPrepareList();
//LOG.debug("PE. None search");
this.validEntries.addAll(this.unprocessedEntries);
// this.unprocessedEntries
// = null;
break;
case LastEntry: {
LOG.debug("PE. Last entry search");
// clearOrPrepareList();
//LOG.debug("PE. Last entry search");
Collections.sort(this.unprocessedEntries, new PumpHistoryEntry.Comparator());
LOG.debug("PE. PumpHistoryResult. Search entry date: " + searchEntry.atechDateTime);
//LOG.debug("PE. PumpHistoryResult. Search entry date: " + searchEntry.atechDateTime);
Long date = searchEntry.atechDateTime;
for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) {
if (unprocessedEntry.equals(searchEntry)) {
LOG.debug("PE. Item found {}.", unprocessedEntry);
//LOG.debug("PE. Item found {}.", unprocessedEntry);
searchFinished = true;
break;
}
LOG.debug("PE. Entry {} added.", unprocessedEntry);
//LOG.debug("PE. Entry {} added.", unprocessedEntry);
this.validEntries.add(unprocessedEntry);
}
}
break;
case Date: {
LOG.debug("PE. Date search");
// clearOrPrepareList();
//LOG.debug("PE. Date search");
for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) {
@ -125,7 +120,7 @@ public class PumpHistoryResult {
} // switch
LOG.debug("PE. Valid Entries: {}", validEntries);
//LOG.debug("PE. Valid Entries: {}", validEntries);
}
@ -189,4 +184,10 @@ public class PumpHistoryResult {
Date
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -2,6 +2,10 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.message;
import android.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.HexDump;
@ -10,9 +14,10 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandTy
/**
* Created by geoff on 5/29/16.
*/
// FIXME: Andy Message body problem, see comment in MessageBody
public class PumpMessage implements RLMessage {
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
public PacketType packetType = PacketType.Carelink;
public byte[] address = new byte[] { 0, 0, 0 };
public MedtronicCommandType commandType;
@ -69,7 +74,8 @@ public class PumpMessage implements RLMessage {
if (rxData.length > 4) {
this.commandType = MedtronicCommandType.getByCode(rxData[4]);
if (this.commandType == MedtronicCommandType.InvalidCommand) {
Log.e("PumpMessage", "Unknown commandType " + rxData[4]);
if (isLogEnabled())
LOG.error("PumpMessage - Unknown commandType " + rxData[4]);
}
}
if (rxData.length > 5) {
@ -126,7 +132,8 @@ public class PumpMessage implements RLMessage {
System.arraycopy(messageBody.getTxData(), 1, arrayOut, 0, length);
Log.d("PumpMessage", "Length: " + length + ", Original Length: " + originalLength + ", CommandType: "
if (isLogEnabled())
LOG.debug("PumpMessage - Length: " + length + ", Original Length: " + originalLength + ", CommandType: "
+ commandType);
return arrayOut;
@ -206,4 +213,9 @@ public class PumpMessage implements RLMessage {
return sb.toString();
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager;
@ -15,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
public class MedtronicUIComm {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicUIComm.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
MedtronicCommunicationManager mcmInstance = null;
MedtronicUIPostprocessor uiPostprocessor = new MedtronicUIPostprocessor();
@ -32,6 +33,7 @@ public class MedtronicUIComm {
public synchronized MedtronicUITask executeCommand(MedtronicCommandType commandType, Object... parameters) {
if (isLogEnabled())
LOG.warn("Execute Command: " + commandType.name());
MedtronicUITask task = new MedtronicUITask(commandType, parameters);
@ -67,6 +69,7 @@ public class MedtronicUIComm {
// }
if (!task.isReceived()) {
if (isLogEnabled())
LOG.warn("Reply not received for " + commandType);
}
@ -101,4 +104,9 @@ public class MedtronicUIComm {
public void startTunning() {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump);
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMP);
}
}

View file

@ -10,6 +10,7 @@ import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BatteryStatusDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO;
@ -26,7 +27,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
public class MedtronicUIPostprocessor {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicUIPostprocessor.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
MedtronicPumpStatus pumpStatus;
@ -108,6 +109,7 @@ public class MedtronicUIPostprocessor {
case PumpModel: {
if (pumpStatus.medtronicDeviceType != MedtronicUtil.getMedtronicPumpModel()) {
if (isLogEnabled())
LOG.warn("Configured pump is different then pump detected !");
sendNotification(MedtronicNotificationType.PumpTypeNotSame);
}
@ -123,6 +125,7 @@ public class MedtronicUIPostprocessor {
// no postprocessing
default:
if (isLogEnabled())
LOG.trace("Post-processing not implemented for {}.", uiTask.commandType.name());
}
@ -141,14 +144,17 @@ public class MedtronicUIPostprocessor {
MedtronicUtil.setPumpTime(clockDTO);
if (isLogEnabled())
LOG.debug("Pump Time: " + clockDTO.localDeviceTime + ", DeviceTime=" + clockDTO.pumpTime + //
", diff: " + dur.getStandardSeconds() + " s");
if (dur.getStandardMinutes() >= 10) {
if (isLogEnabled())
LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: "
+ dur.getStandardSeconds() + " s)");
sendNotification(MedtronicNotificationType.PumpWrongTimeUrgent);
} else if (dur.getStandardMinutes() >= 4) {
if (isLogEnabled())
LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: "
+ dur.getStandardSeconds() + " s)");
sendNotification(MedtronicNotificationType.PumpWrongTimeNormal);
@ -166,8 +172,10 @@ public class MedtronicUIPostprocessor {
PumpSettingDTO checkValue = null;
if (pumpStatus == null) {
if (isLogEnabled())
LOG.debug("Pump Status: was null");
pumpStatus = MedtronicUtil.getPumpStatus();
if (isLogEnabled())
LOG.debug("Pump Status: " + this.pumpStatus);
}
@ -175,6 +183,7 @@ public class MedtronicUIPostprocessor {
// check profile
if (!"Yes".equals(settings.get("PCFG_BASAL_PROFILES_ENABLED").value)) {
if (isLogEnabled())
LOG.error("Basal profiles are not enabled on pump.");
sendNotification(MedtronicNotificationType.PumpBasalProfilesNotEnabled);
@ -182,6 +191,7 @@ public class MedtronicUIPostprocessor {
checkValue = settings.get("PCFG_ACTIVE_BASAL_PROFILE");
if (!"STD".equals(checkValue.value)) {
if (isLogEnabled())
LOG.error("Basal profile set on pump is incorrect (must be STD).");
sendNotification(MedtronicNotificationType.PumpIncorrectBasalProfileSelected);
}
@ -192,6 +202,7 @@ public class MedtronicUIPostprocessor {
checkValue = settings.get("PCFG_TEMP_BASAL_TYPE");
if (!"Units".equals(checkValue.value)) {
if (isLogEnabled())
LOG.error("Wrong TBR type set on pump (must be Absolute).");
sendNotification(MedtronicNotificationType.PumpWrongTBRTypeSet);
}
@ -208,10 +219,15 @@ public class MedtronicUIPostprocessor {
checkValue = settings.get("PCFG_MAX_BASAL");
if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), pumpStatus.maxBasal)) {
if (isLogEnabled())
LOG.error("Wrong Max Basal set on Pump (current={}, required={}).", checkValue.value, pumpStatus.maxBasal);
sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, pumpStatus.maxBasal);
}
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMP);
}
}

View file

@ -5,6 +5,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile;
@ -20,10 +21,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
* Created by andy on 6/14/18.
*/
// FIXME we could refactor this and create sperate class for each command, perhaps
public class MedtronicUITask {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicUITask.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
public MedtronicCommandType commandType;
public Object returnData;
@ -47,6 +47,7 @@ public class MedtronicUITask {
public void execute(MedtronicCommunicationManager communicationManager) {
if (isLogEnabled())
LOG.warn("@@@ In execute. {}", commandType);
switch (commandType) {
@ -134,6 +135,7 @@ public class MedtronicUITask {
break;
default: {
if (isLogEnabled())
LOG.warn("This commandType is not supported (yet) - {}.", commandType);
// invalid = true;
responseType = MedtronicUIResponseType.Invalid;
@ -190,6 +192,7 @@ public class MedtronicUITask {
public void postProcess(MedtronicUIPostprocessor postprocessor) {
EventMedtronicDeviceStatusChange statusChange;
if (isLogEnabled())
LOG.warn("@@@ In execute. {}", commandType);
if (responseType == MedtronicUIResponseType.Data) {
@ -222,4 +225,10 @@ public class MedtronicUITask {
public Object getParameter(int index) {
return parameters[index];
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMP);
}
}

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data;
import com.google.android.gms.common.util.CollectionUtils;
import com.google.common.base.Splitter;
import com.google.gson.Gson;
@ -12,7 +11,6 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
@ -36,6 +34,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpH
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryResult;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusWizardDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.DailyTotalsDTO;
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair;
@ -54,7 +53,7 @@ import info.nightscout.androidaps.utils.SP;
public class MedtronicHistoryData {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicHistoryData.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
private List<PumpHistoryEntry> allHistory = null;
private List<PumpHistoryEntry> newHistory = null;
@ -70,7 +69,7 @@ public class MedtronicHistoryData {
public MedtronicHistoryData() {
this.allHistory = new ArrayList<>();
this.gsonPretty = MedtronicPumpPlugin.gsonInstancePretty;
this.gsonPretty = MedtronicUtil.gsonInstance;
}
@ -101,10 +100,12 @@ public class MedtronicHistoryData {
public static void showLogs(String header, String data) {
if (header != null) {
if (isLogEnabled())
LOG.debug(header);
}
for (final String token : Splitter.fixedLength(3500).split(data)) {
if (isLogEnabled())
LOG.debug("{}", token);
}
}
@ -119,6 +120,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> newHistory2 = new ArrayList<>();
List<PumpHistoryEntry> TBRs = new ArrayList<>();
List<PumpHistoryEntry> bolusEstimates = new ArrayList<>();
long atechDate = DateTimeUtil.toATechDate(new GregorianCalendar());
for (PumpHistoryEntry pumpHistoryEntry : newHistory) {
@ -129,6 +131,9 @@ public class MedtronicHistoryData {
if (type == PumpHistoryEntryType.TempBasalRate || type == PumpHistoryEntryType.TempBasalDuration) {
TBRs.add(pumpHistoryEntry);
} else if (type == PumpHistoryEntryType.BolusWizardEstimate) {
bolusEstimates.add(pumpHistoryEntry);
newHistory2.add(pumpHistoryEntry);
} else {
if (type == PumpHistoryEntryType.EndResultTotals) {
@ -144,17 +149,35 @@ public class MedtronicHistoryData {
TBRs = preProcessTBRs(TBRs);
if (bolusEstimates.size() > 0) {
extendBolusRecords(bolusEstimates, newHistory2);
}
newHistory2.addAll(TBRs);
this.newHistory = newHistory2;
sort(this.newHistory);
if (isLogEnabled())
LOG.debug("New History entries found: {}", this.newHistory.size());
showLogs("List of history (after filtering): ", MedtronicPumpPlugin.gsonInstance.toJson(this.newHistory));
}
private void extendBolusRecords(List<PumpHistoryEntry> bolusEstimates, List<PumpHistoryEntry> newHistory2) {
List<PumpHistoryEntry> boluses = getFilteredItems(newHistory2, PumpHistoryEntryType.Bolus);
for (PumpHistoryEntry bolusEstimate : bolusEstimates) {
for (PumpHistoryEntry bolus : boluses) {
if (bolusEstimate.atechDateTime.equals(bolus.atechDateTime)) {
bolus.addDecodedData("Estimate", bolusEstimate.getDecodedData().get("Object"));
}
}
}
}
public void finalizeNewHistoryRecords() {
@ -349,16 +372,16 @@ public class MedtronicHistoryData {
// TBR
List<PumpHistoryEntry> tbrs = getFilteredItems(PumpHistoryEntryType.TempBasalCombined);
LOG.debug("ProcessHistoryData: TBRs [count={}, items={}]", tbrs.size(), gsonPretty.toJson(tbrs));
LOG.debug("ProcessHistoryData: TBRs NOT Processed [count={}, items={}]", tbrs.size(), gsonPretty.toJson(tbrs));
if (tbrs.size() > 0) {
processEntries(tbrs, ProcessHistoryRecord.TBR);
//processEntries(tbrs, ProcessHistoryRecord.TBR);
}
// Suspends (for suspends/resume, fakeTBR)
List<PumpHistoryEntry> suspends = getSuspends();
LOG.debug("ProcessHistoryData: FakeTBRs (suspend/resume) [count={}, items={}]", suspends.size(),
LOG.debug("ProcessHistoryData: FakeTBRs (suspend/resume) NOT Processed [count={}, items={}]", suspends.size(),
gsonPretty.toJson(suspends));
if (suspends.size() > 0) {
@ -389,6 +412,7 @@ public class MedtronicHistoryData {
TDD tddNew = new TDD();
totalsDTO.setTDD(tddNew);
if (isLogEnabled())
LOG.debug("TDD Add: {}", tddNew);
databaseHelper.createOrUpdateTDD(tddNew);
@ -398,6 +422,7 @@ public class MedtronicHistoryData {
if (!totalsDTO.doesEqual(tddDbEntry)) {
totalsDTO.setTDD(tddDbEntry);
if (isLogEnabled())
LOG.debug("TDD Edit: {}", tddDbEntry);
databaseHelper.createOrUpdateTDD(tddDbEntry);
@ -431,25 +456,83 @@ public class MedtronicHistoryData {
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntries(dateDifference, processHistoryRecord);
LOG.debug(processHistoryRecord.getDescription() + " List (before filter): {}, FromDb={}", gsonPretty.toJson(entryList),
gsonPretty.toJson(entriesFromHistory));
// LOG.debug(processHistoryRecord.getDescription() + " List (before filter): {}, FromDb={}", gsonPretty.toJson(entryList),
// gsonPretty.toJson(entriesFromHistory));
filterOutAlreadyAddedEntries(entryList, entriesFromHistory);
if (entryList.isEmpty())
return;
LOG.debug(processHistoryRecord.getDescription() + " List (after filter): {}, FromDb={}", gsonPretty.toJson(entryList),
gsonPretty.toJson(entriesFromHistory));
// LOG.debug(processHistoryRecord.getDescription() + " List (after filter): {}, FromDb={}", gsonPretty.toJson(entryList),
// gsonPretty.toJson(entriesFromHistory));
if (isCollectionEmpty(entriesFromHistory)) {
for (PumpHistoryEntry treatment : entryList) {
if (isLogEnabled())
LOG.debug("Add " + processHistoryRecord.getDescription() + " (no db entries): " + treatment);
addEntry(treatment, null, processHistoryRecord);
}
} else {
for (PumpHistoryEntry treatment : entryList) {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
if (isLogEnabled())
LOG.debug("Add " + processHistoryRecord.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb);
addEntry(treatment, treatmentDb, processHistoryRecord);
}
}
}
private void processTBREntries(List<PumpHistoryEntry> entryList, ProcessHistoryRecord processHistoryRecord) {
int dateDifference = getOldestDateDifference(entryList);
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntries(dateDifference, processHistoryRecord);
// LOG.debug(processHistoryRecord.getDescription() + " List (before filter): {}, FromDb={}", gsonPretty.toJson(entryList),
// gsonPretty.toJson(entriesFromHistory));
Collections.reverse(entryList);
filterOutAlreadyAddedEntries(entryList, entriesFromHistory);
if (entryList.isEmpty())
return;
// LOG.debug(processHistoryRecord.getDescription() + " List (after filter): {}, FromDb={}", gsonPretty.toJson(entryList),
// gsonPretty.toJson(entriesFromHistory));
PumpHistoryEntry startRecord = null;
for (PumpHistoryEntry treatment : entryList) {
TempBasalPair tbr = (TempBasalPair) treatment.getDecodedDataEntry("Object");
boolean isPossibleCancel = false;
if (tbr.getInsulinRate() > 0.0d) {
startRecord = treatment;
} else {
isPossibleCancel = true;
if (startRecord == null) {
}
}
if (isLogEnabled())
LOG.debug("Add " + processHistoryRecord.getDescription() + " (no db entries): " + treatment);
addEntry(treatment, null, processHistoryRecord);
}
if (isCollectionEmpty(entriesFromHistory)) {
} else {
for (PumpHistoryEntry treatment : entryList) {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
if (isLogEnabled())
LOG.debug("Add " + processHistoryRecord.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb);
addEntry(treatment, treatmentDb, processHistoryRecord);
@ -486,14 +569,15 @@ public class MedtronicHistoryData {
}
}
LOG.error("Entries: (timeDiff=[min={},sec={}],count={},list={})", min, sec, outList.size(),
gsonPretty.toJson(outList));
// LOG.debug("Entries: (timeDiff=[min={},sec={}],count={},list={})", min, sec, outList.size(),
// gsonPretty.toJson(outList));
if (outList.size() == 1) {
return outList.get(0);
}
if (min == 0 && sec == 10 && outList.size() > 1) {
if (isLogEnabled())
LOG.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
min, sec, outList.size(), gsonPretty.toJson(outList));
}
@ -570,8 +654,6 @@ public class MedtronicHistoryData {
if (treatment == null) {
// treatment.carbs = detailedBolusInfo.carbs; // TODO later support BolusWizard ??
switch (bolusDTO.getBolusType()) {
case Normal: {
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
@ -581,11 +663,13 @@ public class MedtronicHistoryData {
detailedBolusInfo.pumpId = bolus.getPumpId();
detailedBolusInfo.insulin = bolusDTO.getDeliveredAmount();
addCarbsFromEstimate(detailedBolusInfo, bolus);
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
bolus.setLinkedObject(detailedBolusInfo);
if (L.isEnabled(L.PUMPCOMM))
if (isLogEnabled())
LOG.debug("addBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
}
@ -605,10 +689,10 @@ public class MedtronicHistoryData {
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
if (L.isEnabled(L.PUMP)) {
if (isLogEnabled())
LOG.debug("addBolus - Extended [date={},pumpId={}, insulin={}, duration={}]", extendedBolus.date,
extendedBolus.pumpId, extendedBolus.insulin, extendedBolus.durationInMinutes);
}
}
break;
}
@ -626,15 +710,28 @@ public class MedtronicHistoryData {
detailedBolusInfo.insulin = bolusDTO.getDeliveredAmount();
detailedBolusInfo.carbs = treatment.carbs;
addCarbsFromEstimate(detailedBolusInfo, bolus);
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
bolus.setLinkedObject(detailedBolusInfo);
if (L.isEnabled(L.PUMP)) {
if (isLogEnabled())
LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
}
}
private void addCarbsFromEstimate(DetailedBolusInfo detailedBolusInfo, PumpHistoryEntry bolus) {
if (bolus.containsDecodedData("Estimate")) {
BolusWizardDTO bolusWizard = (BolusWizardDTO) bolus.getDecodedData().get("Estimate");
detailedBolusInfo.carbs = bolusWizard.carbs;
}
}
@ -662,6 +759,7 @@ public class MedtronicHistoryData {
databaseHelper.createOrUpdate(temporaryBasalDb);
if (isLogEnabled())
LOG.debug(operation + " - [date={},pumpId={}, rate={} {}, duration={}]", //
temporaryBasalDb.date, //
temporaryBasalDb.pumpId, //
@ -717,6 +815,7 @@ public class MedtronicHistoryData {
ldt = ldt.plusSeconds(pumpTime.timeDifference);
ldt = ldt.millisOfSecond().setCopy(000);
if (isLogEnabled())
LOG.debug("tryToGetByLocalTime: [TimeOfEntry={}, ClockPump={}, LocalTime={}, DifferenceSec={}, "
+ "NewTimeOfEntry={}, time={}", atechDateTime, pumpTime.pumpTime.toString("HH:mm:ss"),
pumpTime.localDeviceTime.toString("HH:mm:ss"), pumpTime.timeDifference, ldt.toString("HH:mm:ss"), ldt
@ -754,6 +853,7 @@ public class MedtronicHistoryData {
oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference);
}
} catch (Exception ex) {
if (isLogEnabled())
LOG.error("Problem decoding date from last record: {}" + currentTreatment);
return 10; // default return of 10 minutes
}
@ -763,6 +863,7 @@ public class MedtronicHistoryData {
Minutes minutes = Minutes.minutesBetween(oldestEntryTime, now);
// returns oldest time in history, with calculated time difference between pump and phone, minus 5 minutes
if (isLogEnabled())
LOG.debug("Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt,
this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes());
@ -803,6 +904,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile);
if (isLogEnabled())
LOG.debug("hasBasalProfileChanged. Items: " + filteredItems);
return (filteredItems.size() > 0);
@ -813,6 +915,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile);
if (isLogEnabled())
LOG.debug("processLastBasalProfileChange. Items: " + filteredItems);
PumpHistoryEntry newProfile = null;
@ -832,6 +935,7 @@ public class MedtronicHistoryData {
}
if (newProfile != null) {
if (isLogEnabled())
LOG.debug("processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile);
BasalProfile basalProfile = (BasalProfile) newProfile.getDecodedData().get("Object");
mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour();
@ -895,6 +999,7 @@ public class MedtronicHistoryData {
} else {
List<PumpHistoryEntry> filteredItems = getFilteredItems(entryTypes);
if (isLogEnabled())
LOG.debug("Items: " + filteredItems);
return filteredItems.size() > 0;
@ -939,4 +1044,8 @@ public class MedtronicHistoryData {
return "MedtronicHistoryData::";
}
private static boolean isLogEnabled() {
return (L.isEnabled(L.PUMP));
}
}

View file

@ -9,6 +9,7 @@ import org.slf4j.LoggerFactory;
import com.google.gson.annotations.Expose;
import info.nightscout.androidaps.logging.L;
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.FabricUtil;
@ -31,7 +32,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
*/
public class BasalProfile {
private static final Logger LOG = LoggerFactory.getLogger(BasalProfile.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
public static final int MAX_RAW_DATA_SIZE = (48 * 3) + 1;
private static final boolean DEBUG_BASALPROFILE = false;
@ -357,4 +358,10 @@ public class BasalProfile {
public String toString() {
return basalProfileToString();
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
}

View file

@ -4,6 +4,7 @@ import org.joda.time.LocalTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
/**
@ -13,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
*/
public class BasalProfileEntry {
private static final Logger LOG = LoggerFactory.getLogger(BasalProfileEntry.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
public byte[] rate_raw;
public double rate;

View file

@ -33,6 +33,14 @@ public class BolusWizardDTO extends PumpTimeStampedRecord {
bgTargetHigh, bolusTotal, correctionEstimate, foodEstimate, unabsorbedInsulin);
}
public String getDisplayableValue() {
return String.format("Bg=%d, CH=%d %s, Ch/Ins Ratio=%5.3f, Bg/Ins Ratio=%5.3f;"
+ "Bg Target(L/H)=%d/%d, Bolus: Total=%5.3f, "
+ "Correction=%5.3f, Food=%5.3f, IOB=%5.3f", //
bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, //
bgTargetHigh, bolusTotal, correctionEstimate, foodEstimate, unabsorbedInsulin);
}
public String toString() {
return "BolusWizardDTO [dateTime=" + DateTimeUtil.toString(atechDateTime) + ", " + getValue() + "]";

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil;
@ -21,7 +22,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpH
public class DailyTotalsDTO {
private static final Logger LOG = LoggerFactory.getLogger(DailyTotalsDTO.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
// bg avg, bg low hi, number Bgs,
// Sen Avg, Sen Lo/Hi, Sens Cal/Data = 0/0,
@ -116,7 +117,7 @@ public class DailyTotalsDTO {
// Daily
byte body[] = data; // entry.getBody();
System.out.println("Totals 522");
//System.out.println("Totals 522");
for (int i = 0; i < body.length - 2; i++) {

View file

@ -9,6 +9,7 @@ import org.slf4j.LoggerFactory;
import com.google.gson.annotations.Expose;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
@ -19,7 +20,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
*/
public class TempBasalPair {
private static final Logger LOG = LoggerFactory.getLogger(TempBasalPair.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
@Expose
private double insulinRate = 0.0d;
@ -61,6 +62,7 @@ public class TempBasalPair {
public TempBasalPair(byte[] response) {
if (L.isEnabled(L.PUMPCOMM))
LOG.debug("Received response: " + response);
isPercent = response[0] == 1;

View file

@ -0,0 +1,15 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto;
public class TempBasalProcessDTO {
static enum Operation {
None,
Add,
Edit
}
}

View file

@ -13,10 +13,12 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState;
@ -33,11 +35,10 @@ import info.nightscout.androidaps.utils.SP;
public class MedtronicPumpStatus extends PumpStatus {
private static Logger LOG = LoggerFactory.getLogger(MedtronicPumpStatus.class);
private static Logger LOG = LoggerFactory.getLogger(L.PUMP);
public String errorDescription = null;
public String serialNumber;
// public PumpType pumpType = null;
public String pumpFrequency = null;
public String rileyLinkAddress = null;
public Double maxBolus;
@ -62,13 +63,14 @@ public class MedtronicPumpStatus extends PumpStatus {
String regexSN = "[0-9]{6}";
boolean serialChanged = false;
boolean rileyLinkAddressChanged = false;
boolean encodingChanged = false;
RileyLinkEncodingType encodingType;
private String[] frequencies;
private boolean isFrequencyUS = false;
private Map<String, PumpType> medtronicPumpMap = null;
private Map<String, MedtronicDeviceType> medtronicDeviceTypeMap = null;
private RileyLinkTargetFrequency targetFrequency;
private boolean targetFrequencyChanged = false;
// public boolean isBasalInitalized = false;
public BasalProfileStatus basalProfileStatus;
@ -213,12 +215,14 @@ public class MedtronicPumpStatus extends PumpStatus {
String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null);
if (rileyLinkAddress == null) {
if (isLogEnabled())
LOG.debug("RileyLink address invalid: null");
this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid);
return;
} else {
if (!rileyLinkAddress.matches(regexMac)) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid);
if (isLogEnabled())
LOG.debug("RileyLink address invalid: {}", rileyLinkAddress);
} else {
if (!rileyLinkAddress.equals(this.rileyLinkAddress)) {
@ -233,7 +237,7 @@ public class MedtronicPumpStatus extends PumpStatus {
if (maxBolus == null || !maxBolus.equals(maxBolusLcl)) {
maxBolus = maxBolusLcl;
LOG.debug("Max Bolus from AAPS settings is " + maxBolus);
//LOG.debug("Max Bolus from AAPS settings is " + maxBolus);
}
double maxBasalLcl = checkParameterValue(MedtronicConst.Prefs.MaxBasal, "35.0", 35.0d);
@ -241,9 +245,13 @@ public class MedtronicPumpStatus extends PumpStatus {
if (maxBasal == null || !maxBasal.equals(maxBasalLcl)) {
maxBasal = maxBasalLcl;
LOG.debug("Max Basal from AAPS settings is " + maxBasal);
//LOG.debug("Max Basal from AAPS settings is " + maxBasal);
}
//RileyLinkEncodingType encodingType = RileyLinkEncodingType.getValueByDescription()
startService();
} catch (Exception ex) {
@ -331,4 +339,8 @@ public class MedtronicPumpStatus extends PumpStatus {
return 0;
}
private boolean isLogEnabled() {
return L.isEnabled(L.PUMP);
}
}

View file

@ -10,6 +10,7 @@ import android.os.Binder;
import android.os.IBinder;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
@ -35,7 +36,7 @@ import info.nightscout.androidaps.utils.SP;
*/
public class RileyLinkMedtronicService extends RileyLinkService {
private static final Logger LOG = LoggerFactory.getLogger(RileyLinkMedtronicService.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
private static RileyLinkMedtronicService instance;
private static ServiceTask currentTask = null;
@ -49,6 +50,7 @@ public class RileyLinkMedtronicService extends RileyLinkService {
public RileyLinkMedtronicService() {
super(MainApp.instance().getApplicationContext());
instance = this;
if (isLogEnabled())
LOG.debug("RileyLinkMedtronicService newly constructed");
MedtronicUtil.setMedtronicService(this);
pumpStatus = (MedtronicPumpStatus)MedtronicPumpPlugin.getPlugin().getPumpStatusData();
@ -67,6 +69,7 @@ public class RileyLinkMedtronicService extends RileyLinkService {
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (isLogEnabled())
LOG.warn("onConfigurationChanged");
super.onConfigurationChanged(newConfig);
}
@ -84,19 +87,6 @@ public class RileyLinkMedtronicService extends RileyLinkService {
}
// FIXME remove this, it needs to be set in PumpConfiguration not here
@Override
protected void determineRileyLinkTargetFrequency() {
// boolean hasUSFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency,
// MainApp.gs(R.string.medtronic_pump_frequency_us)).equals(MainApp.gs(R.string.medtronic_pump_frequency_us));
//
// if (hasUSFrequency)
// RileyLinkUtil.setRileyLinkTargetFrequency(RileyLinkTargetFrequency.Medtronic_US);
// else
// RileyLinkUtil.setRileyLinkTargetFrequency(RileyLinkTargetFrequency.Medtronic_WorldWide);
}
/**
* If you have customized RileyLinkServiceData you need to override this
*/
@ -193,260 +183,28 @@ public class RileyLinkMedtronicService extends RileyLinkService {
}
public boolean isSuspended() {
return false;
}
public boolean isBusy() {
return false;
}
public boolean isConnected() {
return RileyLinkServiceState.isReady(RileyLinkUtil.getRileyLinkServiceData().serviceState);
}
public boolean isConnecting() {
return !RileyLinkServiceState.isReady(RileyLinkUtil.getRileyLinkServiceData().serviceState);
}
@Override
public String getDeviceSpecificBroadcastsIdentifierPrefix() {
return null;
}
public boolean handleDeviceSpecificBroadcasts(Intent intent) {
// String action = intent.getAction();
// if (action.equals(RileyLinkConst.IPC.MSG_PUMP_fetchHistory)) {
// mHistoryPages = medtronicCommunicationManager.getAllHistoryPages();
// final boolean savePages = true;
// if (savePages) {
// for (int i = 0; i < mHistoryPages.size(); i++) {
// String filename = "PumpHistoryPage-" + i;
// LOG.warn("Saving history page to file " + filename);
// FileOutputStream outputStream;
// try {
// outputStream = openFileOutput(filename, 0);
// byte[] rawData = mHistoryPages.get(i).getRawData();
// if (rawData != null) {
// outputStream.write(rawData);
// }
// outputStream.close();
// } catch (FileNotFoundException fnf) {
// fnf.printStackTrace();
// } catch (IOException ioe) {
// ioe.printStackTrace();
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Message msg = Message.obtain(null, RT2Const.IPC.MSG_IPC, 0, 0);
// // Create a bundle with the data
// Bundle bundle = new Bundle();
// bundle.putString(RT2Const.IPC.messageKey, RT2Const.IPC.MSG_PUMP_history);
// ArrayList<Bundle> packedPages = new ArrayList<>();
// for (Page page : mHistoryPages) {
// packedPages.add(page.pack());
// }
// bundle.putParcelableArrayList(RT2Const.IPC.MSG_PUMP_history_key, packedPages);
//
// // save it to SQL.
// pumpHistoryManager.clearDatabase();
// pumpHistoryManager.initFromPages(bundle);
// // write html page to documents folder
// pumpHistoryManager.writeHtmlPage();
//
// // Set payload
// msg.setData(bundle);
// //rileyLinkIPCConnection.sendMessage(msg, null/*broadcast*/);
// LOG.debug("sendMessage: sent Full history report");
// } else if (RileyLinkConst.IPC.MSG_PUMP_fetchSavedHistory.equals(action)) {
// LOG.info("Fetching saved history");
// FileInputStream inputStream;
// ArrayList<Page> storedHistoryPages = new ArrayList<>();
// for (int i = 0; i < 16; i++) {
//
// String filename = "PumpHistoryPage-" + i;
// try {
// inputStream = openFileInput(filename);
// byte[] buffer = new byte[1024];
// int numRead = inputStream.read(buffer, 0, 1024);
// if (numRead == 1024) {
// Page p = new Page();
// //p.parseFrom(buffer, PumpModel.MM522);
//
// p.parseFrom(buffer, PumpModel.MM522);
// storedHistoryPages.add(p);
// } else {
// LOG.error(filename + " error: short file");
// }
// } catch (FileNotFoundException fnf) {
// LOG.error("Failed to open " + filename + " for reading.");
// } catch (IOException e) {
// LOG.error("Failed to read " + filename);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// mHistoryPages = storedHistoryPages;
// if (storedHistoryPages.isEmpty()) {
// LOG.error("No stored history pages loaded");
// } else {
// Message msg = Message.obtain(null, RT2Const.IPC.MSG_IPC, 0, 0);
// // Create a bundle with the data
// Bundle bundle = new Bundle();
// bundle.putString(RT2Const.IPC.messageKey, RT2Const.IPC.MSG_PUMP_history);
// ArrayList<Bundle> packedPages = new ArrayList<>();
// for (Page page : mHistoryPages) {
// packedPages.add(page.pack());
// }
// bundle.putParcelableArrayList(RT2Const.IPC.MSG_PUMP_history_key, packedPages);
//
// // save it to SQL.
// pumpHistoryManager.clearDatabase();
// pumpHistoryManager.initFromPages(bundle);
// // write html page to documents folder
// pumpHistoryManager.writeHtmlPage();
//
// // Set payload
// msg.setData(bundle);
// //rileyLinkIPCConnection.sendMessage(msg, null/*broadcast*/);
//
// }
// }
return false;
}
@Override
public void registerDeviceSpecificBroadcasts(IntentFilter intentFilter) {
// intentFilter.addAction(RT2Const.IPC.MSG_PUMP_fetchHistory);
// intentFilter.addAction(RT2Const.IPC.MSG_PUMP_fetchSavedHistory);
}
public boolean handleIncomingServiceTransport(Intent intent) {
// Bundle bundle = intent.getBundleExtra(RT2Const.IPC.bundleKey);
//
// ServiceTransport serviceTransport = new ServiceTransport(bundle);
//
// if (serviceTransport.getServiceCommand().isPumpCommand()) {
// switch (serviceTransport.getOriginalCommandName()) {
// case "ReadPumpClock":
// ServiceTaskExecutor.startTask(new ReadPumpClockTask(serviceTransport));
// break;
// case "FetchPumpHistory":
// ServiceTaskExecutor.startTask(new FetchPumpHistoryTask(serviceTransport));
// break;
// case "RetrieveHistoryPage":
// ServiceTask task = new RetrieveHistoryPageTask(serviceTransport);
// ServiceTaskExecutor.startTask(task);
// break;
// case "ReadISFProfile":
// ServiceTaskExecutor.startTask(new ReadISFProfileTask(serviceTransport));
// /*
// ISFTable table = pumpCommunicationManager.getPumpISFProfile();
// ServiceResult result = new ServiceResult();
// if (table.isValid()) {
// // convert from ISFTable to ISFProfile
// Bundle map = result.getMap();
// map.putIntArray("times", table.getTimes());
// map.putFloatArray("rates", table.getRates());
// map.putString("ValidDate", TimeFormat.standardFormatter().print(table.getValidDate()));
// result.setMap(map);
// result.setResultOK();
// }
// sendServiceTransportResponse(serviceTransport,result);
// */
// break;
// case "ReadBolusWizardCarbProfile":
// ServiceTaskExecutor.startTask(new ReadBolusWizardCarbProfileTask());
// break;
// case "UpdatePumpStatus":
// ServiceTaskExecutor.startTask(new UpdatePumpStatusTask());
// break;
// case "WakeAndTune":
// ServiceTaskExecutor.startTask(new WakeAndTuneTask());
// default:
// LOG.error("Failed to handle pump command: " + serviceTransport.getOriginalCommandName());
// break;
// }
// } else {
// switch (serviceTransport.getOriginalCommandName()) {
// case "SetPumpID":
// // This one is a command to RileyLinkMedtronicService, not to the MedtronicCommunicationManager
// String pumpID = serviceTransport.getServiceCommand().getMap().getString("pumpID", "");
// ServiceResult result = new ServiceResult();
// if ((pumpID != null) && (pumpID.length() == 6)) {
// setPumpIDString(pumpID);
// result.setResultOK();
// } else {
// LOG.error("handleIncomingServiceTransport: SetPumpID bundle missing 'pumpID' value");
// result.setResultError(-1, "Invalid parameter (missing pumpID)");
// }
// sendServiceTransportResponse(serviceTransport, result);
// break;
// case "UseThisRileylink":
// // If we are not connected, connect using the given address.
// // If we are connected and the addresses differ, disconnect, connect to new.
// // If we are connected and the addresses are the same, ignore.
// String deviceAddress = serviceTransport.getServiceCommand().getMap().getString("rlAddress", "");
// if ("".equals(deviceAddress)) {
// LOG.error("handleIPCMessage: null RL address passed");
// } else {
// reconfigureRileylink(deviceAddress);
// }
// break;
// default:
// LOG.error("handleIncomingServiceTransport: Failed to handle service command '" +
// serviceTransport.getOriginalCommandName() + "'");
// break;
// }
// }
return false;
}
public void announceProgress(int progressPercent) {
/*
* if (currentTask != null) {
* ServiceNotification note = new ServiceNotification(RT2Const.IPC.MSG_note_TaskProgress);
* note.getMap().putInt("progress", progressPercent);
* note.getMap().putString("task", currentTask.getServiceTransport().getOriginalCommandName());
* Integer senderHashcode = currentTask.getServiceTransport().getSenderHashcode();
* //rileyLinkIPCConnection.sendNotification(note, senderHashcode);
* } else {
* LOG.error("announceProgress: No current task");
* }
*/
private boolean isLogEnabled() {
return L.isEnabled(L.PUMPCOMM);
}
// public void saveHistoryPage(int pagenumber, Page page) {
// if ((page == null) || (page.getRawData() == null)) {
// return;
// }
// String filename = "history-" + pagenumber;
// FileOutputStream os;
// try {
// os = openFileOutput(filename, Context.MODE_PRIVATE);
// os.write(page.getRawData());
// os.close();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}

View file

@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
import android.os.Bundle;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceResult;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType;
@ -16,9 +17,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandTy
*/
public class MedtronicPumpResult extends ServiceResult {
// private static final String TAG = "ReadPumpClockResult";
// Map<String,Object> resultMap = new HashMap<>();
private static final Logger LOG = LoggerFactory.getLogger(MedtronicPumpResult.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
public MedtronicPumpResult(MedtronicCommandType commandType) {
@ -46,18 +45,6 @@ public class MedtronicPumpResult extends ServiceResult {
}
// public void addParameter(String parameter, String value)
// {
// map.put(parameter, value);
// }
// public void setTime(LocalDateTime pumpTime) {
// Bundle map = getMap();
// DateTimeFormatter fmt = DateTimeFormat.forStyle("FF");
// map.putString("PumpTime", fmt.print(pumpTime));
// setMap(map);
// }
public void addParameter(String key, LocalDateTime time) {
DateTimeFormatter fmt = DateTimeFormat.forStyle("FF");
map.putString(key, fmt.print(time));

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.service.tasks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.PumpTask;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager;
@ -17,7 +18,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.service.data.MedtronicP
*/
public class MedtronicPumpTask extends PumpTask {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicPumpTask.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
MedtronicCommandType commandType;
Object[] parameters;

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.plugins.pump.medtronic.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
@ -11,6 +14,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -20,7 +24,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.HexDump;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.message.MessageType;
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.defs.MedtronicCommandType;
@ -37,7 +41,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtro
public class MedtronicUtil extends RileyLinkUtil {
private static final Logger LOG = LoggerFactory.getLogger(MedtronicUtil.class);
private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM);
static int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS]
static int CRC_SIZE = 1;
private static boolean lowLevelDebug = true;
@ -50,6 +54,18 @@ public class MedtronicUtil extends RileyLinkUtil {
private static int BIG_FRAME_LENGTH = 65;
private static int doneBit = 1 << 7;
private static ClockDTO pumpTime;
public static Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
public static Gson gsonInstancePretty = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting().create();
public static Gson getGsonInstance() {
return gsonInstance;
}
public static Gson getGsonInstancePretty() {
return gsonInstancePretty;
}
public static LocalTime getTimeFrom30MinInterval(int interval) {
@ -221,9 +237,9 @@ public class MedtronicUtil extends RileyLinkUtil {
}
public static byte[] buildCommandPayload(MessageType commandType, byte[] parameters) {
return buildCommandPayload(commandType.getValue(), parameters);
}
// public static byte[] buildCommandPayload(MessageType commandType, byte[] parameters) {
// return buildCommandPayload(commandType.getValue(), parameters);
// }
public static byte[] buildCommandPayload(MedtronicCommandType commandType, byte[] parameters) {
@ -260,6 +276,7 @@ public class MedtronicUtil extends RileyLinkUtil {
byte[] payload = sendPayloadBuffer.array();
if (L.isEnabled(L.PUMPCOMM))
LOG.info(HexDump.toHexStringDisplayable(payload));
// int crc = computeCRC8WithPolynomial(payload, 0, payload.length - 1);
@ -406,9 +423,7 @@ public class MedtronicUtil extends RileyLinkUtil {
public static void setMedtronicPumpModel(MedtronicDeviceType medtronicPumpModel) {
// if (medtronicPumpModel != null && medtronicPumpModel != MedtronicDeviceType.Unknown_Device) {
MedtronicUtil.medtronicPumpModel = medtronicPumpModel;
// }
}

View file

@ -1,6 +1,6 @@
#Mon Apr 02 11:30:12 CEST 2018
#Wed May 15 21:44:10 IST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip