diff --git a/app/build.gradle b/app/build.gradle index cd2c927d63..8d56c75c33 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -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() + '"' diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index 7ce637cfcc..ff6b59c45c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -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)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java index 4848d41505..d7836b0968 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java @@ -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,20 +64,13 @@ 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 sendAndListen(RLMessage msg, int timeout_ms, Class clazz) throws RileyLinkCommunicationException { if (showPumpMessages) { - LOG.info("Sent:" + ByteUtil.shortHexString(msg.getTxData())); + if (isLogEnabled()) + LOG.info("Sent:" + ByteUtil.shortHexString(msg.getTxData())); } RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(msg.getTxData()), timeout_ms); @@ -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,7 +104,8 @@ public abstract class RileyLinkCommunicationManager { } if (showPumpMessages) { - LOG.info("Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse().getPayload())); + if (isLogEnabled()) + LOG.info("Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse().getPayload())); } return response; @@ -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,18 +139,21 @@ public abstract class RileyLinkCommunicationManager { nextWakeUpRequired = 0L; if (System.currentTimeMillis() > nextWakeUpRequired) { - LOG.info("Waking pump..."); + 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); - LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); + if (isLogEnabled()) + LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); // FIXME wakeUp successful !!!!!!!!!!!!!!!!!! nextWakeUpRequired = System.currentTimeMillis() + (receiverDeviceAwakeForMinutes * 60 * 1000); } else { - LOG.trace("Last pump communication was recent, not waking pump."); + if (isLogEnabled()) + LOG.trace("Last pump communication was recent, not waking pump."); } // long lastGoodPlus = getLastGoodReceiverCommunicationTime() + (receiverDeviceAwakeForMinutes * 60 * 1000); @@ -226,9 +209,9 @@ public abstract class RileyLinkCommunicationManager { public abstract boolean tryToConnectToDevice(); - // FIXME sorting, and time display public double scanForDevice(double[] frequencies) { - LOG.info("Scanning for receiver ({})", receiverDeviceID); + 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,7 +284,8 @@ public abstract class RileyLinkCommunicationManager { results.bestFrequencyMHz = bestTrial.frequencyMHz; if (bestTrial.successes > 0) { rfspy.setBaseFrequency(results.bestFrequencyMHz); - LOG.debug("Best frequency found: " + results.bestFrequencyMHz); + if (isLogEnabled()) + LOG.debug("Best frequency found: " + results.bestFrequencyMHz); return results.bestFrequencyMHz; } else { LOG.error("No pump response during scan."); @@ -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,9 +325,9 @@ 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:" + LOG.warn("tune_tryFrequency: invalid radio response:" + ByteUtil.shortHexString(radioResponse.getPayload())); } @@ -362,13 +359,16 @@ public abstract class RileyLinkCommunicationManager { } if (betterFrequency == 0.0) { // we've failed... caller should try a full scan for pump - LOG.error("quickTuneForPump: failed to find pump"); + if (isLogEnabled()) + LOG.error("quickTuneForPump: failed to find pump"); } else { rfspy.setBaseFrequency(betterFrequency); if (betterFrequency != startFrequencyMHz) { - LOG.info("quickTuneForPump: new frequency is {}MHz", betterFrequency); + if (isLogEnabled()) + LOG.info("quickTuneForPump: new frequency is {}MHz", betterFrequency); } else { - LOG.info("quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); + if (isLogEnabled()) + LOG.info("quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); } } return betterFrequency; @@ -376,7 +376,8 @@ public abstract class RileyLinkCommunicationManager { private double quickTunePumpStep(double startFrequencyMHz, double stepSizeMHz) { - LOG.info("Doing quick radio tune for receiver ({})", receiverDeviceID); + if (isLogEnabled()) + LOG.info("Doing quick radio tune for receiver ({})", receiverDeviceID); wakeUp(false); int startRssi = tune_tryFrequency(startFrequencyMHz); double lowerFrequency = startFrequencyMHz - stepSizeMHz; @@ -414,7 +415,8 @@ public abstract class RileyLinkCommunicationManager { // Might still be zero, but that's fine. } double minutesAgo = (System.currentTimeMillis() - lastGoodReceiverCommunicationTime) / (1000.0 * 60.0); - LOG.trace("Last good pump communication was " + minutesAgo + " minutes ago."); + 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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkConst.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkConst.java index 0a0d2ef079..51e5adc654 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkConst.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkConst.java @@ -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"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkUtil.java index f555ec0295..506932bec0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkUtil.java @@ -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 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,8 +114,9 @@ public class RileyLinkUtil { RileyLinkUtil.rileyLinkServiceData.serviceState = newState; RileyLinkUtil.rileyLinkServiceData.errorCode = errorCode; - LOG.warn("RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " - + errorCode.name()); + 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, RileyLinkUtil.rileyLinkServiceData.errorCode, targetDevice)); @@ -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; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java index c99c94d198..3b6f88609a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java @@ -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,7 +111,8 @@ public class RFSpy { BLECommOperationResult result = rileyLinkBle.readCharacteristic_blocking(radioServiceUUID, radioVersionUUID); if (result.resultCode == BLECommOperationResult.RESULT_SUCCESS) { String version = StringUtil.fromBytes(result.value); - LOG.debug("BLE Version: " + version); + if (isLogEnabled()) + LOG.debug("BLE Version: " + version); return version; } else { LOG.error("getVersion failed with code: " + result.resultCode); @@ -128,7 +123,8 @@ public class RFSpy { public RileyLinkFirmwareVersion getFirmwareVersion() { - LOG.debug("Firmware Version. Get Version - Start"); + if (isLogEnabled()) + LOG.debug("Firmware Version. Get Version - Start"); for (int i = 0; i < 5; i++) { // We have to call raw version of communication to get firmware version @@ -137,7 +133,8 @@ public class RFSpy { byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code); byte[] response = writeToDataRaw(getVersionRaw, 5000); - LOG.debug("Firmware Version. GetVersion [response={}]", ByteUtil.getHex(response)); + if (isLogEnabled()) + LOG.debug("Firmware Version. GetVersion [response={}]", ByteUtil.getHex(response)); if (response != null) { // && response[0] == (byte) 0xDD) { @@ -146,7 +143,8 @@ public class RFSpy { RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(StringUtil .fromBytes(response)); - LOG.trace("Firmware Version string: {}, resolved to {}.", versionString, version); + if (isLogEnabled()) + LOG.trace("Firmware Version string: {}, resolved to {}.", versionString, version); if (version != RileyLinkFirmwareVersion.UnknownVersion) return version; @@ -218,7 +216,8 @@ public class RFSpy { if (resp.looksLikeRadioPacket()) { // RadioResponse radioResp = resp.getRadioResponse(); // byte[] responsePayload = radioResp.getPayload(); - LOG.trace("writeToData: received radio response. Will decode at upper level"); + if (isLogEnabled()) + LOG.trace("writeToData: received radio response. Will decode at upper level"); resetNotConnectedCount(); } // Log.i(TAG, "writeToData: raw response is " + ByteUtil.shortHexString(rawResponse)); @@ -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() { - if (RileyLinkFirmwareVersion.isSameVersion(this.firmwareVersion, RileyLinkFirmwareVersion.Version2AndHigher)) { + 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,8 +413,12 @@ 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 + // FIXME not working correctly yet RFSpyResponse resp = null; try { resp = writeToData(new Reset(), EXPECTED_MAX_BLUETOOTH_LATENCY_MS); @@ -449,6 +431,6 @@ public class RFSpy { } private boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); + return L.isEnabled(L.PUMPBTCOMM); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpyReader.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpyReader.java index cf74ad96f5..063cdb877b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpyReader.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpyReader.java @@ -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 readerTask; private RileyLinkBLE rileyLinkBle; private Semaphore waitForRadioData = new Semaphore(0, true); private LinkedBlockingQueue mDataQueue = new LinkedBlockingQueue<>(); private int acquireCount = 0; private int releaseCount = 0; + private boolean stopAtNull = true; public RFSpyReader(RileyLinkBLE rileyLinkBle) { @@ -49,21 +51,30 @@ 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) { - LOG.trace(ThreadUtil.sig() + "Entering poll at t==" + SystemClock.uptimeMillis() + ", timeout is " + timeout_ms - + " mDataQueue size is " + mDataQueue.size()); + 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) { - LOG.debug("Got data [" + ByteUtil.shortHexString(dataFromQueue) + "] at t==" - + SystemClock.uptimeMillis()); + if (isLogEnabled()) + LOG.debug("Got data [" + ByteUtil.shortHexString(dataFromQueue) + "] at t==" + + SystemClock.uptimeMillis()); } else { - LOG.debug("Got data [null] at t==" + SystemClock.uptimeMillis()); + if (isLogEnabled()) + LOG.debug("Got data [null] at t==" + SystemClock.uptimeMillis()); } return dataFromQueue; } catch (InterruptedException e) { @@ -77,8 +88,9 @@ public class RFSpyReader { public void newDataIsAvailable() { releaseCount++; - LOG.trace(ThreadUtil.sig() + "waitForRadioData released(count=" + releaseCount + ") at t=" - + SystemClock.uptimeMillis()); + if (isLogEnabled()) + LOG.trace(ThreadUtil.sig() + "waitForRadioData released(count=" + releaseCount + ") at t=" + + SystemClock.uptimeMillis()); waitForRadioData.release(); } @@ -91,15 +103,13 @@ 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(); - LOG.trace(ThreadUtil.sig() + "waitForRadioData acquired (count=" + acquireCount + ") at t=" - + SystemClock.uptimeMillis()); + if (isLogEnabled()) + LOG.trace(ThreadUtil.sig() + "waitForRadioData acquired (count=" + acquireCount + ") at t=" + + SystemClock.uptimeMillis()); SystemClock.sleep(100); SystemClock.sleep(1); result = rileyLinkBle.readCharacteristic_blocking(serviceUUID, radioDataUUID); @@ -133,4 +143,8 @@ public class RFSpyReader { }.execute(); } + private boolean isLogEnabled() { + return L.isEnabled(L.PUMPBTCOMM); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RileyLinkBLE.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RileyLinkBLE.java index 42ca36b528..a42be3ce13 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RileyLinkBLE.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RileyLinkBLE.java @@ -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,14 +58,15 @@ public class RileyLinkBLE { this.context = context; this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - LOG.debug("BT Adapter: " + this.bluetoothAdapter); + if (isLogEnabled()) + LOG.debug("BT Adapter: " + this.bluetoothAdapter); bluetoothGattCallback = new BluetoothGattCallback() { @Override 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,10 +86,10 @@ public class RileyLinkBLE { super.onCharacteristicRead(gatt, characteristic, status); final String statusMessage = getGattStatusMessage(status); - if (gattDebugEnabled) { - LOG.trace(ThreadUtil.sig() + "onCharacteristicRead (" - + GattAttributes.lookup(characteristic.getUuid()) + ") " + statusMessage + ":" - + HexDump.toHexString(characteristic.getValue())); + if (gattDebugEnabled && isLogEnabled()) { + LOG.trace(ThreadUtil.sig() + "onCharacteristicRead (" + + GattAttributes.lookup(characteristic.getUuid()) + ") " + statusMessage + ":" + + HexDump.toHexString(characteristic.getValue())); } mCurrentOperation.gattOperationCompletionCallback(characteristic.getUuid(), characteristic.getValue()); } @@ -99,9 +101,9 @@ public class RileyLinkBLE { super.onCharacteristicWrite(gatt, characteristic, status); final String uuidString = GattAttributes.lookup(characteristic.getUuid()); - if (gattDebugEnabled) { - LOG.trace(ThreadUtil.sig() + "onCharacteristicWrite " + getGattStatusMessage(status) + " " - + uuidString + " " + HexDump.toHexString(characteristic.getValue())); + if (gattDebugEnabled && isLogEnabled()) { + LOG.trace(ThreadUtil.sig() + "onCharacteristicWrite " + getGattStatusMessage(status) + " " + + uuidString + " " + HexDump.toHexString(characteristic.getValue())); } mCurrentOperation.gattOperationCompletionCallback(characteristic.getUuid(), characteristic.getValue()); } @@ -133,14 +135,16 @@ public class RileyLinkBLE { stateMessage = "UNKNOWN newState (" + newState + ")"; } - LOG.warn("onConnectionStateChange " + getGattStatusMessage(status) + " " + stateMessage); + if (isLogEnabled()) + LOG.warn("onConnectionStateChange " + getGattStatusMessage(status) + " " + stateMessage); } if (newState == BluetoothProfile.STATE_CONNECTED) { if (status == BluetoothGatt.GATT_SUCCESS) { RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); } else { - LOG.debug("BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); + if (isLogEnabled()) + LOG.debug("BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); } } else if ((newState == BluetoothProfile.STATE_CONNECTING) || // @@ -151,9 +155,9 @@ public class RileyLinkBLE { RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); if (manualDisconnect) close(); - LOG.warn("RileyLink Disconnected."); + LOG.warn("RileyLink Disconnected."); } else { - LOG.warn("Some other state: (status={},newState={})", status, newState); + LOG.warn("Some other state: (status={},newState={})", status, newState); } } @@ -161,9 +165,9 @@ public class RileyLinkBLE { @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorWrite(gatt, descriptor, status); - if (gattDebugEnabled) { - LOG.warn("onDescriptorWrite " + GattAttributes.lookup(descriptor.getUuid()) + " " - + getGattStatusMessage(status) + " written: " + HexDump.toHexString(descriptor.getValue())); + if (gattDebugEnabled && isLogEnabled()) { + LOG.warn("onDescriptorWrite " + GattAttributes.lookup(descriptor.getUuid()) + " " + + getGattStatusMessage(status) + " written: " + HexDump.toHexString(descriptor.getValue())); } mCurrentOperation.gattOperationCompletionCallback(descriptor.getUuid(), 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,7 +341,8 @@ public class RileyLinkBLE { } if (bluetoothConnectionGatt.discoverServices()) { - LOG.warn("Starting to discover GATT Services."); + if (isLogEnabled()) + LOG.warn("Starting to discover GATT Services."); return true; } else { LOG.error("Cannot discover GATT Services."); @@ -357,7 +363,8 @@ public class RileyLinkBLE { public void findRileyLink(String RileyLinkAddress) { - LOG.debug("RileyLink address: " + RileyLinkAddress); + if (isLogEnabled()) + LOG.debug("RileyLink address: " + RileyLinkAddress); // Must verify that this is a valid MAC, or crash. rileyLinkDevice = bluetoothAdapter.getRemoteDevice(RileyLinkAddress); @@ -372,10 +379,10 @@ 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) { - LOG.debug("Gatt Connected?"); + if (isLogEnabled()) + LOG.debug("Gatt Connected?"); } } } @@ -383,14 +390,13 @@ public class RileyLinkBLE { public void disconnect() { mIsConnected = false; - LOG.warn("Closing GATT connection"); + 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,7 +436,8 @@ public class RileyLinkBLE { List list = chara.getDescriptors(); if (gattDebugEnabled) { for (int i = 0; i < list.size(); i++) { - LOG.debug("Found descriptor: " + list.get(i).toString()); + if (isLogEnabled()) + LOG.debug("Found descriptor: " + list.get(i).toString()); } } BluetoothGattDescriptor descr = list.get(0); @@ -558,4 +565,8 @@ public class RileyLinkBLE { return statusMessage; } + private boolean isLogEnabled() { + return L.isEnabled(L.PUMPBTCOMM); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioPacket.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioPacket.java index c469224846..a48e3de208 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioPacket.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioPacket.java @@ -46,7 +46,7 @@ public class RadioPacket { } case FourByteSixByteRileyLink: { - return pkt; + return getWithCRC(); } default: diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioResponse.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioResponse.java index 1b1cbba2e5..3f26e6ff40 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioResponse.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RadioResponse.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bAbstract.java index e8bfe2056b..3bab1a6d05 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bAbstract.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkBLEError.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkBLEError.java index bbb7d87931..8d32445718 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkBLEError.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkBLEError.java @@ -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."); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java index 5d86ac86d8..20d15a1089 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java @@ -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 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; + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicReadOperation.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicReadOperation.java index 7f9a1a1c0b..6c12a8ef77 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicReadOperation.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicReadOperation.java @@ -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,7 +45,8 @@ public class CharacteristicReadOperation extends BLECommOperation { timedOut = true; } } catch (InterruptedException e) { - LOG.error("Interrupted while waiting for gatt write operation to complete"); + if (isLogEnabled()) + LOG.error("Interrupted while waiting for gatt write operation to complete"); interrupted = true; } value = characteristic.getValue(); @@ -62,4 +64,8 @@ public class CharacteristicReadOperation extends BLECommOperation { operationComplete.release(); } + private boolean isLogEnabled() { + return L.isEnabled(L.PUMPBTCOMM); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicWriteOperation.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicWriteOperation.java index 91d81a5fc0..488b03af27 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicWriteOperation.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/CharacteristicWriteOperation.java @@ -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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java index 386fb196fe..9b9cbe2f4e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java @@ -74,12 +74,12 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter if (!first) { // 7-12 - int[] ids = { R.id.rls_t1_tv02, R.id.rls_t1_tv03, R.id.rls_t1_tv04, R.id.rls_t1_tv05, R.id.rls_t1_tv07, // - R.id.rls_t1_tv08, R.id.rls_t1_tv09, R.id.rls_t1_tv10, R.id.rls_t1_tv11, R.id.rls_t1_tv12, R.id.rls_t1_tv13 }; + int[] ids = {R.id.rls_t1_tv02, R.id.rls_t1_tv03, R.id.rls_t1_tv04, R.id.rls_t1_tv05, R.id.rls_t1_tv07, // + R.id.rls_t1_tv08, R.id.rls_t1_tv09, R.id.rls_t1_tv10, R.id.rls_t1_tv11, R.id.rls_t1_tv12, R.id.rls_t1_tv13}; for (int id : ids) { - TextView tv = (TextView)getActivity().findViewById(id); + TextView tv = (TextView) getActivity().findViewById(id); tv.setText(tv.getText() + ":"); } @@ -118,19 +118,21 @@ 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("???"); if (rileyLinkServiceData.lastGoodFrequency != null) this.lastUsedFrequency.setText(String.format(Locale.ENGLISH, "%.2f MHz", - rileyLinkServiceData.lastGoodFrequency)); + rileyLinkServiceData.lastGoodFrequency)); - // FIXME if (medtronicPumpStatus.lastConnection != 0) this.lastDeviceContact.setText(StringUtil.toDateTimeString(new LocalDateTime( - medtronicPumpStatus.lastDataTime))); + medtronicPumpStatus.lastDataTime))); else this.lastDeviceContact.setText("Never"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistory.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistory.java index 639d33cbb6..82e6c15a9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistory.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistory.java @@ -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 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 { @@ -173,108 +156,4 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter } } - // private class RileyLinkHistoryListAdapter extends BaseAdapter { - // - // private List 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 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; - // } - // } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java index b5cba95007..6d745ee24c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java @@ -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> 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,7 +96,8 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { if (action == null) { LOG.error("onReceive: null action"); } else { - LOG.debug("Received Broadcast: " + action); + if (isLoggingEnabled()) + LOG.debug("Received Broadcast: " + action); if (!processBluetoothBroadcasts(action) && // !processRileyLinkBroadcasts(action) && // @@ -128,7 +119,6 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { for (Map.Entry> 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)) { - LOG.warn("MedtronicConst.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,15 +158,18 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { String bleVersion = this.serviceInstance.rfspy.getBLEVersionCached(); RileyLinkFirmwareVersion rlVersion = this.serviceInstance.rfspy.getRLVersionCached(); - LOG.debug("RfSpy version (BLE113): " + bleVersion); +// if (isLoggingEnabled()) + LOG.debug("RfSpy version (BLE113): " + bleVersion); this.serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion; - LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); +// if (isLoggingEnabled()) + LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; ServiceTask task = new InitializePumpManagerTask(RileyLinkUtil.getTargetDevice()); ServiceTaskExecutor.startTask(task); - LOG.info("Announcing RileyLink open For business"); + if (isLoggingEnabled()) + LOG.info("Announcing RileyLink open For business"); return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) { @@ -200,22 +198,16 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { public boolean processBluetoothBroadcasts(String action) { if (action.equals(RileyLinkConst.Intents.BluetoothConnected)) { - LOG.debug("Bluetooth - Connected"); - // sendIPCNotification(RT2Const.IPC.MSG_note_FindingRileyLink); + if (isLoggingEnabled()) + LOG.debug("Bluetooth - Connected"); ServiceTaskExecutor.startTask(new DiscoverGattServicesTask()); return true; } else if (action.equals(RileyLinkConst.Intents.BluetoothReconnected)) { - LOG.debug("Bluetooth - Reconnecting"); - // sendIPCNotification(RT2Const.IPC.MSG_note_FindingRileyLink); - serviceInstance.bluetoothInit(); - ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(true)); + if (isLoggingEnabled()) + LOG.debug("Bluetooth - Reconnecting"); - 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)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java index 784ea631c6..06b7baf45f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java @@ -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,14 +127,14 @@ 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() { - LOG.debug("bluetoothInit: attempting to get an adapter"); + if (isLogEnabled()) + LOG.debug("bluetoothInit: attempting to get an adapter"); RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -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)) { - LOG.info("No change to RL address. Not reconnecting."); + if (isLogEnabled()) + LOG.info("No change to RL address. Not reconnecting."); return false; } else { - LOG.warn("Disconnecting from old RL (" + rileyLinkServiceData.rileylinkAddress - + "), reconnecting to new: " + deviceAddress); + 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,25 +223,12 @@ 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)) { - LOG.info("Saving new pump frequency of {}MHz", newFrequency); + if (isLogEnabled()) + LOG.info("Saving new pump frequency of {} MHz", newFrequency); SP.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, newFrequency); rileyLinkServiceData.lastGoodFrequency = newFrequency; rileyLinkServiceData.tuneUpDone = true; @@ -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); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkServiceData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkServiceData.java index a2f68004c5..dd66255da4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkServiceData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkServiceData.java @@ -39,4 +39,5 @@ public class RileyLinkServiceData { this.pumpID = pumpId; this.pumpIDBytes = pumpIdBytes; } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java index d4e219239b..c856a4a8e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java @@ -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); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java index 8bd986f89a..a5b559d38d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java @@ -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; } @@ -82,8 +89,8 @@ public class DateTimeUtil { public static boolean isSameDay(LocalDateTime ldt1, LocalDateTime ldt2) { return (ldt1.getYear() == ldt2.getYear() && // - ldt1.getMonthOfYear() == ldt2.getMonthOfYear() && // - ldt1.getDayOfMonth() == ldt2.getDayOfMonth()); + ldt1.getMonthOfYear() == ldt2.getMonthOfYear() && // + ldt1.getDayOfMonth() == ldt2.getDayOfMonth()); } @@ -128,25 +135,25 @@ public class DateTimeUtil { public static String toString(long atechDateTime) { - int year = (int)(atechDateTime / 10000000000L); + int year = (int) (atechDateTime / 10000000000L); atechDateTime -= year * 10000000000L; - int month = (int)(atechDateTime / 100000000L); + int month = (int) (atechDateTime / 100000000L); atechDateTime -= month * 100000000L; - int dayOfMonth = (int)(atechDateTime / 1000000L); + int dayOfMonth = (int) (atechDateTime / 1000000L); atechDateTime -= dayOfMonth * 1000000L; - int hourOfDay = (int)(atechDateTime / 10000L); + int hourOfDay = (int) (atechDateTime / 10000L); atechDateTime -= hourOfDay * 10000L; - int minute = (int)(atechDateTime / 100L); + int minute = (int) (atechDateTime / 100L); atechDateTime -= minute * 100L; - int second = (int)atechDateTime; + int second = (int) atechDateTime; return getZeroPrefixed(dayOfMonth) + "." + getZeroPrefixed(month) + "." + year + " " + // - getZeroPrefixed(hourOfDay) + ":" + getZeroPrefixed(minute) + ":" + getZeroPrefixed(second); + getZeroPrefixed(hourOfDay) + ":" + getZeroPrefixed(minute) + ":" + getZeroPrefixed(second); } @@ -157,11 +164,11 @@ public class DateTimeUtil { public static int getYear(Long atechDateTime) { - if (atechDateTime==null || atechDateTime==0) { + if (atechDateTime == null || atechDateTime == 0) { return 2000; } - int year = (int)(atechDateTime / 10000000000L); + int year = (int) (atechDateTime / 10000000000L); return year; } @@ -177,22 +184,22 @@ public class DateTimeUtil { public static long toMillisFromATD(long atechDateTime) { - int year = (int)(atechDateTime / 10000000000L); + int year = (int) (atechDateTime / 10000000000L); atechDateTime -= year * 10000000000L; - int month = (int)(atechDateTime / 100000000L); + int month = (int) (atechDateTime / 100000000L); atechDateTime -= month * 100000000L; - int dayOfMonth = (int)(atechDateTime / 1000000L); + int dayOfMonth = (int) (atechDateTime / 1000000L); atechDateTime -= dayOfMonth * 1000000L; - int hourOfDay = (int)(atechDateTime / 10000L); + int hourOfDay = (int) (atechDateTime / 10000L); atechDateTime -= hourOfDay * 10000L; - int minute = (int)(atechDateTime / 100L); + int minute = (int) (atechDateTime / 100L); atechDateTime -= minute * 100L; - int second = (int)atechDateTime; + int second = (int) atechDateTime; Date d = new Date(); d.setDate(dayOfMonth); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.java index 793dd1a3ac..1bb22614e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.java @@ -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,7 +206,8 @@ public class MedtronicFragment extends SubscriberFragment { @Subscribe public void onStatusEvent(final EventMedtronicDeviceStatusChange eventStatusChange) { - LOG.info("onStatusEvent(EventMedtronicDeviceStatusChange): {}", eventStatusChange); + if (isLogEnabled()) + LOG.info("onStatusEvent(EventMedtronicDeviceStatusChange): {}", eventStatusChange); Activity activity = getActivity(); if (activity != null) { @@ -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,16 +316,7 @@ public class MedtronicFragment extends SubscriberFragment { } break; - // // FIXME - // - // pumpStatusIconView.setText(" " + pumpStatus.pumpDeviceState.name()); - // break; - // - // // FIXME - // - // pumpStatusIconView.setText(" " + pumpStatus.pumpDeviceState.name()); - // break; - default: + default: LOG.warn("Unknown pump state: " + pumpStatus.pumpDeviceState); } } else { @@ -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); + } + + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index 7f6e770248..8b521f9324 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -106,6 +106,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter public static boolean isBusy = false; private List 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 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(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java index 3b9c58d17e..03085a231c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java @@ -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,7 +123,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager for (int retry = 0; retry < 5; retry++) { - LOG.debug("isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : "")); + if (isLogEnabled()) + LOG.debug("isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : "")); boolean connected = connectToDevice(); @@ -156,10 +158,12 @@ 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); - LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + if (isLogEnabled()) + LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); if (rfSpyResponse.wasTimeout()) { - LOG.error("isDeviceReachable. Failed to find pump (timeout)."); + if (isLogEnabled()) + LOG.error("isDeviceReachable. Failed to find pump (timeout)."); } else if (rfSpyResponse.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(); @@ -172,8 +176,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload(), PumpMessage.class); if (!pumpResponse.isValid()) { - LOG.warn("Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), - rfSpyResponse.wasTimeout()); + if (isLogEnabled()) + LOG.warn("Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), + rfSpyResponse.wasTimeout()); } else { // radioResponse.rssi; @@ -187,8 +192,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicUtil.setMedtronicPumpModel(pumpModel); } - LOG.debug("isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, - radioResponse.rssi); + if (isLogEnabled()) + LOG.debug("isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, + radioResponse.rssi); if (valid) { if (state == PumpDeviceState.PumpUnreachable) @@ -196,8 +202,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager else MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); - if (firstConnection) - checkFirstConnectionTime(); +// if (firstConnection) +// checkFirstConnectionTime(); rememberLastGoodDeviceCommunicationTime(); @@ -211,72 +217,32 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } else { - LOG.warn("isDeviceReachable. Failed to parse radio response: " - + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + if (isLogEnabled()) + LOG.warn("isDeviceReachable. Failed to parse radio response: " + + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } } catch (RileyLinkCommunicationException e) { - LOG.warn("isDeviceReachable. Failed to decode radio response: " - + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + if (isLogEnabled()) + LOG.warn("isDeviceReachable. Failed to decode radio response: " + + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } } else { - LOG.warn("isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + if (isLogEnabled()) + LOG.warn("isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } return false; } - // 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,83 +262,19 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return rval; } else { - LOG.error("runCommandWithArgs: Pump did not ack Attention packet"); + 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> frames) throws RileyLinkCommunicationException { - LOG.debug("Run command with Frames: {}", commandType.name()); + if (isLogEnabled()) + LOG.debug("Run command with Frames: {}", commandType.name()); PumpMessage rval = null; PumpMessage shortMessage = makePumpMessage(commandType, new CarelinkShortMessageBody(new byte[] { 0 })); @@ -380,11 +282,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage shortResponse = sendAndListen(shortMessage); if (shortResponse.commandType != MedtronicCommandType.CommandACK) { - LOG.error("runCommandWithFrames: Pump did not ack Attention packet"); + if (isLogEnabled()) + LOG.error("runCommandWithFrames: Pump did not ack Attention packet"); return new PumpMessage("No ACK after start message."); } else { - LOG.debug("Run command with Frames: Got ACK response for Attention packet"); + if (isLogEnabled()) + LOG.debug("Run command with Frames: Got ACK response for Attention packet"); } int frameNr = 1; @@ -402,14 +306,17 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager // LOG.debug("PumpResponse: " + rval); if (rval.commandType != MedtronicCommandType.CommandACK) { - LOG.error("runCommandWithFrames: Pump did not ACK frame #{}", frameNr); + if (isLogEnabled()) + LOG.error("runCommandWithFrames: Pump did not ACK frame #{}", frameNr); - LOG.error("Run command with Frames FAILED (command={}, response={})", commandType.name(), - rval.toString()); + if (isLogEnabled()) + LOG.error("Run command with Frames FAILED (command={}, response={})", commandType.name(), + rval.toString()); return new PumpMessage("No ACK after frame #" + frameNr); } else { - LOG.debug("Run command with Frames: Got ACK response for frame #{}", (frameNr)); + if (isLogEnabled()) + LOG.debug("Run command with Frames: Got ACK response for frame #{}", (frameNr)); } frameNr++; @@ -428,7 +335,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false); - LOG.debug("Current command: " + MedtronicUtil.getCurrentCommand()); + if (isLogEnabled()) + LOG.debug("Current command: " + MedtronicUtil.getCurrentCommand()); MedtronicUtil.setPumpDeviceState(PumpDeviceState.Active); boolean doneWithError = false; @@ -440,7 +348,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, new GetHistoryPageCarelinkMessageBody(pageNumber)); - LOG.info("getPumpHistory: Page {}", 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,7 +365,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager failed = false; break; } catch (RileyLinkCommunicationException e) { - LOG.error("First call for PumpHistory failed (retry={})", retries); + if (isLogEnabled()) + LOG.error("First call for PumpHistory failed (retry={})", retries); failed = true; } } @@ -483,7 +393,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager && currentResponse.getFrameNumber() == expectedFrameNum) { // success! got a frame. if (frameData.length != 64) { - LOG.warn("Expected frame of length 64, got frame of length " + frameData.length); + if (isLogEnabled()) + LOG.warn("Expected frame of length 64, got frame of length " + frameData.length); // but append it anyway? } // handle successful frame data @@ -493,7 +404,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, currentResponse.getFrameNumber()); - LOG.info("getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber); + 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 expectedFrameNum++; @@ -502,18 +414,22 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } else { if (frameData == null) { - LOG.error("null frame data, retrying"); + if (isLogEnabled()) + LOG.error("null frame data, retrying"); } else if (currentResponse.getFrameNumber() != expectedFrameNum) { - LOG.warn("Expected frame number {}, received {} (retrying)", expectedFrameNum, - currentResponse.getFrameNumber()); + if (isLogEnabled()) + LOG.warn("Expected frame number {}, received {} (retrying)", expectedFrameNum, + currentResponse.getFrameNumber()); } else if (frameData.length == 0) { - LOG.warn("Frame has zero length, retrying"); + if (isLogEnabled()) + LOG.warn("Frame has zero length, retrying"); } failures++; if (failures == 6) { - LOG.error( - "getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.", - expectedFrameNum, pageNumber); + if (isLogEnabled()) + LOG.error( + "getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.", + expectedFrameNum, pageNumber); done = true; // failure completion. doneWithError = true; } @@ -529,25 +445,30 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager nextMsg = sendAndListen(ackMsg); break; } catch (RileyLinkCommunicationException e) { - LOG.error("Problem acknowledging frame response. (retry={})", retries); + if (isLogEnabled()) + LOG.error("Problem acknowledging frame response. (retry={})", retries); } } if (nextMsg != null) currentResponse = new GetHistoryPageCarelinkMessageBody(nextMsg.getMessageBody().getTxData()); - else - LOG.error("We couldn't acknowledge frame from pump, aborting operation."); + else { + if (isLogEnabled()) + LOG.error("We couldn't acknowledge frame from pump, aborting operation."); + } } } if (rawHistoryPage.getLength() != 1024) { - LOG.warn("getPumpHistory: short page. Expected length of 1024, found length of " - + rawHistoryPage.getLength()); + if (isLogEnabled()) + LOG.warn("getPumpHistory: short page. Expected length of 1024, found length of " + + rawHistoryPage.getLength()); doneWithError = true; } if (!rawHistoryPage.isChecksumOK()) { - LOG.error("getPumpHistory: checksum is wrong"); + if (isLogEnabled()) + LOG.error("getPumpHistory: checksum is wrong"); doneWithError = true; } @@ -563,12 +484,14 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager List medtronicHistoryEntries = pumpHistoryDecoder .processPageAndCreateRecords(rawHistoryPage); - LOG.debug("getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); + if (isLogEnabled()) + LOG.debug("getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); // PumpHistoryResult pumpHistoryResult = new PumpHistoryResult(lastEntry, targetDate); pumpTotalResult.addHistoryEntries(medtronicHistoryEntries); - LOG.debug("getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); + if (isLogEnabled()) + LOG.debug("getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); if (pumpTotalResult.isSearchFinished()) { MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); @@ -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 getAllHistoryPages() { - // ArrayList pages = new ArrayList<>(); - // - // for (int pageNum = 0; pageNum < 16; pageNum++) { - // pages.add(getPumpHistoryPage(pageNum)); - // } - // - // return pages; - // } - - // public ArrayList getHistoryEventsSinceDate(Instant when) { - // ArrayList 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,7 +604,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private Object sendAndGetResponseWithCheck(MedtronicCommandType commandType, byte[] bodyData) { - LOG.debug("getDataFromPump: {}", commandType); + if (isLogEnabled()) + LOG.debug("getDataFromPump: {}", commandType); for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { @@ -800,7 +621,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager Object dataResponse = medtronicConverter.convertResponse(commandType, response.getRawContent()); - LOG.debug("Converted response for {} is {}.", commandType.name(), dataResponse); + if (isLogEnabled()) + LOG.debug("Converted response for {} is {}.", commandType.name(), dataResponse); return dataResponse; } else { @@ -809,7 +631,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } catch (RileyLinkCommunicationException e) { - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + if (isLogEnabled()) + LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } @@ -822,7 +645,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (!response.isValid()) { String responseData = String.format("%s: Invalid response.", method); - LOG.warn(responseData); + if (isLogEnabled()) + LOG.warn(responseData); return responseData; } @@ -838,7 +662,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager "%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, "" + expectedLength, "" + contents.length); - LOG.warn(responseData); + if (isLogEnabled()) + LOG.warn(responseData); return responseData; } } else { @@ -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,7 +700,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicCommandType commandType = MedtronicCommandType.GetBasalProfileSTD; - LOG.debug("getDataFromPump: {}", commandType); + 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,7 +754,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } else { this.errorMessage = check2; - LOG.debug("Error message: " + check2); + if (isLogEnabled()) + LOG.debug("Error message: " + check2); } } @@ -942,7 +765,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager BasalProfile basalProfile = (BasalProfile)medtronicConverter.convertResponse(commandType, data); - LOG.debug("Converted response for {} is {}.", commandType.name(), basalProfile); + if (isLogEnabled()) + LOG.debug("Converted response for {} is {}.", commandType.name(), basalProfile); MedtronicUtil.setCurrentCommand(null); MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); @@ -950,11 +774,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return basalProfile; } catch (RileyLinkCommunicationException e) { - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + if (isLogEnabled()) + LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } - LOG.warn("Error reading profile in max retries."); + if (isLogEnabled()) + LOG.warn("Error reading profile in max retries."); MedtronicUtil.setCurrentCommand(null); MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); @@ -972,7 +798,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager int last = responseRaw.length - 1; - LOG.debug("Length: " + data.length); + if (isLogEnabled()) + LOG.debug("Length: " + data.length); if (data.length >= BasalProfile.MAX_RAW_DATA_SIZE) { return false; @@ -1024,7 +851,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public Boolean setBolus(double units) { - LOG.info("setBolus: " + units); + if (isLogEnabled()) + LOG.info("setBolus: " + units); return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getBolusStrokes(units)); @@ -1033,7 +861,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public boolean setTBR(TempBasalPair tbr) { - LOG.info("setTBR: " + tbr.getDescription()); + if (isLogEnabled()) + LOG.info("setTBR: " + tbr.getDescription()); return setCommand(MedtronicCommandType.SetTemporaryBasal, tbr.getAsRawData()); } @@ -1058,10 +887,15 @@ 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) { - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + if (isLogEnabled()) + LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } @@ -1095,7 +929,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return responseMessage.commandType == MedtronicCommandType.CommandACK; } catch (RileyLinkCommunicationException e) { - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + if (isLogEnabled()) + LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } // LOG.debug("Set Basal Profile: {}", HexDump.toHexStringDisplayable(responseMessage.getRawContent())); @@ -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 ? } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.java index ece5c91594..2e83649b4a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.java @@ -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,12 +36,13 @@ 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; } - LOG.debug("Raw response before convert: " + HexDump.toHexStringDisplayable(rawContent)); + if (isLogEnabled()) + LOG.debug("Raw response before convert: " + HexDump.toHexStringDisplayable(rawContent)); this.pumpModel = MedtronicUtil.getMedtronicPumpModel(); @@ -102,7 +104,8 @@ public class MedtronicConverter { String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3)); MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel); - LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); + if (isLogEnabled()) + LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); if (pumpModel != MedtronicDeviceType.Unknown_Device) { if (!MedtronicUtil.isModelSet()) { @@ -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,7 +205,8 @@ public class MedtronicConverter { float value = ByteUtil.toInt(rawData[startIdx], rawData[startIdx + 1]) / (1.0f * strokes); - LOG.debug("Remaining insulin: " + value); + if (isLogEnabled()) + LOG.debug("Remaining insulin: " + value); return value; } @@ -229,7 +235,6 @@ public class MedtronicConverter { public Map decodeSettings512(byte[] rd) { Map map = new HashMap<>(); - // List 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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.java index 1c6d2d82c9..a0e7c84dcc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.java @@ -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 implements MedtronicHistoryDecoderInterface { - 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 i public abstract void postProcess(); - // public abstract void refreshOutputWriter(); - - // public List decodePage(RawHistoryPage dataPage) throws Exception { - // // refreshOutputWriter(); - // - // List minimedHistoryRecords = processPageAndCreateRecords(dataPage); - // - // for (MedtronicHistoryEntry record : minimedHistoryRecords) { - // decodeRecord(record); - // } - // - // runPostDecodeTasks(); - // - // return minimedHistoryRecords; - // } - - // public List decodePartialPage(RawHistoryPage dataPage) throws Exception { - // // refreshOutputWriter(); - // - // List 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 i } - // public abstract List processPageAndCreateRecords(RawHistoryPage page, - // boolean partial) throws Exception; - public List processPageAndCreateRecords(RawHistoryPage rawHistoryPage) { return processPageAndCreateRecords(rawHistoryPage, false); } @@ -164,10 +133,11 @@ public abstract class MedtronicHistoryDecoder i StringUtil.appendToStringBuilder(sb, "" + unknownEntry.getKey(), ", "); } - LOG.debug("STATISTICS OF PUMP DECODE"); + 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> entry : mapStatistics.entrySet()) { @@ -183,10 +153,12 @@ public abstract class MedtronicHistoryDecoder i String spaces = StringUtils.repeat(" ", 14 - entry.getKey().name().length()); - LOG.debug(" {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(), - sb.toString()); + if (isLogEnabled()) + LOG.debug(" {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(), + sb.toString()); } else { - LOG.debug(" {} - {}", entry.getKey().name(), entry.getValue().size()); + if (isLogEnabled()) + LOG.debug(" {} - {}", entry.getKey().name(), entry.getValue().size()); } } } @@ -213,14 +185,6 @@ public abstract class MedtronicHistoryDecoder i } - // public List processPageAndCreateRecords(RawHistoryPage rawHistoryPage) { - // return processPageAndCreateRecords(rawHistoryPage, false, getHistoryEntryClass()); - // } - - // public List processPageAndCreateRecords(RawHistoryPage rawHistoryPage, boolean partial) { - // return processPageAndCreateRecords(rawHistoryPage, partial, getHistoryEntryClass()); - // } - private List processPageAndCreateRecords(RawHistoryPage rawHistoryPage, boolean partial) { List dataClear = checkPage(rawHistoryPage, partial); List records = createRecords(dataClear); @@ -234,6 +198,8 @@ public abstract class MedtronicHistoryDecoder i return records; } - // public abstract List createRecords(List dataClear); + protected boolean isLogEnabled() { + return L.isEnabled(L.PUMPCOMM); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.java index 4a817dc561..270a669207 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.java @@ -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(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/RawHistoryPage.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/RawHistoryPage.java index 7d3e5f41af..77ae298235 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/RawHistoryPage.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/RawHistoryPage.java @@ -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]; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java index 2467506f1a..c51a1276c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java @@ -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 { - 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 createRecords(List dataClearInput) { - // List listRecords = new - // ArrayList(); - - LOG.debug("createRecords not implemented... WIP"); - // return listRecords; List dataClear = reverseList(dataClearInput, Byte.class); - System.out.println("Reversed:" + ByteUtil.getHex(ByteUtil.getByteArrayFromList(dataClear))); - prepareStatistics(); int counter = 0; - // int record = 0; List outList = new ArrayList(); @@ -215,7 +208,8 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder> 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 { - 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 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 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> 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); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.java index 9fd984407c..0910f4bd88 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.java @@ -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)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryResult.java index 54b5a9fc7f..856d2a687d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryResult.java @@ -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,11 +41,13 @@ public class PumpHistoryResult { */ this.searchDate = searchEntry.atechDateTime; this.searchType = SearchType.Date; - LOG.debug("PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate); + if (isLogEnabled()) + LOG.debug("PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate); } else if (targetDate != null) { this.searchDate = targetDate; this.searchType = SearchType.Date; - LOG.debug("PumpHistoryResult. Search parameters: Date: " + targetDate); + if (isLogEnabled()) + LOG.debug("PumpHistoryResult. Search parameters: Date: " + targetDate); } // this.unprocessedEntries = new ArrayList<>(); @@ -55,7 +57,7 @@ public class PumpHistoryResult { public void addHistoryEntries(List 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); + } + + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.java index b8583084b4..fd07214f13 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PumpMessage.java @@ -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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIComm.java index b6958ea454..92c2d6fdaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIComm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIComm.java @@ -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,7 +33,8 @@ public class MedtronicUIComm { public synchronized MedtronicUITask executeCommand(MedtronicCommandType commandType, Object... parameters) { - LOG.warn("Execute Command: " + commandType.name()); + if (isLogEnabled()) + LOG.warn("Execute Command: " + commandType.name()); MedtronicUITask task = new MedtronicUITask(commandType, parameters); @@ -67,7 +69,8 @@ public class MedtronicUIComm { // } if (!task.isReceived()) { - LOG.warn("Reply not received for " + commandType); + 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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.java index 5916befc7a..38e6c0dd44 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.java @@ -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,7 +109,8 @@ public class MedtronicUIPostprocessor { case PumpModel: { if (pumpStatus.medtronicDeviceType != MedtronicUtil.getMedtronicPumpModel()) { - LOG.warn("Configured pump is different then pump detected !"); + if (isLogEnabled()) + LOG.warn("Configured pump is different then pump detected !"); sendNotification(MedtronicNotificationType.PumpTypeNotSame); } } @@ -123,7 +125,8 @@ public class MedtronicUIPostprocessor { // no postprocessing default: - LOG.trace("Post-processing not implemented for {}.", uiTask.commandType.name()); + if (isLogEnabled()) + LOG.trace("Post-processing not implemented for {}.", uiTask.commandType.name()); } @@ -141,16 +144,19 @@ public class MedtronicUIPostprocessor { MedtronicUtil.setPumpTime(clockDTO); - LOG.debug("Pump Time: " + clockDTO.localDeviceTime + ", DeviceTime=" + clockDTO.pumpTime + // - ", diff: " + dur.getStandardSeconds() + " s"); + if (isLogEnabled()) + LOG.debug("Pump Time: " + clockDTO.localDeviceTime + ", DeviceTime=" + clockDTO.pumpTime + // + ", diff: " + dur.getStandardSeconds() + " s"); if (dur.getStandardMinutes() >= 10) { - LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: " - + dur.getStandardSeconds() + " s)"); + 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) { - LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: " - + dur.getStandardSeconds() + " s)"); + if (isLogEnabled()) + LOG.warn("Pump clock needs update, pump time: " + clockDTO.pumpTime.toString("HH:mm:ss") + " (difference: " + + dur.getStandardSeconds() + " s)"); sendNotification(MedtronicNotificationType.PumpWrongTimeNormal); } @@ -166,23 +172,27 @@ public class MedtronicUIPostprocessor { PumpSettingDTO checkValue = null; if (pumpStatus == null) { - LOG.debug("Pump Status: was null"); + if (isLogEnabled()) + LOG.debug("Pump Status: was null"); pumpStatus = MedtronicUtil.getPumpStatus(); - LOG.debug("Pump Status: " + this.pumpStatus); + if (isLogEnabled()) + LOG.debug("Pump Status: " + this.pumpStatus); } this.pumpStatus.verifyConfiguration(); // check profile if (!"Yes".equals(settings.get("PCFG_BASAL_PROFILES_ENABLED").value)) { - LOG.error("Basal profiles are not enabled on pump."); + if (isLogEnabled()) + LOG.error("Basal profiles are not enabled on pump."); sendNotification(MedtronicNotificationType.PumpBasalProfilesNotEnabled); } else { checkValue = settings.get("PCFG_ACTIVE_BASAL_PROFILE"); if (!"STD".equals(checkValue.value)) { - LOG.error("Basal profile set on pump is incorrect (must be STD)."); + if (isLogEnabled()) + LOG.error("Basal profile set on pump is incorrect (must be STD)."); sendNotification(MedtronicNotificationType.PumpIncorrectBasalProfileSelected); } } @@ -192,7 +202,8 @@ public class MedtronicUIPostprocessor { checkValue = settings.get("PCFG_TEMP_BASAL_TYPE"); if (!"Units".equals(checkValue.value)) { - LOG.error("Wrong TBR type set on pump (must be Absolute)."); + 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)) { - LOG.error("Wrong Max Basal set on Pump (current={}, required={}).", 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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUITask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUITask.java index 7fdd0e0e82..091fd5fe3f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUITask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUITask.java @@ -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,7 +47,8 @@ public class MedtronicUITask { public void execute(MedtronicCommunicationManager communicationManager) { - LOG.warn("@@@ In execute. {}", commandType); + if (isLogEnabled()) + LOG.warn("@@@ In execute. {}", commandType); switch (commandType) { case PumpModel: { @@ -134,7 +135,8 @@ public class MedtronicUITask { break; default: { - LOG.warn("This commandType is not supported (yet) - {}.", commandType); + if (isLogEnabled()) + LOG.warn("This commandType is not supported (yet) - {}.", commandType); // invalid = true; responseType = MedtronicUIResponseType.Invalid; } @@ -190,7 +192,8 @@ public class MedtronicUITask { public void postProcess(MedtronicUIPostprocessor postprocessor) { EventMedtronicDeviceStatusChange statusChange; - LOG.warn("@@@ In execute. {}", commandType); + if (isLogEnabled()) + LOG.warn("@@@ In execute. {}", commandType); if (responseType == MedtronicUIResponseType.Data) { postprocessor.postProcessData(this); @@ -222,4 +225,10 @@ public class MedtronicUITask { public Object getParameter(int index) { return parameters[index]; } + + + private boolean isLogEnabled() { + return L.isEnabled(L.PUMP); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index fdd1f198e8..ef9ac92bde 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java @@ -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 allHistory = null; private List newHistory = null; @@ -70,7 +69,7 @@ public class MedtronicHistoryData { public MedtronicHistoryData() { this.allHistory = new ArrayList<>(); - this.gsonPretty = MedtronicPumpPlugin.gsonInstancePretty; + this.gsonPretty = MedtronicUtil.gsonInstance; } @@ -101,11 +100,13 @@ public class MedtronicHistoryData { public static void showLogs(String header, String data) { if (header != null) { - LOG.debug(header); + if (isLogEnabled()) + LOG.debug(header); } for (final String token : Splitter.fixedLength(3500).split(data)) { - LOG.debug("{}", token); + if (isLogEnabled()) + LOG.debug("{}", token); } } @@ -119,6 +120,7 @@ public class MedtronicHistoryData { List newHistory2 = new ArrayList<>(); List TBRs = new ArrayList<>(); + List 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); - LOG.debug("New History entries found: {}", this.newHistory.size()); + 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 bolusEstimates, List newHistory2) { + + List 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() { @@ -169,13 +192,13 @@ public class MedtronicHistoryData { this.allHistory.add(pumpHistoryEntry); } - if (pumpHistoryEntry.atechDateTime!=null && pumpHistoryEntry.isAfter(pheLast.atechDateTime)) { + if (pumpHistoryEntry.atechDateTime != null && pumpHistoryEntry.isAfter(pheLast.atechDateTime)) { pheLast = pumpHistoryEntry; } } - if (pheLast==null) // if we don't have any valid record we don't do the filtering and setting + if (pheLast == null) // if we don't have any valid record we don't do the filtering and setting return; this.setLastHistoryRecordTime(pheLast.atechDateTime); @@ -349,16 +372,16 @@ public class MedtronicHistoryData { // TBR List 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 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,7 +412,8 @@ public class MedtronicHistoryData { TDD tddNew = new TDD(); totalsDTO.setTDD(tddNew); - LOG.debug("TDD Add: {}", tddNew); + if (isLogEnabled()) + LOG.debug("TDD Add: {}", tddNew); databaseHelper.createOrUpdateTDD(tddNew); @@ -398,7 +422,8 @@ public class MedtronicHistoryData { if (!totalsDTO.doesEqual(tddDbEntry)) { totalsDTO.setTDD(tddDbEntry); - LOG.debug("TDD Edit: {}", tddDbEntry); + if (isLogEnabled()) + LOG.debug("TDD Edit: {}", tddDbEntry); databaseHelper.createOrUpdateTDD(tddDbEntry); } @@ -431,26 +456,84 @@ public class MedtronicHistoryData { List 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) { - LOG.debug("Add " + processHistoryRecord.getDescription() + " (no db entries): " + treatment); + 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); - LOG.debug("Add " + processHistoryRecord.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb); + if (isLogEnabled()) + LOG.debug("Add " + processHistoryRecord.getDescription() + " {} - (entryFromDb={}) ", treatment, treatmentDb); + + addEntry(treatment, treatmentDb, processHistoryRecord); + } + } + } + + + private void processTBREntries(List entryList, ProcessHistoryRecord processHistoryRecord) { + + int dateDifference = getOldestDateDifference(entryList); + + List 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,16 +569,17 @@ 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) { - LOG.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})", - min, sec, outList.size(), gsonPretty.toJson(outList)); + if (isLogEnabled()) + LOG.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})", + min, sec, outList.size(), gsonPretty.toJson(outList)); } } } @@ -506,25 +590,25 @@ public class MedtronicHistoryData { private void addEntry(PumpHistoryEntry treatment, DbObjectBase treatmentDb, ProcessHistoryRecord processHistoryRecord) { - if (processHistoryRecord==ProcessHistoryRecord.Bolus) { - addBolus(treatment, (Treatment)treatmentDb); - } else if (processHistoryRecord==ProcessHistoryRecord.TBR) { - addTBR(treatment, (TemporaryBasal)treatmentDb); + if (processHistoryRecord == ProcessHistoryRecord.Bolus) { + addBolus(treatment, (Treatment) treatmentDb); + } else if (processHistoryRecord == ProcessHistoryRecord.TBR) { + addTBR(treatment, (TemporaryBasal) treatmentDb); } else { - addTBR(treatment, (TemporaryBasal)treatmentDb); + addTBR(treatment, (TemporaryBasal) treatmentDb); } } private List getDatabaseEntries(int dateDifference, ProcessHistoryRecord processHistoryRecord) { - if (processHistoryRecord==ProcessHistoryRecord.Bolus) { + if (processHistoryRecord == ProcessHistoryRecord.Bolus) { List treatmentsFromHistory = TreatmentsPlugin.getPlugin().getTreatmentsFromHistoryXMinutesAgo( dateDifference); return treatmentsFromHistory; } else { GregorianCalendar gc = new GregorianCalendar(); - gc.add(Calendar.MINUTE, (-1)*dateDifference); + gc.add(Calendar.MINUTE, (-1) * dateDifference); List tbrsFromHistory = databaseHelper.getTemporaryBasalsDataFromTime(gc.getTimeInMillis(), true); return tbrsFromHistory; @@ -534,7 +618,7 @@ public class MedtronicHistoryData { private void filterOutAlreadyAddedEntries(List entryList, List treatmentsFromHistory) { - if (isCollectionEmpty(treatmentsFromHistory) ) + if (isCollectionEmpty(treatmentsFromHistory)) return; List removeTreatmentsFromHistory = new ArrayList<>(); @@ -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,26 +710,39 @@ 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; } } private void addTBR(PumpHistoryEntry treatment, TemporaryBasal temporaryBasalDbInput) { - TempBasalPair tbr = (TempBasalPair)treatment.getDecodedData().get("Object"); + TempBasalPair tbr = (TempBasalPair) treatment.getDecodedData().get("Object"); TemporaryBasal temporaryBasalDb = temporaryBasalDbInput; String operation = "editTBR"; - if (temporaryBasalDb==null) { + if (temporaryBasalDb == null) { temporaryBasalDb = new TemporaryBasal(); temporaryBasalDb.date = tryToGetByLocalTime(treatment.atechDateTime); @@ -662,13 +759,14 @@ public class MedtronicHistoryData { databaseHelper.createOrUpdate(temporaryBasalDb); - LOG.debug(operation + " - [date={},pumpId={}, rate={} {}, duration={}]", // - temporaryBasalDb.date, // - temporaryBasalDb.pumpId, // - temporaryBasalDb.isAbsolute ? String.format("%.2f", temporaryBasalDb.absoluteRate) : - String.format("%d", temporaryBasalDb.percentRate), // - temporaryBasalDb.isAbsolute ? "U/h" : "%", // - temporaryBasalDb.durationInMinutes); + if (isLogEnabled()) + LOG.debug(operation + " - [date={},pumpId={}, rate={} {}, duration={}]", // + temporaryBasalDb.date, // + temporaryBasalDb.pumpId, // + temporaryBasalDb.isAbsolute ? String.format("%.2f", temporaryBasalDb.absoluteRate) : + String.format("%d", temporaryBasalDb.percentRate), // + temporaryBasalDb.isAbsolute ? "U/h" : "%", // + temporaryBasalDb.durationInMinutes); } @@ -717,10 +815,11 @@ public class MedtronicHistoryData { ldt = ldt.plusSeconds(pumpTime.timeDifference); ldt = ldt.millisOfSecond().setCopy(000); - 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 - .toDate().getTime()); + 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 + .toDate().getTime()); return ldt.toDate().getTime(); } @@ -754,7 +853,8 @@ public class MedtronicHistoryData { oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference); } } catch (Exception ex) { - LOG.error("Problem decoding date from last record: {}" + currentTreatment); + if (isLogEnabled()) + LOG.error("Problem decoding date from last record: {}" + currentTreatment); return 10; // default return of 10 minutes } @@ -763,8 +863,9 @@ 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 - LOG.debug("Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt, - this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes()); + if (isLogEnabled()) + LOG.debug("Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}", dt, + this.pumpTime.timeDifference, oldestEntryTime, now, minutes.getMinutes()); return minutes.getMinutes(); } @@ -803,7 +904,8 @@ public class MedtronicHistoryData { List filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile); - LOG.debug("hasBasalProfileChanged. Items: " + filteredItems); + if (isLogEnabled()) + LOG.debug("hasBasalProfileChanged. Items: " + filteredItems); return (filteredItems.size() > 0); } @@ -813,7 +915,8 @@ public class MedtronicHistoryData { List filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile); - LOG.debug("processLastBasalProfileChange. Items: " + filteredItems); + if (isLogEnabled()) + LOG.debug("processLastBasalProfileChange. Items: " + filteredItems); PumpHistoryEntry newProfile = null; Long lastDate = null; @@ -832,7 +935,8 @@ public class MedtronicHistoryData { } if (newProfile != null) { - LOG.debug("processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile); + if (isLogEnabled()) + LOG.debug("processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile); BasalProfile basalProfile = (BasalProfile) newProfile.getDecodedData().get("Object"); mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour(); } @@ -895,7 +999,8 @@ public class MedtronicHistoryData { } else { List filteredItems = getFilteredItems(entryTypes); - LOG.debug("Items: " + filteredItems); + 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)); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java index 894e503783..286f906f2a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java @@ -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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.java index a9d92d0b40..9768ad2fc8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BolusWizardDTO.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BolusWizardDTO.java index 7bd463071c..5d9710a5c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BolusWizardDTO.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BolusWizardDTO.java @@ -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() + "]"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java index 119a7d2b18..c5d163ee8c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java @@ -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++) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java index 97a8b5d463..10b73778e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java @@ -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,7 +62,8 @@ public class TempBasalPair { public TempBasalPair(byte[] response) { - LOG.debug("Received response: " + response); + if (L.isEnabled(L.PUMPCOMM)) + LOG.debug("Received response: " + response); isPercent = response[0] == 1; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.java new file mode 100644 index 0000000000..3d35af0646 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.java @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; + +public class TempBasalProcessDTO { + + + + + static enum Operation { + None, + Add, + Edit + } + + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java index da1dab903f..d93866a7b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java @@ -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 medtronicPumpMap = null; private Map medtronicDeviceTypeMap = null; private RileyLinkTargetFrequency targetFrequency; private boolean targetFrequencyChanged = false; - // public boolean isBasalInitalized = false; public BasalProfileStatus basalProfileStatus; @@ -213,13 +215,15 @@ public class MedtronicPumpStatus extends PumpStatus { String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null); if (rileyLinkAddress == null) { - LOG.debug("RileyLink address invalid: 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); - LOG.debug("RileyLink address invalid: {}", rileyLinkAddress); + if (isLogEnabled()) + LOG.debug("RileyLink address invalid: {}", rileyLinkAddress); } else { if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { this.rileyLinkAddress = 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); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java index 19b5514de6..f6d4dfeb04 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java @@ -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,7 +50,8 @@ public class RileyLinkMedtronicService extends RileyLinkService { public RileyLinkMedtronicService() { super(MainApp.instance().getApplicationContext()); instance = this; - LOG.debug("RileyLinkMedtronicService newly constructed"); + if (isLogEnabled()) + LOG.debug("RileyLinkMedtronicService newly constructed"); MedtronicUtil.setMedtronicService(this); pumpStatus = (MedtronicPumpStatus)MedtronicPumpPlugin.getPlugin().getPumpStatusData(); } @@ -67,7 +69,8 @@ public class RileyLinkMedtronicService extends RileyLinkService { @Override public void onConfigurationChanged(Configuration newConfig) { - LOG.warn("onConfigurationChanged"); + 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 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 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 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; + 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(); - // } - // } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/data/MedtronicPumpResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/data/MedtronicPumpResult.java index 64c43c1e79..1e449ef5e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/data/MedtronicPumpResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/data/MedtronicPumpResult.java @@ -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 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)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/tasks/MedtronicPumpTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/tasks/MedtronicPumpTask.java index 3af43c485a..6813163360 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/tasks/MedtronicPumpTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/tasks/MedtronicPumpTask.java @@ -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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java index 75c37eda6d..6eb676a66a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java @@ -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,7 +276,8 @@ public class MedtronicUtil extends RileyLinkUtil { byte[] payload = sendPayloadBuffer.array(); - LOG.info(HexDump.toHexStringDisplayable(payload)); + 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; - // } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index c25a2b3e46..5096a7e356 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -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