From e8f69fc1c03f718d07a9f63a730f3f2297fd403e Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 25 Apr 2020 09:23:19 +0200 Subject: [PATCH 01/23] pass 1 --- .../dependencyInjection/FragmentsModule.kt | 5 + .../dependencyInjection/ReceiversModule.kt | 3 + .../dialog/RileyLinkBLEScanActivity.java | 5 +- .../RileyLinkCommunicationManager.java | 8 +- .../common/hw/rileylink/RileyLinkUtil.java | 184 ++++++++++-------- .../pump/common/hw/rileylink/ble/RFSpy.java | 6 +- .../common/hw/rileylink/ble/RileyLinkBLE.java | 10 +- .../rileylink/ble/command/SendAndListen.java | 2 +- .../hw/rileylink/ble/command/SetPreamble.java | 2 +- .../hw/rileylink/ble/data/RadioPacket.java | 6 +- .../hw/rileylink/ble/data/RadioResponse.java | 21 +- .../dialog/RileyLinkStatusActivity.java | 7 +- ...va => RileyLinkStatusGeneralFragment.java} | 18 +- ...va => RileyLinkStatusHistoryFragment.java} | 11 +- .../RileyLinkBluetoothStateReceiver.kt | 3 +- .../service/RileyLinkBroadcastReceiver.java | 23 ++- .../rileylink/service/RileyLinkService.java | 36 ++-- .../tasks/DiscoverGattServicesTask.java | 4 +- .../tasks/InitializePumpManagerTask.java | 28 ++- .../common/ui/RileyLinkSelectPreference.java | 4 +- .../pump/medtronic/MedtronicFragment.kt | 7 +- .../pump/medtronic/MedtronicPumpPlugin.java | 9 +- .../medtronic/comm/ui/MedtronicUIComm.java | 7 +- .../medtronic/data/MedtronicHistoryData.java | 4 +- .../medtronic/driver/MedtronicPumpStatus.java | 6 +- .../service/RileyLinkMedtronicService.java | 8 +- .../res/layout/rileylink_status_general.xml | 2 +- .../res/layout/rileylink_status_history.xml | 2 +- 28 files changed, 236 insertions(+), 195 deletions(-) rename app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/{RileyLinkStatusGeneral.java => RileyLinkStatusGeneralFragment.java} (92%) rename app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/{RileyLinkStatusHistory.java => RileyLinkStatusHistoryFragment.java} (93%) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index 164dd0def0..4e6161473d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -32,6 +32,8 @@ import info.nightscout.androidaps.plugins.insulin.InsulinFragment import info.nightscout.androidaps.plugins.profile.local.LocalProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment import info.nightscout.androidaps.plugins.pump.combo.ComboFragment +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment @@ -113,4 +115,7 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesWizardInfoDialog(): WizardInfoDialog @ContributesAndroidInjector abstract fun contributesPasswordCheck(): PasswordCheck + + @ContributesAndroidInjector abstract fun contributesRileyLinkStatusGeneral(): RileyLinkStatusGeneralFragment + @ContributesAndroidInjector abstract fun contributesRileyLinkStatusHistoryFragment(): RileyLinkStatusHistoryFragment } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt index 6aa97bee69..0921ed7cd0 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver import info.nightscout.androidaps.receivers.* @Module @@ -17,4 +18,6 @@ abstract class ReceiversModule { @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver + + @ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java index e292808ded..d4642a5b56 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java @@ -60,6 +60,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { @Inject SP sp; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; + @Inject RileyLinkUtil rileyLinkUtil; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 30241; // arbitrary. private static final int REQUEST_ENABLE_BT = 30242; // arbitrary @@ -108,7 +109,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { sp.putString(RileyLinkConst.Prefs.RileyLinkAddress, bleAddress); - RileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress); + rileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress); MedtronicPumpStatus pumpStatus = MedtronicUtil.getPumpStatus(); pumpStatus.verifyConfiguration(); // force reloading of address @@ -189,7 +190,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { } // disable currently selected RL, so that we can discover it - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnect); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnect); } 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 5a30a75fe1..c748222497 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 @@ -55,8 +55,8 @@ public abstract class RileyLinkCommunicationManager { public RileyLinkCommunicationManager(Context context, RFSpy rfspy) { this.context = context; this.rfspy = rfspy; - this.rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData(); - RileyLinkUtil.setRileyLinkCommunicationManager(this); + this.rileyLinkServiceData = RileyLinkUtil.getInstance().getRileyLinkServiceData(); + RileyLinkUtil.getInstance().setRileyLinkCommunicationManager(this); configurePumpSpecificSettings(); } @@ -178,7 +178,7 @@ public abstract class RileyLinkCommunicationManager { public double tuneForDevice() { - return scanForDevice(RileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies()); + return scanForDevice(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies()); } @@ -192,7 +192,7 @@ public abstract class RileyLinkCommunicationManager { */ public boolean isValidFrequency(double frequency) { - double[] scanFrequencies = RileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies(); + double[] scanFrequencies = RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies(); if (scanFrequencies.length == 1) { return RileyLinkUtil.isSame(scanFrequencies[0], frequency); 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 71006e2c34..f0ed044124 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 @@ -5,8 +5,7 @@ import android.content.Intent; import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jetbrains.annotations.NotNull; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -15,9 +14,13 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import javax.annotation.Nonnull; +import javax.inject.Inject; +import javax.inject.Singleton; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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; @@ -42,143 +45,160 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDe * Created by andy on 17/05/2018. */ +@Singleton public class RileyLinkUtil { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP); - protected static List historyRileyLink = new ArrayList<>(); - protected static RileyLinkCommunicationManager rileyLinkCommunicationManager; + protected List historyRileyLink = new ArrayList<>(); + protected RileyLinkCommunicationManager rileyLinkCommunicationManager; static ServiceTask currentTask; - private static Context context; - private static RileyLinkBLE rileyLinkBLE; - private static RileyLinkServiceData rileyLinkServiceData; - private static RileyLinkService rileyLinkService; - private static RileyLinkTargetFrequency rileyLinkTargetFrequency; + private RileyLinkBLE rileyLinkBLE; + private RileyLinkServiceData rileyLinkServiceData; + private RileyLinkService rileyLinkService; + private RileyLinkTargetFrequency rileyLinkTargetFrequency; - private static RileyLinkTargetDevice targetDevice; - private static RileyLinkEncodingType encoding; - private static RileyLinkSelectPreference rileyLinkSelectPreference; - private static Encoding4b6b encoding4b6b; - private static RileyLinkFirmwareVersion firmwareVersion; + private RileyLinkTargetDevice targetDevice; + private RileyLinkEncodingType encoding; + private RileyLinkSelectPreference rileyLinkSelectPreference; + private Encoding4b6b encoding4b6b; + private RileyLinkFirmwareVersion firmwareVersion; - public static void setContext(Context contextIn) { - RileyLinkUtil.context = contextIn; + @NotNull private final Context context; + @NotNull private final AAPSLogger aapsLogger; + @Nonnull private final RxBusWrapper rxBus; + + @Inject + public RileyLinkUtil( + Context context, + AAPSLogger aapsLogger, + RxBusWrapper rxBus + + ) { + this.context = context; + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; + instance = this; } + private static RileyLinkUtil instance; - public static RileyLinkEncodingType getEncoding() { + // TODO: replace by injection + @Deprecated + public static RileyLinkUtil getInstance() { + if (instance == null) throw new IllegalStateException("RileyLinkUtil not initialized"); + return instance; + } + + public RileyLinkEncodingType getEncoding() { return encoding; } - public static void setEncoding(RileyLinkEncodingType encoding) { - RileyLinkUtil.encoding = encoding; + public void setEncoding(RileyLinkEncodingType encoding) { + this.encoding = encoding; if (encoding == RileyLinkEncodingType.FourByteSixByteLocal) { - RileyLinkUtil.encoding4b6b = new Encoding4b6bGeoff(); + this.encoding4b6b = new Encoding4b6bGeoff(); } } - public static void sendBroadcastMessage(String message) { - if (context != null) { - Intent intent = new Intent(message); - LocalBroadcastManager.getInstance(RileyLinkUtil.context).sendBroadcast(intent); - } + public void sendBroadcastMessage(String message) { + Intent intent = new Intent(message); + LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } - public static void setServiceState(RileyLinkServiceState newState) { + public void setServiceState(RileyLinkServiceState newState) { setServiceState(newState, null); } - public static RileyLinkError getError() { - if (RileyLinkUtil.rileyLinkServiceData != null) - return RileyLinkUtil.rileyLinkServiceData.errorCode; + public RileyLinkError getError() { + if (rileyLinkServiceData != null) + return rileyLinkServiceData.errorCode; else return null; } - public static RileyLinkServiceState getServiceState() { + public RileyLinkServiceState getServiceState() { return workWithServiceState(null, null, false); } - public static void setServiceState(RileyLinkServiceState newState, RileyLinkError errorCode) { + public void setServiceState(RileyLinkServiceState newState, RileyLinkError errorCode) { workWithServiceState(newState, errorCode, true); } - private static synchronized RileyLinkServiceState workWithServiceState(RileyLinkServiceState newState, - RileyLinkError errorCode, boolean set) { + private synchronized RileyLinkServiceState workWithServiceState(RileyLinkServiceState newState, + RileyLinkError errorCode, boolean set) { if (set) { - RileyLinkUtil.rileyLinkServiceData.serviceState = newState; - RileyLinkUtil.rileyLinkServiceData.errorCode = errorCode; + rileyLinkServiceData.serviceState = newState; + rileyLinkServiceData.errorCode = errorCode; - if (L.isEnabled(L.PUMP)) - LOG.info("RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " - + errorCode.name()); + aapsLogger.info(LTag.PUMP, "RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " + + errorCode.name()); - RileyLinkUtil.historyRileyLink.add(new RLHistoryItem(RileyLinkUtil.rileyLinkServiceData.serviceState, - RileyLinkUtil.rileyLinkServiceData.errorCode, targetDevice)); - RxBus.Companion.getINSTANCE().send(new EventMedtronicDeviceStatusChange(newState, errorCode)); + historyRileyLink.add(new RLHistoryItem(rileyLinkServiceData.serviceState, + rileyLinkServiceData.errorCode, targetDevice)); + rxBus.send(new EventMedtronicDeviceStatusChange(newState, errorCode)); return null; } else { - return (RileyLinkUtil.rileyLinkServiceData == null || RileyLinkUtil.rileyLinkServiceData.serviceState == null) ? // + return (rileyLinkServiceData == null || rileyLinkServiceData.serviceState == null) ? // RileyLinkServiceState.NotStarted - : RileyLinkUtil.rileyLinkServiceData.serviceState; + : rileyLinkServiceData.serviceState; } } - public static RileyLinkBLE getRileyLinkBLE() { - return RileyLinkUtil.rileyLinkBLE; + public RileyLinkBLE getRileyLinkBLE() { + return rileyLinkBLE; } - public static void setRileyLinkBLE(RileyLinkBLE rileyLinkBLEIn) { - RileyLinkUtil.rileyLinkBLE = rileyLinkBLEIn; + public void setRileyLinkBLE(RileyLinkBLE rileyLinkBLEIn) { + rileyLinkBLE = rileyLinkBLEIn; } - public static RileyLinkServiceData getRileyLinkServiceData() { - return RileyLinkUtil.rileyLinkServiceData; + public RileyLinkServiceData getRileyLinkServiceData() { + return rileyLinkServiceData; } - public static void setRileyLinkServiceData(RileyLinkServiceData rileyLinkServiceData) { - RileyLinkUtil.rileyLinkServiceData = rileyLinkServiceData; + public void setRileyLinkServiceData(RileyLinkServiceData rileyLinkServiceData) { + this.rileyLinkServiceData = rileyLinkServiceData; } - public static boolean hasPumpBeenTunned() { - return RileyLinkUtil.rileyLinkServiceData.tuneUpDone; + public boolean hasPumpBeenTunned() { + return rileyLinkServiceData.tuneUpDone; } - public static RileyLinkService getRileyLinkService() { - return RileyLinkUtil.rileyLinkService; + public RileyLinkService getRileyLinkService() { + return rileyLinkService; } - public static void setRileyLinkService(RileyLinkService rileyLinkService) { - RileyLinkUtil.rileyLinkService = rileyLinkService; + public void setRileyLinkService(RileyLinkService rileyLinkService) { + this.rileyLinkService = rileyLinkService; } - public static RileyLinkCommunicationManager getRileyLinkCommunicationManager() { - return RileyLinkUtil.rileyLinkCommunicationManager; + public RileyLinkCommunicationManager getRileyLinkCommunicationManager() { + return rileyLinkCommunicationManager; } - public static void setRileyLinkCommunicationManager(RileyLinkCommunicationManager rileyLinkCommunicationManager) { - RileyLinkUtil.rileyLinkCommunicationManager = rileyLinkCommunicationManager; + void setRileyLinkCommunicationManager(RileyLinkCommunicationManager rileyLinkCommunicationManager) { + this.rileyLinkCommunicationManager = rileyLinkCommunicationManager; } @@ -222,13 +242,13 @@ public class RileyLinkUtil { } - public static RileyLinkTargetFrequency getRileyLinkTargetFrequency() { - return RileyLinkUtil.rileyLinkTargetFrequency; + public RileyLinkTargetFrequency getRileyLinkTargetFrequency() { + return rileyLinkTargetFrequency; } - public static void setRileyLinkTargetFrequency(RileyLinkTargetFrequency rileyLinkTargetFrequency) { - RileyLinkUtil.rileyLinkTargetFrequency = rileyLinkTargetFrequency; + public void setRileyLinkTargetFrequency(RileyLinkTargetFrequency rileyLinkTargetFrequency) { + this.rileyLinkTargetFrequency = rileyLinkTargetFrequency; } @@ -286,44 +306,42 @@ public class RileyLinkUtil { } - public static List getRileyLinkHistory() { + public List getRileyLinkHistory() { return historyRileyLink; } - public static RileyLinkTargetDevice getTargetDevice() { + public RileyLinkTargetDevice getTargetDevice() { return targetDevice; } - public static void setTargetDevice(RileyLinkTargetDevice targetDevice) { - RileyLinkUtil.targetDevice = targetDevice; + public void setTargetDevice(RileyLinkTargetDevice targetDevice) { + this.targetDevice = targetDevice; } - public static void setRileyLinkSelectPreference(RileyLinkSelectPreference rileyLinkSelectPreference) { - - RileyLinkUtil.rileyLinkSelectPreference = rileyLinkSelectPreference; + public void setRileyLinkSelectPreference(RileyLinkSelectPreference rileyLinkSelectPreference) { + this.rileyLinkSelectPreference = rileyLinkSelectPreference; } - public static RileyLinkSelectPreference getRileyLinkSelectPreference() { - + public RileyLinkSelectPreference getRileyLinkSelectPreference() { return rileyLinkSelectPreference; } - public static Encoding4b6b getEncoding4b6b() { - return RileyLinkUtil.encoding4b6b; + public Encoding4b6b getEncoding4b6b() { + return encoding4b6b; } - public static void setFirmwareVersion(RileyLinkFirmwareVersion firmwareVersion) { - RileyLinkUtil.firmwareVersion = firmwareVersion; + public void setFirmwareVersion(RileyLinkFirmwareVersion firmwareVersion) { + this.firmwareVersion = firmwareVersion; } - public static RileyLinkFirmwareVersion getFirmwareVersion() { + public RileyLinkFirmwareVersion getFirmwareVersion() { return firmwareVersion; } } 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 031de05e23..beed22f7fa 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 @@ -90,7 +90,7 @@ public class RFSpy { public void initializeRileyLink() { bleVersion = getVersion(); firmwareVersion = getFirmwareVersion(); - RileyLinkUtil.setFirmwareVersion(firmwareVersion); + RileyLinkUtil.getInstance().setFirmwareVersion(firmwareVersion); } @@ -289,7 +289,7 @@ public class RFSpy { this.currentFrequencyMHz = freqMHz; - configureRadioForRegion(RileyLinkUtil.getRileyLinkTargetFrequency()); + configureRadioForRegion(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency()); } @@ -396,7 +396,7 @@ public class RFSpy { if (resp.isOK()) { reader.setRileyLinkEncodingType(encoding); - RileyLinkUtil.setEncoding(encoding); + RileyLinkUtil.getInstance().setEncoding(encoding); } return resp; 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 42b7f8ce6e..49f1b426e3 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 @@ -142,7 +142,7 @@ public class RileyLinkBLE { if (newState == BluetoothProfile.STATE_CONNECTED) { if (status == BluetoothGatt.GATT_SUCCESS) { - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); + RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); } else { if (isLogEnabled()) LOG.debug("BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); @@ -153,7 +153,7 @@ public class RileyLinkBLE { // LOG.debug("We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" : // "Disconnecting"); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); + RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); if (manualDisconnect) close(); LOG.warn("RileyLink Disconnected."); @@ -240,19 +240,19 @@ public class RileyLinkBLE { if (rileyLinkFound) { mIsConnected = true; - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady); + RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady); // RileyLinkUtil.sendNotification(new // ServiceNotification(RileyLinkConst.Intents.RileyLinkReady), null); } else { mIsConnected = false; - RileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkError, + RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.RileyLinkError, RileyLinkError.DeviceIsNotRileyLink); } } else { if (isLogEnabled()) LOG.debug("onServicesDiscovered " + getGattStatusMessage(status)); - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed); + RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed); } } }; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java index 900275a05f..cdefa2af29 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java @@ -57,7 +57,7 @@ public class SendAndListen extends RileyLinkCommand { // If firmware version is not set (error reading version from device, shouldn't happen), // we will default to version 2 - boolean isPacketV2 = RileyLinkUtil.getFirmwareVersion() != null ? RileyLinkUtil.getFirmwareVersion() + boolean isPacketV2 = RileyLinkUtil.getInstance().getFirmwareVersion() != null ? RileyLinkUtil.getInstance().getFirmwareVersion() .isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher) : true; ArrayList bytes = new ArrayList(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java index 7333459f2b..16ed2efc3b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java @@ -17,7 +17,7 @@ public class SetPreamble extends RileyLinkCommand { super(); // this command was not supported before 2.0 - if (!RileyLinkUtil.getFirmwareVersion().isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { + if (!RileyLinkUtil.getInstance().getFirmwareVersion().isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { throw new NotImplementedException("Old firmware does not support SetPreamble command"); } 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 a48e3de208..35fc0d54ff 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 @@ -33,7 +33,7 @@ public class RadioPacket { public byte[] getEncoded() { - switch (RileyLinkUtil.getEncoding()) { + switch (RileyLinkUtil.getInstance().getEncoding()) { case Manchester: { // We have this encoding in RL firmware return pkt; } @@ -41,7 +41,7 @@ public class RadioPacket { case FourByteSixByteLocal: { byte[] withCRC = getWithCRC(); - byte[] encoded = RileyLinkUtil.getEncoding4b6b().encode4b6b(withCRC); + byte[] encoded = RileyLinkUtil.getInstance().getEncoding4b6b().encode4b6b(withCRC); return ByteUtil.concat(encoded, (byte)0); } @@ -50,7 +50,7 @@ public class RadioPacket { } default: - throw new NotImplementedException(("Encoding not supported: " + RileyLinkUtil.getEncoding().toString())); + throw new NotImplementedException(("Encoding not supported: " + RileyLinkUtil.getInstance().getEncoding().toString())); } } 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 2b170cd0fb..3caf7872c0 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 @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data; import org.apache.commons.lang3.NotImplementedException; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; @@ -75,8 +74,8 @@ public class RadioResponse { } byte[] encodedPayload; - if (RileyLinkFirmwareVersion.isSameVersion(RileyLinkUtil.getRileyLinkServiceData().versionCC110, - RileyLinkFirmwareVersion.Version2)) { + if (RileyLinkFirmwareVersion.isSameVersion(RileyLinkUtil.getInstance().getRileyLinkServiceData().versionCC110, + RileyLinkFirmwareVersion.Version2)) { encodedPayload = ByteUtil.substring(rxData, 3, rxData.length - 3); rssi = rxData[1]; responseNumber = rxData[2]; @@ -92,23 +91,23 @@ public class RadioResponse { // well, for non-radio commands we shouldn't even reach this point // but getVersion is kind of exception if (command != null && // - command.getCommandType() != RileyLinkCommandType.SendAndListen) { + command.getCommandType() != RileyLinkCommandType.SendAndListen) { decodedOK = true; decodedPayload = encodedPayload; return; } - switch (RileyLinkUtil.getEncoding()) { + switch (RileyLinkUtil.getInstance().getEncoding()) { case Manchester: case FourByteSixByteRileyLink: { decodedOK = true; decodedPayload = encodedPayload; } - break; + break; case FourByteSixByteLocal: { - byte[] decodeThis = RileyLinkUtil.getEncoding4b6b().decode4b6b(encodedPayload); + byte[] decodeThis = RileyLinkUtil.getInstance().getEncoding4b6b().decode4b6b(encodedPayload); if (decodeThis != null && decodeThis.length > 2) { decodedOK = true; @@ -118,17 +117,17 @@ public class RadioResponse { byte calculatedCRC = CRC.crc8(decodedPayload); if (receivedCRC != calculatedCRC) { LOG.error(String.format("RadioResponse: CRC mismatch, calculated 0x%02x, received 0x%02x", - calculatedCRC, receivedCRC)); + calculatedCRC, receivedCRC)); } } else { throw new RileyLinkCommunicationException(RileyLinkBLEError.TooShortOrNullResponse); } } - break; + break; default: - throw new NotImplementedException("this {" + RileyLinkUtil.getEncoding().toString() - + "} encoding is not supported"); + throw new NotImplementedException("this {" + RileyLinkUtil.getInstance().getEncoding().toString() + + "} encoding is not supported"); } } catch (NumberFormatException e) { decodedOK = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java index 5d6b2a655b..09af88b437 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java @@ -26,6 +26,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { @Inject ResourceHelper resourceHelper; + @Inject RileyLinkUtil rileyLinkUtil; TextView connectionStatus; TextView configuredAddress; @@ -76,7 +77,7 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { this.connectedDevice = findViewById(R.id.rls_t1_connected_device); this.connectionError = findViewById(R.id.rls_t1_connection_error); - rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData(); + rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData(); // // 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, // @@ -114,8 +115,8 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - mSectionsPagerAdapter.addFragment(new RileyLinkStatusGeneral(), resourceHelper.gs(R.string.rileylink_settings_tab1)); - mSectionsPagerAdapter.addFragment(new RileyLinkStatusHistory(), resourceHelper.gs(R.string.rileylink_settings_tab2)); + mSectionsPagerAdapter.addFragment(new RileyLinkStatusGeneralFragment(), resourceHelper.gs(R.string.rileylink_settings_tab1)); + mSectionsPagerAdapter.addFragment(new RileyLinkStatusHistoryFragment(), resourceHelper.gs(R.string.rileylink_settings_tab2)); //mSectionsPagerAdapter.addFragment(new RileyLinkStatusDevice(), "Medtronic"); mViewPager.setAdapter(mSectionsPagerAdapter); 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/RileyLinkStatusGeneralFragment.java similarity index 92% rename from app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java rename to app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index 021d1ee068..e4d1944a6a 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/RileyLinkStatusGeneralFragment.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -11,6 +10,9 @@ import org.joda.time.LocalDateTime; import java.util.Locale; +import javax.inject.Inject; + +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; @@ -27,7 +29,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; * Created by andy on 5/19/18. */ -public class RileyLinkStatusGeneral extends Fragment implements RefreshableInterface { +public class RileyLinkStatusGeneralFragment extends DaggerFragment implements RefreshableInterface { + + @Inject RileyLinkUtil rileyLinkUtil; TextView connectionStatus; TextView configuredAddress; @@ -58,7 +62,7 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter @Override public void onStart() { super.onStart(); - rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData(); + rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData(); this.connectionStatus = getActivity().findViewById(R.id.rls_t1_connection_status); this.configuredAddress = getActivity().findViewById(R.id.rls_t1_configured_address); @@ -93,12 +97,12 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter public void refreshData() { - RileyLinkTargetDevice targetDevice = RileyLinkUtil.getTargetDevice(); + RileyLinkTargetDevice targetDevice = rileyLinkUtil.getTargetDevice(); - if (RileyLinkUtil.getServiceState()==null) + if (rileyLinkUtil.getServiceState() == null) this.connectionStatus.setText(MainApp.gs(RileyLinkServiceState.NotStarted.getResourceId(targetDevice))); else - this.connectionStatus.setText(MainApp.gs(RileyLinkUtil.getServiceState().getResourceId(targetDevice))); + this.connectionStatus.setText(MainApp.gs(rileyLinkUtil.getServiceState().getResourceId(targetDevice))); if (rileyLinkServiceData != null) { this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress); @@ -109,7 +113,7 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter RileyLinkFirmwareVersion firmwareVersion = rileyLinkServiceData.versionCC110; - if (firmwareVersion==null) { + if (firmwareVersion == null) { this.firmwareVersion.setText("BLE113: -\nCC110: -"); } else { this.firmwareVersion.setText("BLE113: " + rileyLinkServiceData.versionBLE113 + // 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/RileyLinkStatusHistoryFragment.java similarity index 93% rename from app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistory.java rename to app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java index d6af799550..644bd15dcf 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/RileyLinkStatusHistoryFragment.java @@ -12,6 +12,9 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import javax.inject.Inject; + +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; @@ -23,7 +26,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; * Created by andy on 5/19/18. */ -public class RileyLinkStatusHistory extends Fragment implements RefreshableInterface { +public class RileyLinkStatusHistoryFragment extends DaggerFragment implements RefreshableInterface { + + @Inject RileyLinkUtil rileyLinkUtil; RecyclerView recyclerView; RecyclerViewAdapter recyclerViewAdapter; @@ -59,8 +64,8 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter @Override public void refreshData() { - if (RileyLinkUtil.getRileyLinkHistory()!=null) { - recyclerViewAdapter.addItemsAndClean(RileyLinkUtil.getRileyLinkHistory()); + if (rileyLinkUtil.getRileyLinkHistory()!=null) { + recyclerViewAdapter.addItemsAndClean(rileyLinkUtil.getRileyLinkHistory()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt index c677ae0c1e..bca161e139 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt @@ -15,6 +15,7 @@ import javax.inject.Inject class RileyLinkBluetoothStateReceiver : DaggerBroadcastReceiver() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var rileyLinkUtil: RileyLinkUtil override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) @@ -27,7 +28,7 @@ class RileyLinkBluetoothStateReceiver : DaggerBroadcastReceiver() { BluetoothAdapter.STATE_ON -> { aapsLogger.debug("RileyLinkBluetoothStateReceiver: Bluetooth back on. Sending broadcast to RileyLink Framework") - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected) + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected) } } } 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 9dfb05fc63..f250d1480a 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 @@ -5,20 +5,22 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service; */ import android.bluetooth.BluetoothAdapter; -import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; + import androidx.localbroadcastmanager.content.LocalBroadcastManager; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.inject.Inject; + +import dagger.android.DaggerBroadcastReceiver; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; @@ -31,14 +33,17 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTask; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * I added this class outside of RileyLinkService, because for now it's very important part of RL framework and * where we get a lot of problems. Especially merging between AAPS and RileyLinkAAPS. I might put it back at * later time */ -public class RileyLinkBroadcastReceiver extends BroadcastReceiver { +public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { + + @Inject RileyLinkUtil rileyLinkUtil; + @Inject SP sp; private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); @@ -88,6 +93,7 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { + super.onReceive(context, intent); if (intent == null) { LOG.error("onReceive: received null intent"); @@ -135,10 +141,9 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnected)) { if (BluetoothAdapter.getDefaultAdapter().isEnabled()) { - RileyLinkUtil - .setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable); } else { - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); } return true; @@ -166,14 +171,14 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver { LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; - ServiceTask task = new InitializePumpManagerTask(RileyLinkUtil.getTargetDevice()); + ServiceTask task = new InitializePumpManagerTask(rileyLinkUtil.getTargetDevice()); ServiceTaskExecutor.startTask(task); if (isLoggingEnabled()) LOG.info("Announcing RileyLink open For business"); return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) { - String RileylinkBLEAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); + String RileylinkBLEAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); if (RileylinkBLEAddress.equals("")) { LOG.error("No Rileylink BLE Address saved in app"); } else { 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 0b697fe6eb..c31ec9dcad 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 @@ -25,8 +25,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import static info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil.getRileyLinkCommunicationManager; - /** * Created by andy on 5/6/18. * Split from original file and renamed. @@ -36,6 +34,7 @@ public abstract class RileyLinkService extends DaggerService { @Inject protected AAPSLogger aapsLogger; @Inject protected SP sp; @Inject protected Context context; + @Inject protected RileyLinkUtil rileyLinkUtil; public RileyLinkBLE rileyLinkBLE; // android-bluetooth management @@ -50,9 +49,8 @@ public abstract class RileyLinkService extends DaggerService { super.onCreate(); //LOG.debug("onCreate"); - RileyLinkUtil.setContext(this.context); - RileyLinkUtil.setRileyLinkService(this); - RileyLinkUtil.setEncoding(getEncoding()); + rileyLinkUtil.setRileyLinkService(this); + rileyLinkUtil.setEncoding(getEncoding()); initRileyLinkServiceData(); mBroadcastReceiver = new RileyLinkBroadcastReceiver(this, this.context); @@ -134,27 +132,26 @@ public abstract class RileyLinkService extends DaggerService { // We've received a service startCommand, we grab the lock. @Override public int onStartCommand(Intent intent, int flags, int startId) { - RileyLinkUtil.setContext(getApplicationContext()); return (START_STICKY); } public boolean bluetoothInit() { aapsLogger.debug(LTag.PUMPCOMM, "bluetoothInit: attempting to get an adapter"); - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { aapsLogger.error("Unable to obtain a BluetoothAdapter."); - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter); } else { if (!bluetoothAdapter.isEnabled()) { aapsLogger.error("Bluetooth is not enabled."); - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); } else { - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); return true; } } @@ -167,11 +164,11 @@ public abstract class RileyLinkService extends DaggerService { public boolean reconfigureRileyLink(String deviceAddress) { if (rileyLinkBLE == null) { - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); return false; } - RileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkInitializing); + rileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkInitializing); if (rileyLinkBLE.isConnected()) { if (deviceAddress.equals(rileyLinkServiceData.rileylinkAddress)) { @@ -192,10 +189,10 @@ public abstract class RileyLinkService extends DaggerService { } else { aapsLogger.debug(LTag.PUMPCOMM, "Using RL " + deviceAddress); - if (RileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) { + if (rileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) { if (!bluetoothInit()) { aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. {}", - RileyLinkUtil.getError() != null ? RileyLinkUtil.getError().name() : "Unknown error (null)"); + rileyLinkUtil.getError() != null ? rileyLinkUtil.getError().name() : "Unknown error (null)"); return false; } } @@ -214,7 +211,7 @@ public abstract class RileyLinkService extends DaggerService { // FIXME: This needs to be run in a session so that is interruptable, has a separate thread, etc. public void doTuneUpDevice() { - RileyLinkUtil.setServiceState(RileyLinkServiceState.TuneUpDevice); + rileyLinkUtil.setServiceState(RileyLinkServiceState.TuneUpDevice); MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); double lastGoodFrequency = 0.0d; @@ -239,11 +236,10 @@ public abstract class RileyLinkService extends DaggerService { if (newFrequency == 0.0d) { // error tuning pump, pump not present ?? - RileyLinkUtil - .setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed); + rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed); } else { - getRileyLinkCommunicationManager().clearNotConnectedCount(); - RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); + rileyLinkUtil.getRileyLinkCommunicationManager().clearNotConnectedCount(); + rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); } } @@ -255,7 +251,7 @@ public abstract class RileyLinkService extends DaggerService { rileyLinkServiceData.rileylinkAddress = null; } - RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); + rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java index 5f807c3e89..a588d300fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java @@ -23,8 +23,8 @@ public class DiscoverGattServicesTask extends ServiceTask { public void run() { if (needToConnect) - RileyLinkUtil.getRileyLinkBLE().connectGatt(); + RileyLinkUtil.getInstance().getRileyLinkBLE().connectGatt(); - RileyLinkUtil.getRileyLinkBLE().discoverServices(); + RileyLinkUtil.getInstance().getRileyLinkBLE().discoverServices(); } } 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 1697e0640d..314e4323ef 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 @@ -1,9 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; -import android.util.Log; - import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; @@ -13,7 +10,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; -import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.utils.SP; /** @@ -43,42 +39,42 @@ public class InitializePumpManagerTask extends ServiceTask { double lastGoodFrequency = 0.0d; - if (RileyLinkUtil.getRileyLinkServiceData().lastGoodFrequency==null) { + if (RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency == null) { lastGoodFrequency = SP.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0d); lastGoodFrequency = Math.round(lastGoodFrequency * 1000d) / 1000d; - RileyLinkUtil.getRileyLinkServiceData().lastGoodFrequency = lastGoodFrequency; + RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency = lastGoodFrequency; // if (RileyLinkUtil.getRileyLinkTargetFrequency() == null) { // String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null); // } } else { - lastGoodFrequency = RileyLinkUtil.getRileyLinkServiceData().lastGoodFrequency; + lastGoodFrequency = RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency; } if ((lastGoodFrequency > 0.0d) - && RileyLinkUtil.getRileyLinkCommunicationManager().isValidFrequency(lastGoodFrequency)) { + && RileyLinkUtil.getInstance().getRileyLinkCommunicationManager().isValidFrequency(lastGoodFrequency)) { - RileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkReady); + RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.RileyLinkReady); if (L.isEnabled(L.PUMPCOMM)) LOG.info("Setting radio frequency to {} MHz", lastGoodFrequency); - RileyLinkUtil.getRileyLinkCommunicationManager().setRadioFrequencyForPump(lastGoodFrequency); + RileyLinkUtil.getInstance().getRileyLinkCommunicationManager().setRadioFrequencyForPump(lastGoodFrequency); - boolean foundThePump = RileyLinkUtil.getRileyLinkCommunicationManager().tryToConnectToDevice(); + boolean foundThePump = RileyLinkUtil.getInstance().getRileyLinkCommunicationManager().tryToConnectToDevice(); if (foundThePump) { - RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); + RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorReady); } else { - RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError, - RileyLinkError.NoContactWithDevice); - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorError, + RileyLinkError.NoContactWithDevice); + RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); } } else { - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java index 360f6e4798..93ce56952a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java @@ -19,7 +19,7 @@ public class RileyLinkSelectPreference extends Preference { super(context); setInitialSummaryValue(); - MedtronicUtil.setRileyLinkSelectPreference(this); + MedtronicUtil.getInstance().setRileyLinkSelectPreference(this); } @@ -27,7 +27,7 @@ public class RileyLinkSelectPreference extends Preference { super(context, attrs); setInitialSummaryValue(); - MedtronicUtil.setRileyLinkSelectPreference(this); + MedtronicUtil.getInstance().setRileyLinkSelectPreference(this); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 7237dab948..08a8f4480f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -57,6 +57,7 @@ class MedtronicFragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin @Inject lateinit var warnColors: WarnColors + @Inject lateinit var rileyLinkUtil: RileyLinkUtil private var disposable: CompositeDisposable = CompositeDisposable() @@ -173,10 +174,10 @@ class MedtronicFragment : DaggerFragment() { private fun setDeviceStatus() { val pumpStatus: MedtronicPumpStatus = MedtronicUtil.getPumpStatus() pumpStatus.rileyLinkServiceState = checkStatusSet(pumpStatus.rileyLinkServiceState, - RileyLinkUtil.getServiceState()) as RileyLinkServiceState? + rileyLinkUtil.getServiceState()) as RileyLinkServiceState? val resourceId = pumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) - val rileyLinkError = RileyLinkUtil.getError() + val rileyLinkError = rileyLinkUtil.getError() medtronic_rl_status.text = when { pumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) @@ -187,7 +188,7 @@ class MedtronicFragment : DaggerFragment() { } medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) - pumpStatus.rileyLinkError = checkStatusSet(pumpStatus.rileyLinkError, RileyLinkUtil.getError()) as RileyLinkError? + pumpStatus.rileyLinkError = checkStatusSet(pumpStatus.rileyLinkError, rileyLinkUtil.getError()) as RileyLinkError? medtronic_errors.text = pumpStatus.rileyLinkError?.let { 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 19e6abebe1..dc5783244d 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 @@ -53,6 +53,7 @@ import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; 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.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ResetRileyLinkConfigurationTask; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; @@ -95,6 +96,7 @@ import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUt public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInterface { private final SP sp; + private final RileyLinkUtil rileyLinkUtil; protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService medtronicService; @@ -125,7 +127,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter ActivePluginProvider activePlugin, SP sp, CommandQueueProvider commandQueue, - FabricPrivacy fabricPrivacy + FabricPrivacy fabricPrivacy, + RileyLinkUtil rileyLinkUtil ) { super(new PluginDescription() // @@ -139,7 +142,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter ); this.plugin = this; - this.rxBus = rxBus; + this.rileyLinkUtil = rileyLinkUtil; this.sp = sp; displayConnectionMessages = false; @@ -177,7 +180,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Override protected void onStart() { super.onStart(); - medtronicUIComm = new MedtronicUIComm(aapsLogger, rxBus, getResourceHelper()); + medtronicUIComm = new MedtronicUIComm(aapsLogger, rxBus, getResourceHelper(), rileyLinkUtil); medtronicHistoryData = new MedtronicHistoryData(aapsLogger, sp, activePlugin); } 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 b4cebbb1cf..4af652e29f 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 @@ -16,6 +16,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class MedtronicUIComm { private final AAPSLogger aapsLogger; + private final RileyLinkUtil rileyLinkUtil; MedtronicCommunicationManager mcmInstance = null; MedtronicUIPostprocessor uiPostprocessor; @@ -23,9 +24,11 @@ public class MedtronicUIComm { public MedtronicUIComm( AAPSLogger aapsLogger, RxBusWrapper rxBus, - ResourceHelper resourceHelper + ResourceHelper resourceHelper, + RileyLinkUtil rileyLinkUtil ) { this.aapsLogger = aapsLogger; + this.rileyLinkUtil = rileyLinkUtil; uiPostprocessor = new MedtronicUIPostprocessor(aapsLogger, rxBus, resourceHelper); } @@ -108,6 +111,6 @@ public class MedtronicUIComm { public void startTunning() { - RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); } } 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 ac07c9a337..2496a919df 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 @@ -69,7 +69,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; public class MedtronicHistoryData { - private static AAPSLogger aapsLogger; + private AAPSLogger aapsLogger; private SP sp; private ActivePluginProvider activePlugin; @@ -138,7 +138,7 @@ public class MedtronicHistoryData { } - private static void showLogs(String header, String data) { + private void showLogs(String header, String data) { if (header != null) { aapsLogger.debug(LTag.PUMP, header); } 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 315aeb0869..5703e1b7ea 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 @@ -211,7 +211,7 @@ public class MedtronicPumpStatus extends PumpStatus { : RileyLinkTargetFrequency.Medtronic_WorldWide; if (targetFrequency != newTargetFrequency) { - RileyLinkUtil.setRileyLinkTargetFrequency(newTargetFrequency); + RileyLinkUtil.getInstance().setRileyLinkTargetFrequency(newTargetFrequency); targetFrequency = newTargetFrequency; targetFrequencyChanged = true; } @@ -311,12 +311,12 @@ public class MedtronicPumpStatus extends PumpStatus { } if (rileyLinkAddressChanged) { - MedtronicUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); + MedtronicUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); rileyLinkAddressChanged = false; } if (encodingChanged) { - RileyLinkUtil.getRileyLinkService().changeRileyLinkEncoding(encodingType); + RileyLinkUtil.getInstance().getRileyLinkService().changeRileyLinkEncoding(encodingType); encodingChanged = false; } } 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 255696aba4..ccaaa8fbbc 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 @@ -87,8 +87,8 @@ public class RileyLinkMedtronicService extends RileyLinkService { rileyLinkServiceData = new RileyLinkServiceData(RileyLinkTargetDevice.MedtronicPump); - RileyLinkUtil.setRileyLinkServiceData(rileyLinkServiceData); - RileyLinkUtil.setTargetDevice(RileyLinkTargetDevice.MedtronicPump); + rileyLinkUtil.setRileyLinkServiceData(rileyLinkServiceData); + rileyLinkUtil.setTargetDevice(RileyLinkTargetDevice.MedtronicPump); setPumpIDString(sp.getString(MedtronicConst.Prefs.PumpSerial, "000000")); @@ -99,7 +99,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { rfspy = new RFSpy(rileyLinkBLE); rfspy.startReader(); - RileyLinkUtil.setRileyLinkBLE(rileyLinkBLE); + rileyLinkUtil.setRileyLinkBLE(rileyLinkBLE); // init rileyLinkCommunicationManager medtronicCommunicationManager = new MedtronicCommunicationManager(context, rfspy); @@ -177,7 +177,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { // PumpInterface - REMOVE public boolean isInitialized() { - return RileyLinkServiceState.isReady(RileyLinkUtil.getRileyLinkServiceData().serviceState); + return RileyLinkServiceState.isReady(rileyLinkUtil.getRileyLinkServiceData().serviceState); } diff --git a/app/src/main/res/layout/rileylink_status_general.xml b/app/src/main/res/layout/rileylink_status_general.xml index e1a841b301..42f5cd5abb 100644 --- a/app/src/main/res/layout/rileylink_status_general.xml +++ b/app/src/main/res/layout/rileylink_status_general.xml @@ -2,7 +2,7 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" - tools:context=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneral"> + tools:context=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment"> + tools:context=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment"> Date: Sun, 26 Apr 2020 17:01:31 +0200 Subject: [PATCH 02/23] remove unused tests --- .../plugins/pump/common/data/PumpStatus.java | 10 +-- .../pump/medtronic/MedtronicPumpPlugin.java | 25 +++---- .../medtronic/driver/MedtronicPumpStatus.java | 67 ++++++++++--------- .../comm/MedtronicConverterUTest.java | 6 +- .../medtronic/data/dto/BasalProfileUTest.java | 9 +-- 5 files changed, 54 insertions(+), 63 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java index fee0ac914d..98b4c5cbcf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java @@ -52,17 +52,17 @@ public abstract class PumpStatus { public int tempBasalRatio = 0; public int tempBasalRemainMin = 0; public Date tempBasalStart; - protected PumpDescription pumpDescription; + //protected PumpDescription pumpDescription; - public PumpStatus(PumpDescription pumpDescription) { - this.pumpDescription = pumpDescription; + public PumpStatus() { + // public PumpStatus(PumpDescription pumpDescription) { + // this.pumpDescription = pumpDescription; - this.initSettings(); +// this.initSettings(); } - public abstract void initSettings(); public void setLastCommunicationToNow() { 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 aa1589f7d9..179934930a 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 @@ -138,7 +138,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .fragmentClass(MedtronicFragment.class.getName()) // .pluginName(R.string.medtronic_name) // .shortName(R.string.medtronic_name_short) // - .preferencesId(R.xml.pref_medtronic).description(R.string.description_pump_medtronic), // + .preferencesId(R.xml.pref_medtronic) + .description(R.string.description_pump_medtronic), // PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy ); @@ -609,17 +610,16 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Override public boolean isThisProfileSet(Profile profile) { - MedtronicPumpStatus mdtPumpStatus = medtronicPumpStatus; - aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitalized=" + mdtPumpStatus.basalProfileStatus); + aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitalized=" + medtronicPumpStatus.basalProfileStatus); if (!isInitialized) return true; - if (mdtPumpStatus.basalProfileStatus == BasalProfileStatus.NotInitialized) { + if (medtronicPumpStatus.basalProfileStatus == BasalProfileStatus.NotInitialized) { // this shouldn't happen, but if there was problem we try again getBasalProfiles(); return isProfileSame(profile); - } else if (mdtPumpStatus.basalProfileStatus == BasalProfileStatus.ProfileChanged) { + } else if (medtronicPumpStatus.basalProfileStatus == BasalProfileStatus.ProfileChanged) { return false; } else { @@ -674,7 +674,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Override public long lastDataTime() { - medtronicPumpStatus; if (medtronicPumpStatus.lastConnection != 0) { return medtronicPumpStatus.lastConnection; @@ -778,14 +777,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter setRefreshButtonEnabled(false); - MedtronicPumpStatus mdtPumpStatus = medtronicPumpStatus; - - if (detailedBolusInfo.insulin > mdtPumpStatus.reservoirRemainingUnits) { + if (detailedBolusInfo.insulin > medtronicPumpStatus.reservoirRemainingUnits) { return new PumpEnactResult(getInjector()) // .success(false) // .enacted(false) // .comment(getResourceHelper().gs(R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin, - mdtPumpStatus.reservoirRemainingUnits, + medtronicPumpStatus.reservoirRemainingUnits, detailedBolusInfo.insulin)); } @@ -1447,14 +1444,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter StringBuilder stringBuilder = new StringBuilder(); - MedtronicPumpStatus pumpStatus = medtronicPumpStatus; - - if (pumpStatus.maxBasal == null) + if (medtronicPumpStatus.maxBasal == null) return null; for (BasalProfileEntry profileEntry : basalProfile.getEntries()) { - if (profileEntry.rate > pumpStatus.maxBasal) { + if (profileEntry.rate > medtronicPumpStatus.maxBasal) { stringBuilder.append(profileEntry.startTime.toString("HH:mm")); stringBuilder.append("="); stringBuilder.append(profileEntry.rate); @@ -1468,8 +1463,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @NonNull private BasalProfile convertProfileToMedtronicProfile(Profile profile) { - MedtronicPumpStatus pumpStatus = medtronicPumpStatus; - PumpType pumpType = pumpStatus.pumpType; BasalProfile basalProfile = new BasalProfile(); 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 6d2faaeef7..9d36b71aed 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 @@ -11,9 +11,7 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; @@ -24,6 +22,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile 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; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; @@ -31,8 +30,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceTyp import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; -import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by andy on 4/28/18. @@ -43,6 +42,7 @@ public class MedtronicPumpStatus extends PumpStatus { private final AAPSLogger aapsLogger; private final ResourceHelper resourceHelper; + private final SP sp; public String errorDescription = null; public String serialNumber; @@ -50,7 +50,7 @@ public class MedtronicPumpStatus extends PumpStatus { public String rileyLinkAddress = null; public Double maxBolus; public Double maxBasal; - public boolean inPreInit = true; + private boolean inPreInit = true; // statuses public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; @@ -89,16 +89,17 @@ public class MedtronicPumpStatus extends PumpStatus { public MedtronicPumpStatus( AAPSLogger aapsLogger, ResourceHelper resourceHelper, - PumpDescription pumpDescription + SP sp ) { - super(pumpDescription); + super(); this.aapsLogger = aapsLogger; this.resourceHelper = resourceHelper; + this.sp = sp; + initSettings(); } - @Override - public void initSettings() { + private void initSettings() { this.activeProfileName = "STD"; this.reservoirRemainingUnits = 75d; @@ -110,7 +111,7 @@ public class MedtronicPumpStatus extends PumpStatus { if (this.medtronicDeviceTypeMap == null) createMedtronicDeviceTypeMap(); - this.lastConnection = SP.getLong(MedtronicConst.Statistics.LastGoodPumpCommunicationTime, 0L); + this.lastConnection = sp.getLong(MedtronicConst.Statistics.LastGoodPumpCommunicationTime, 0L); this.lastDataTime = new LocalDateTime(this.lastConnection); } @@ -147,8 +148,8 @@ public class MedtronicPumpStatus extends PumpStatus { medtronicPumpMap.put("754", PumpType.Medtronic_554_754_Veo); frequencies = new String[2]; - frequencies[0] = MainApp.gs(R.string.key_medtronic_pump_frequency_us_ca); - frequencies[1] = MainApp.gs(R.string.key_medtronic_pump_frequency_worldwide); + frequencies[0] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca); + frequencies[1] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_worldwide); } @@ -164,14 +165,14 @@ public class MedtronicPumpStatus extends PumpStatus { this.errorDescription = "-"; - String serialNr = SP.getString(MedtronicConst.Prefs.PumpSerial, null); + String serialNr = sp.getStringOrNull(MedtronicConst.Prefs.PumpSerial, null); if (serialNr == null) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_serial_not_set); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_not_set); return false; } else { if (!serialNr.matches(regexSN)) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_serial_invalid); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_invalid); return false; } else { if (!serialNr.equals(this.serialNumber)) { @@ -181,21 +182,21 @@ public class MedtronicPumpStatus extends PumpStatus { } } - String pumpType = SP.getString(MedtronicConst.Prefs.PumpType, null); + String pumpType = sp.getStringOrNull(MedtronicConst.Prefs.PumpType, null); if (pumpType == null) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_type_not_set); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_not_set); return false; } else { String pumpTypePart = pumpType.substring(0, 3); if (!pumpTypePart.matches("[0-9]{3}")) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_type_invalid); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_invalid); return false; } else { this.pumpType = medtronicPumpMap.get(pumpTypePart); this.medtronicDeviceType = medtronicDeviceTypeMap.get(pumpTypePart); - this.pumpDescription.setPumpDescription(this.pumpType); + MedtronicPumpPlugin.getPlugin().getPumpDescription().setPumpDescription(this.pumpType); if (pumpTypePart.startsWith("7")) this.reservoirFullUnits = 300; @@ -204,14 +205,14 @@ public class MedtronicPumpStatus extends PumpStatus { } } - String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null); + String pumpFrequency = sp.getStringOrNull(MedtronicConst.Prefs.PumpFrequency, null); if (pumpFrequency == null) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_frequency_not_set); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_not_set); return false; } else { if (!pumpFrequency.equals(frequencies[0]) && !pumpFrequency.equals(frequencies[1])) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_frequency_invalid); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_invalid); return false; } else { this.pumpFrequency = pumpFrequency; @@ -230,15 +231,15 @@ public class MedtronicPumpStatus extends PumpStatus { } } - String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null); + String rileyLinkAddress = sp.getStringOrNull(RileyLinkConst.Prefs.RileyLinkAddress, null); if (rileyLinkAddress == null) { aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: null"); - this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); return false; } else { if (!rileyLinkAddress.matches(regexMac)) { - this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid); + this.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: {}", rileyLinkAddress); } else { if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { @@ -265,7 +266,7 @@ public class MedtronicPumpStatus extends PumpStatus { } - String encodingTypeStr = SP.getString(MedtronicConst.Prefs.Encoding, null); + String encodingTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.Encoding, null); if (encodingTypeStr == null) { return false; @@ -280,7 +281,7 @@ public class MedtronicPumpStatus extends PumpStatus { this.encodingChanged = true; } - String batteryTypeStr = SP.getString(MedtronicConst.Prefs.BatteryType, null); + String batteryTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.BatteryType, null); if (batteryTypeStr == null) return false; @@ -292,9 +293,9 @@ public class MedtronicPumpStatus extends PumpStatus { MedtronicUtil.getInstance().setBatteryType(this.batteryType); } - String bolusDebugEnabled = SP.getString(MedtronicConst.Prefs.BolusDebugEnabled, null); + String bolusDebugEnabled = sp.getStringOrNull(MedtronicConst.Prefs.BolusDebugEnabled, null); - boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(MainApp.gs(R.string.common_on)); + boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(resourceHelper.gs(R.string.common_on)); MedtronicHistoryData.doubleBolusDebug = bolusDebug; @@ -344,7 +345,7 @@ public class MedtronicPumpStatus extends PumpStatus { private double checkParameterValue(int key, String defaultValue, double defaultValueDouble) { double val = 0.0d; - String value = SP.getString(key, defaultValue); + String value = sp.getString(key, defaultValue); try { val = Double.parseDouble(value); @@ -354,7 +355,7 @@ public class MedtronicPumpStatus extends PumpStatus { } if (val > defaultValueDouble) { - SP.putString(key, defaultValue); + sp.putString(key, defaultValue); val = defaultValueDouble; } @@ -394,13 +395,13 @@ public class MedtronicPumpStatus extends PumpStatus { } // Battery type - Map mapByDescription; + private Map mapByDescription; - public BatteryType getBatteryTypeByDescription(String batteryTypeStr) { + private BatteryType getBatteryTypeByDescription(String batteryTypeStr) { if (mapByDescription == null) { mapByDescription = new HashMap<>(); for (BatteryType value : BatteryType.values()) { - mapByDescription.put(MainApp.gs(value.description), value); + mapByDescription.put(resourceHelper.gs(value.description), value); } } if (mapByDescription.containsKey(batteryTypeStr)) { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverterUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverterUTest.java index 67c205fa37..1e10544e88 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverterUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverterUTest.java @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm; import java.util.Map; +import org.junit.Ignore; import org.junit.Test; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; @@ -13,8 +14,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; /** * Created by andy on 1/30/19. */ +@Ignore public class MedtronicConverterUTest { - +/* MedtronicConverter converter = new MedtronicConverter(); @@ -35,5 +37,5 @@ public class MedtronicConverterUTest { // byte[] data = new byte[] { 00 03 00 05 01 00 C8 00 A0 01 01 00 01 00 00 64 01 05 00 14 00 64 01 00 00 }; } - +*/ } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java index 6511117e9b..21b98660d6 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java @@ -23,15 +23,10 @@ import static org.mockito.Mockito.when; //@PrepareForTest({ MainApp.class, DatabaseHelper.class, DateUtil.class, SP.class }) @Ignore public class BasalProfileUTest { - +/* // MainApp mainApp = new MainApp(); @Before public void initMocking() { -// AAPSMocker.mockMainApp(); -// AAPSMocker.mockStrings(); -// AAPSMocker.mockDatabaseHelper(); - -// SPMocker.prepareMock(); PowerMockito.mockStatic(DateUtil.class); when(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()); @@ -161,5 +156,5 @@ public class BasalProfileUTest { // 1.800 1.600 1.400 1.450 1.450 1.450 1.250 1.250 0.950 0.950 1.150 1.150 1.250 0.950 0.950 0.950 0.650 0.650 // 0.650 0.650 0.650 0.500 0.500 0.500 } - +*/ } From 0d063ca73f6b0f73794384b2d1a6fc0b7803d2bd Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 26 Apr 2020 22:47:13 +0200 Subject: [PATCH 03/23] MDT refactor pass 2 --- .../dependencyInjection/AppComponent.kt | 9 +++++ .../dependencyInjection/AppModule.kt | 9 +++++ .../pump/common/PumpPluginAbstract.java | 5 ++- .../plugins/pump/common/data/PumpStatus.java | 16 +++----- .../RileyLinkCommunicationManager.java | 9 ++++- .../service/RileyLinkBroadcastReceiver.java | 10 +++-- .../tasks/DiscoverGattServicesTask.java | 7 +++- .../tasks/InitializePumpManagerTask.java | 9 +++-- .../hw/rileylink/service/tasks/PumpTask.java | 9 +++-- .../ResetRileyLinkConfigurationTask.java | 24 +++++++++--- .../rileylink/service/tasks/ServiceTask.java | 10 ++++- .../service/tasks/WakeAndTuneTask.java | 23 +++++++++--- .../pump/medtronic/MedtronicPumpPlugin.java | 37 +++++++++++++------ .../comm/MedtronicCommunicationManager.java | 7 ++-- .../medtronic/driver/MedtronicPumpStatus.java | 2 +- .../service/RileyLinkMedtronicService.java | 11 ++---- .../pump/medtronic/util/MedtronicUtil.java | 17 --------- .../plugins/treatments/TreatmentService.java | 5 ++- .../plugins/treatments/TreatmentsPlugin.java | 4 +- 19 files changed, 137 insertions(+), 86 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index ccb6b2eb46..c3de19c59e 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -29,6 +29,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.commands.* @@ -185,6 +186,14 @@ interface AppComponent : AndroidInjector { fun injectGraphData(graphData: GraphData) + //Medtronic + fun injectServiceTask(serviceTask: ServiceTask) + fun injectPumpTask(pumpTask: PumpTask) + fun injectDiscoverGattServicesTask(discoverGattServicesTask: DiscoverGattServicesTask) + fun injectInitializePumpManagerTask(initializePumpManagerTask: InitializePumpManagerTask) + fun injectResetRileyLinkConfigurationTask(resetRileyLinkConfigurationTask: ResetRileyLinkConfigurationTask) + fun injectWakeAndTuneTask(wakeAndTuneTask: WakeAndTuneTask) + @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 1dd34b8100..fdc6d680bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -46,6 +46,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.commands.* @@ -278,6 +279,14 @@ open class AppModule { @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector + // Medtronic + @ContributesAndroidInjector fun serviceTaskProvider(): ServiceTask + @ContributesAndroidInjector fun pumpTaskProvider(): PumpTask + @ContributesAndroidInjector fun discoverGattServicesTaskProvider(): DiscoverGattServicesTask + @ContributesAndroidInjector fun initializePumpManagerTaskProvider(): InitializePumpManagerTask + @ContributesAndroidInjector fun resetRileyLinkConfigurationTaskProvider(): ResetRileyLinkConfigurationTask + @ContributesAndroidInjector fun wakeAndTuneTaskProvider(): WakeAndTuneTask + @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider 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 008d2daac7..70edbcec19 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 @@ -109,7 +109,8 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public abstract void initPumpStatusData(); - + public abstract void resetRileyLinkConfiguration(); + public abstract void doTuneUpDevice(); @Override protected void onStart() { @@ -125,7 +126,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI disposable.add(rxBus .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) - .subscribe(event -> context.unbindService(serviceConnection), exception -> fabricPrivacy.logException(exception)) + .subscribe(event -> context.unbindService(serviceConnection), fabricPrivacy::logException) ); onStartCustomActions(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java index 98b4c5cbcf..8f241feb3d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java @@ -1,13 +1,11 @@ package info.nightscout.androidaps.plugins.pump.common.data; -import org.joda.time.LocalDateTime; - import java.util.Date; import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.plugins.pump.common.defs.PumpStatusType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; +import info.nightscout.androidaps.utils.DateUtil; /** * Created by andy on 4/28/18. @@ -16,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; public abstract class PumpStatus { // connection - public LocalDateTime lastDataTime; + public long lastDataTime; public long lastConnection = 0L; public long previousConnection = 0L; // here should be stored last connection of previous session (so needs to be // read before lastConnection is modified for first time). @@ -55,18 +53,16 @@ public abstract class PumpStatus { //protected PumpDescription pumpDescription; - public PumpStatus() { - // public PumpStatus(PumpDescription pumpDescription) { - // this.pumpDescription = pumpDescription; + public PumpStatus() { + // public PumpStatus(PumpDescription pumpDescription) { + // this.pumpDescription = pumpDescription; // this.initSettings(); } - - public void setLastCommunicationToNow() { - this.lastDataTime = LocalDateTime.now(); + this.lastDataTime = DateUtil.now(); this.lastConnection = System.currentTimeMillis(); } 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 e16f686db4..8d5c9f9319 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 @@ -3,6 +3,9 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; @@ -36,6 +39,7 @@ public abstract class RileyLinkCommunicationManager { private static final int SCAN_TIMEOUT = 1500; private static final int ALLOWED_PUMP_UNREACHABLE = 10 * 60 * 1000; // 10 minutes + protected final HasAndroidInjector injector; protected final RFSpy rfspy; protected int receiverDeviceAwakeForMinutes = 1; // override this in constructor of specific implementation protected String receiverDeviceID; // String representation of receiver device (ex. Pump (xxxxxx) or Pod (yyyyyy)) @@ -49,7 +53,8 @@ public abstract class RileyLinkCommunicationManager { private int timeoutCount = 0; - public RileyLinkCommunicationManager(RFSpy rfspy) { + public RileyLinkCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { + this.injector = injector; this.rfspy = rfspy; this.rileyLinkServiceData = RileyLinkUtil.getInstance().getRileyLinkServiceData(); RileyLinkUtil.getInstance().setRileyLinkCommunicationManager(this); @@ -107,7 +112,7 @@ public abstract class RileyLinkCommunicationManager { if (diff > ALLOWED_PUMP_UNREACHABLE) { LOG.warn("We reached max time that Pump can be unreachable. Starting Tuning."); - ServiceTaskExecutor.startTask(new WakeAndTuneTask()); + ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); timeoutCount = 0; } } 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 f250d1480a..2af0eccfdb 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 @@ -21,6 +21,7 @@ import java.util.Map; import javax.inject.Inject; import dagger.android.DaggerBroadcastReceiver; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; @@ -42,6 +43,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; */ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { + @Inject HasAndroidInjector injector; @Inject RileyLinkUtil rileyLinkUtil; @Inject SP sp; @@ -171,7 +173,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; - ServiceTask task = new InitializePumpManagerTask(rileyLinkUtil.getTargetDevice()); + ServiceTask task = new InitializePumpManagerTask(injector, rileyLinkUtil.getTargetDevice()); ServiceTaskExecutor.startTask(task); if (isLoggingEnabled()) LOG.info("Announcing RileyLink open For business"); @@ -205,7 +207,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { if (action.equals(RileyLinkConst.Intents.BluetoothConnected)) { if (isLoggingEnabled()) LOG.debug("Bluetooth - Connected"); - ServiceTaskExecutor.startTask(new DiscoverGattServicesTask()); + ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(injector)); return true; @@ -214,7 +216,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { LOG.debug("Bluetooth - Reconnecting"); serviceInstance.bluetoothInit(); - ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(true)); + ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(injector, true)); return true; } else { @@ -229,7 +231,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { if (this.broadcastIdentifiers.get("TuneUp").contains(action)) { if (serviceInstance.getRileyLinkTargetDevice().isTuneUpEnabled()) { - ServiceTaskExecutor.startTask(new WakeAndTuneTask()); + ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); } return true; } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java index a588d300fc..42b850d4f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; /** @@ -10,11 +11,13 @@ public class DiscoverGattServicesTask extends ServiceTask { public boolean needToConnect = false; - public DiscoverGattServicesTask() { + public DiscoverGattServicesTask(HasAndroidInjector injector) { + super(injector); } - public DiscoverGattServicesTask(boolean needToConnect) { + public DiscoverGattServicesTask(HasAndroidInjector injector, boolean needToConnect) { + super(injector); this.needToConnect = needToConnect; } 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 314e4323ef..0bf78f08c1 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,7 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.task import org.slf4j.Logger; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; @@ -23,14 +24,14 @@ public class InitializePumpManagerTask extends ServiceTask { private RileyLinkTargetDevice targetDevice; private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - public InitializePumpManagerTask(RileyLinkTargetDevice targetDevice) { - super(); + public InitializePumpManagerTask(HasAndroidInjector injector, RileyLinkTargetDevice targetDevice) { + super(injector); this.targetDevice = targetDevice; } - public InitializePumpManagerTask(ServiceTransport transport) { - super(transport); + public InitializePumpManagerTask(HasAndroidInjector injector, ServiceTransport transport) { + super(injector, transport); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/PumpTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/PumpTask.java index c307a43590..66aeb7ae07 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/PumpTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/PumpTask.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; /** @@ -7,12 +8,12 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data. */ public class PumpTask extends ServiceTask { - public PumpTask() { - super(); + public PumpTask(HasAndroidInjector injector) { + super(injector); } - public PumpTask(ServiceTransport transport) { - super(transport); + public PumpTask(HasAndroidInjector injector, ServiceTransport transport) { + super(injector, transport); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java index cc17f81b45..fb738a241c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java @@ -1,6 +1,13 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState; @@ -11,25 +18,30 @@ import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtro */ public class ResetRileyLinkConfigurationTask extends PumpTask { + @Inject ActivePluginProvider activePlugin; + @Inject RxBusWrapper rxBus; + private static final String TAG = "ResetRileyLinkTask"; - public ResetRileyLinkConfigurationTask() { + public ResetRileyLinkConfigurationTask(HasAndroidInjector injector) { + super(injector); } - public ResetRileyLinkConfigurationTask(ServiceTransport transport) { - super(transport); + public ResetRileyLinkConfigurationTask(HasAndroidInjector injector, ServiceTransport transport) { + super(injector, transport); } @Override public void run() { - RxBus.Companion.getINSTANCE().send(new EventRefreshButtonState(false)); + PumpPluginAbstract pump = (PumpPluginAbstract) activePlugin.getActivePump(); + rxBus.send(new EventRefreshButtonState(false)); MedtronicPumpPlugin.isBusy = true; - RileyLinkMedtronicService.getInstance().resetRileyLinkConfiguration(); + pump.resetRileyLinkConfiguration(); MedtronicPumpPlugin.isBusy = false; - RxBus.Companion.getINSTANCE().send(new EventRefreshButtonState(true)); + rxBus.send(new EventRefreshButtonState(true)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java index e287b63e17..178c5185f1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; /** @@ -10,14 +11,19 @@ public class ServiceTask implements Runnable { private static final String TAG = "ServiceTask(base)"; public boolean completed = false; protected ServiceTransport mTransport; + protected HasAndroidInjector injector; - public ServiceTask() { + public ServiceTask(HasAndroidInjector injector) { + this.injector = injector; + injector.androidInjector().inject(this); init(new ServiceTransport()); } - public ServiceTask(ServiceTransport transport) { + public ServiceTask(HasAndroidInjector injector, ServiceTransport transport) { + this.injector = injector; + injector.androidInjector().inject(this); init(transport); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java index 1035d7d2d8..11a6de7a3d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java @@ -1,6 +1,12 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState; @@ -11,24 +17,29 @@ import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtro */ public class WakeAndTuneTask extends PumpTask { + @Inject ActivePluginProvider activePlugin; + @Inject RxBusWrapper rxBus; + private static final String TAG = "WakeAndTuneTask"; - public WakeAndTuneTask() { + public WakeAndTuneTask(HasAndroidInjector injector) { + super(injector); } - public WakeAndTuneTask(ServiceTransport transport) { - super(transport); + public WakeAndTuneTask(HasAndroidInjector injector, ServiceTransport transport) { + super(injector, transport); } @Override public void run() { - RxBus.Companion.getINSTANCE().send(new EventRefreshButtonState(false)); + PumpPluginAbstract pump = (PumpPluginAbstract) activePlugin.getActivePump(); + rxBus.send(new EventRefreshButtonState(false)); MedtronicPumpPlugin.isBusy = true; - RileyLinkMedtronicService.getInstance().doTuneUpDevice(); + pump.doTuneUpDevice(); MedtronicPumpPlugin.isBusy = false; - RxBus.Companion.getINSTANCE().send(new EventRefreshButtonState(true)); + rxBus.send(new EventRefreshButtonState(true)); } } 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 179934930a..21198a2a37 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 @@ -8,6 +8,7 @@ import android.os.IBinder; import android.os.SystemClock; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import org.joda.time.LocalDateTime; @@ -100,7 +101,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final MedtronicPumpStatus medtronicPumpStatus; protected static MedtronicPumpPlugin plugin = null; - private RileyLinkMedtronicService medtronicService; + private RileyLinkMedtronicService rileyLinkMedtronicService; private MedtronicUIComm medtronicUIComm; // variables for handling statuses and history @@ -156,13 +157,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter public void onServiceDisconnected(ComponentName name) { aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is disconnected"); - medtronicService = null; + rileyLinkMedtronicService = null; } public void onServiceConnected(ComponentName name, IBinder service) { aapsLogger.debug(LTag.PUMP, "RileyLinkMedtronicService is connected"); RileyLinkMedtronicService.LocalBinder mLocalBinder = (RileyLinkMedtronicService.LocalBinder) service; - medtronicService = mLocalBinder.getServiceInstance(); + rileyLinkMedtronicService = mLocalBinder.getServiceInstance(); new Thread(() -> { @@ -213,7 +214,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter medtronicUtil.setPumpStatus(medtronicPumpStatus); medtronicPumpStatus.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); - medtronicPumpStatus.lastDataTime = new LocalDateTime(medtronicPumpStatus.lastConnection); + medtronicPumpStatus.lastDataTime = medtronicPumpStatus.lastConnection; medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection; medtronicPumpStatus.refreshConfiguration(); @@ -234,6 +235,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } + @Override + public void resetRileyLinkConfiguration() { + rileyLinkMedtronicService.resetRileyLinkConfiguration(); + } + + @Override public void doTuneUpDevice() { + rileyLinkMedtronicService.doTuneUpDevice(); + } + private void migrateSettings() { if ("US (916 MHz)".equals(sp.getString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)"))) { @@ -306,9 +316,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter // Pump Plugin private boolean isServiceSet() { - return medtronicService != null; + return rileyLinkMedtronicService != null; } + @Deprecated + @Nullable + public RileyLinkMedtronicService getRileyLinkMedtronicService() { + return rileyLinkMedtronicService; + } @Override public boolean isInitialized() { @@ -373,7 +388,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter public boolean isConnected() { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnected"); - return isServiceSet() && medtronicService.isInitialized(); + return isServiceSet() && rileyLinkMedtronicService.isInitialized(); } @@ -381,7 +396,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter public boolean isConnecting() { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "MedtronicPumpPlugin::isConnecting"); - return !isServiceSet() || !medtronicService.isInitialized(); + return !isServiceSet() || !rileyLinkMedtronicService.isInitialized(); } @@ -581,7 +596,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (errorCount >= 5) { aapsLogger.error("Number of error counts was 5 or more. Starting tunning."); setRefreshButtonEnabled(true); - ServiceTaskExecutor.startTask(new WakeAndTuneTask()); + ServiceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); return; } @@ -1518,7 +1533,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter case WakeUpAndTune: { if (medtronicUtil.getPumpStatus().verifyConfiguration()) { - ServiceTaskExecutor.startTask(new WakeAndTuneTask()); + ServiceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); } else { Intent i = new Intent(context, ErrorHelperActivity.class); i.putExtra("soundid", R.raw.boluserror); @@ -1538,7 +1553,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter break; case ResetRileyLinkConfiguration: { - ServiceTaskExecutor.startTask(new ResetRileyLinkConfigurationTask()); + ServiceTaskExecutor.startTask(new ResetRileyLinkConfigurationTask(getInjector())); } break; @@ -1557,7 +1572,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } - public void setEnableCustomAction(MedtronicCustomActionType customAction, boolean isEnabled) { + private void setEnableCustomAction(MedtronicCustomActionType customAction, boolean isEnabled) { if (customAction == MedtronicCustomActionType.ClearBolusBlock) { this.customActionClearBolusBlock.setEnabled(isEnabled); 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 e4b382c1f6..16b9ad2a32 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 java.util.GregorianCalendar; import java.util.List; import java.util.Map; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; @@ -70,8 +71,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private boolean doWakeUpBeforeCommand = true; - public MedtronicCommunicationManager(RFSpy rfspy) { - super(rfspy); + public MedtronicCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { + super(injector, rfspy); medtronicCommunicationManager = this; this.medtronicConverter = new MedtronicConverter(); this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder(); @@ -143,7 +144,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager long diff = System.currentTimeMillis() - MedtronicUtil.getInstance().getPumpStatus().lastConnection; if (diff > RILEYLINK_TIMEOUT) { - ServiceTaskExecutor.startTask(new WakeAndTuneTask()); + ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); } } 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 9d36b71aed..2b43890c06 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 @@ -112,7 +112,7 @@ public class MedtronicPumpStatus extends PumpStatus { createMedtronicDeviceTypeMap(); this.lastConnection = sp.getLong(MedtronicConst.Statistics.LastGoodPumpCommunicationTime, 0L); - this.lastDataTime = new LocalDateTime(this.lastConnection); + this.lastDataTime = this.lastConnection; } 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 b51d24b317..e54debd30c 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 @@ -9,6 +9,7 @@ import android.os.IBinder; import javax.inject.Inject; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; @@ -36,11 +37,11 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; */ public class RileyLinkMedtronicService extends RileyLinkService { + @Inject HasAndroidInjector injector; @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicUtil medtronicUtil; @Deprecated // TEDO remove this reference - private static RileyLinkMedtronicService instance; private static ServiceTask currentTask = null; // cache of most recently received set of pump history pages. Probably shouldn't be here. @@ -51,12 +52,6 @@ public class RileyLinkMedtronicService extends RileyLinkService { public RileyLinkMedtronicService() { super(); - instance = this; - } - - - public static RileyLinkMedtronicService getInstance() { - return instance; } @@ -101,7 +96,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { rileyLinkUtil.setRileyLinkBLE(rileyLinkBLE); // init rileyLinkCommunicationManager - medtronicCommunicationManager = new MedtronicCommunicationManager(rfspy); + medtronicCommunicationManager = new MedtronicCommunicationManager(injector, rfspy); aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed"); medtronicUtil.setMedtronicService(this); 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 0409a73421..ad97583cec 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 @@ -72,7 +72,6 @@ public class MedtronicUtil { @Inject public MedtronicUtil( - Context context, AAPSLogger aapsLogger, RxBusWrapper rxBus, RileyLinkUtil rileyLinkUtil @@ -93,16 +92,6 @@ public class MedtronicUtil { return instance; } - public Gson getGsonInstance() { - return gsonInstance; - } - - - public Gson getGsonInstanceCore() { - return gsonInstanceCore; - } - - public LocalTime getTimeFrom30MinInterval(int interval) { if (interval % 2 == 0) { return new LocalTime(interval / 2, 0); @@ -122,12 +111,6 @@ public class MedtronicUtil { return k; } - public boolean isMedtronicPump() { - return MedtronicPumpPlugin.getPlugin().isEnabled(PluginType.PUMP); - //return ConfigBuilderPlugin.getPlugin().getActivePump().deviceID().equals("Medtronic"); - } - - public byte[] getByteArrayFromUnsignedShort(int shortValue, boolean returnFixedSize) { byte highByte = (byte) (shortValue >> 8 & 0xFF); byte lowByte = (byte) (shortValue & 0xFF); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index af9aa31ac4..6e250bd851 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -40,6 +40,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -265,9 +266,9 @@ public class TreatmentService extends OrmLiteBaseService { if (treatment != null) { if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicUtil.getInstance().isMedtronicPump()); + log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicPumpPlugin.getPlugin().isEnabled()); - if (!MedtronicUtil.getInstance().isMedtronicPump()) + if (!MedtronicPumpPlugin.getPlugin().isEnabled()) createOrUpdate(treatment); else createOrUpdateMedtronic(treatment, true); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 0bac0d9724..f5a514b24e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -300,13 +300,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface long time = System.currentTimeMillis(); synchronized (treatments) { - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().create().toJson(treatments)); + getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); for (Treatment t : treatments) { if (t.date <= time && t.date >= fromTimestamp) in5minback.add(t); } - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().create().toJson(in5minback)); + getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); return in5minback; } } From 331c1c3ab5fefc60ffda283ffa84435a933f3395 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 26 Apr 2020 23:52:29 +0200 Subject: [PATCH 04/23] MDT refactor pass 3 --- .../dependencyInjection/AppComponent.kt | 6 ++ .../dependencyInjection/AppModule.kt | 6 ++ .../dialog/RileyLinkBLEScanActivity.java | 4 +- .../RileyLinkCommunicationManager.java | 56 ++++++-------- .../RileyLinkStatusGeneralFragment.java | 15 ++-- .../pump/medtronic/MedtronicFragment.kt | 75 +++++++++---------- .../pump/medtronic/MedtronicPumpPlugin.java | 23 +++--- .../comm/MedtronicCommunicationManager.java | 22 +++--- .../medtronic/comm/ui/MedtronicUIComm.java | 21 ++++-- .../comm/ui/MedtronicUIPostprocessor.java | 51 +++++++------ .../medtronic/comm/ui/MedtronicUITask.java | 21 ++++-- .../pump/medtronic/data/dto/BasalProfile.java | 4 +- .../medtronic/driver/MedtronicPumpStatus.java | 6 +- .../service/RileyLinkMedtronicService.java | 14 +--- .../pump/medtronic/util/MedtronicUtil.java | 14 ++-- 15 files changed, 173 insertions(+), 165 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index c3de19c59e..db7cbba831 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -29,7 +29,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* +import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager +import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.commands.* @@ -187,6 +190,9 @@ interface AppComponent : AndroidInjector { fun injectGraphData(graphData: GraphData) //Medtronic + fun injectRileyLinkCommunicationManager(rileyLinkCommunicationManager: RileyLinkCommunicationManager) + fun injectMedtronicCommunicationManager(medtronicCommunicationManager: MedtronicCommunicationManager) + fun injectMedtronicUITask(medtronicUITask: MedtronicUITask) fun injectServiceTask(serviceTask: ServiceTask) fun injectPumpTask(pumpTask: PumpTask) fun injectDiscoverGattServicesTask(discoverGattServicesTask: DiscoverGattServicesTask) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index fdc6d680bc..5273cb61d5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -46,7 +46,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* +import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager +import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.commands.* @@ -280,6 +283,9 @@ open class AppModule { @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector // Medtronic + @ContributesAndroidInjector fun rileyLinkCommunicationManagerProvider(): RileyLinkCommunicationManager + @ContributesAndroidInjector fun medtronicCommunicationManagerProvider(): MedtronicCommunicationManager + @ContributesAndroidInjector fun medtronicUITaskProvider(): MedtronicUITask @ContributesAndroidInjector fun serviceTaskProvider(): ServiceTask @ContributesAndroidInjector fun pumpTaskProvider(): PumpTask @ContributesAndroidInjector fun discoverGattServicesTaskProvider(): DiscoverGattServicesTask diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java index a0cba01cc9..389a122ca6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java @@ -62,6 +62,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { @Inject ResourceHelper resourceHelper; @Inject RileyLinkUtil rileyLinkUtil; @Inject MedtronicUtil medtronicUtil; + @Inject MedtronicPumpStatus medtronicPumpStatus; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 30241; // arbitrary. private static final int REQUEST_ENABLE_BT = 30242; // arbitrary @@ -112,8 +113,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { rileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress); - MedtronicPumpStatus pumpStatus = medtronicUtil.getPumpStatus(); - pumpStatus.verifyConfiguration(); // force reloading of address + medtronicPumpStatus.verifyConfiguration(); // force reloading of address rxBus.send(new EventMedtronicPumpConfigurationChanged()); 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 8d5c9f9319..35cfd48a5b 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 @@ -24,8 +24,9 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * This is abstract class for RileyLink Communication, this one needs to be extended by specific "Pump" class. @@ -34,6 +35,9 @@ import info.nightscout.androidaps.utils.SP; */ public abstract class RileyLinkCommunicationManager { + @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject protected SP sp; + private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); private static final int SCAN_TIMEOUT = 1500; @@ -44,7 +48,7 @@ public abstract class RileyLinkCommunicationManager { protected int receiverDeviceAwakeForMinutes = 1; // override this in constructor of specific implementation protected String receiverDeviceID; // String representation of receiver device (ex. Pump (xxxxxx) or Pod (yyyyyy)) protected long lastGoodReceiverCommunicationTime = 0; - protected PumpStatus pumpStatus; + // protected PumpStatus pumpStatus; protected RileyLinkServiceData rileyLinkServiceData; private long nextWakeUpRequired = 0L; @@ -55,17 +59,13 @@ public abstract class RileyLinkCommunicationManager { public RileyLinkCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { this.injector = injector; + injector.androidInjector().inject(this); this.rfspy = rfspy; this.rileyLinkServiceData = RileyLinkUtil.getInstance().getRileyLinkServiceData(); RileyLinkUtil.getInstance().setRileyLinkCommunicationManager(this); - - configurePumpSpecificSettings(); } - protected abstract void configurePumpSpecificSettings(); - - // All pump communications go through this function. public E sendAndListen(RLMessage msg, int timeout_ms, Class clazz) throws RileyLinkCommunicationException { @@ -92,7 +92,7 @@ public abstract class RileyLinkCommunicationManager { } RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(msg.getTxData()), - (byte)0, (byte)repeatCount, (byte)0, (byte)0, timeout_ms, (byte)retryCount, extendPreamble_ms); + (byte) 0, (byte) repeatCount, (byte) 0, (byte) 0, timeout_ms, (byte) retryCount, extendPreamble_ms); RadioResponse radioResponse = rfSpyResponse.getRadioResponse(); E response = createResponseMessage(radioResponse.getPayload(), clazz); @@ -108,7 +108,7 @@ public abstract class RileyLinkCommunicationManager { if (hasTunning()) { timeoutCount++; - long diff = System.currentTimeMillis() - pumpStatus.lastConnection; + long diff = System.currentTimeMillis() - getPumpStatus().lastConnection; if (diff > ALLOWED_PUMP_UNREACHABLE) { LOG.warn("We reached max time that Pump can be unreachable. Starting Tuning."); @@ -166,8 +166,8 @@ public abstract class RileyLinkCommunicationManager { 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); + RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, + (byte) 0, (byte) 0, 25000, (byte) 0); if (isLogEnabled()) LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); @@ -248,8 +248,8 @@ public abstract class RileyLinkCommunicationManager { for (int j = 0; j < tries; j++) { byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); - RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte)0, (byte)0, - (byte)0, (byte)0, 1250, (byte)0); + RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (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()) { @@ -281,7 +281,7 @@ public abstract class RileyLinkCommunicationManager { trial.tries++; } sumRSSI += -99.0 * (trial.tries - trial.successes); - trial.averageRSSI2 = (double)(sumRSSI) / (double)(trial.tries); + trial.averageRSSI2 = (double) (sumRSSI) / (double) (trial.tries); trial.calculateAverage(); @@ -296,7 +296,7 @@ public abstract class RileyLinkCommunicationManager { FrequencyTrial one = results.trials.get(k); stringBuilder.append(String.format("Scan Result[%s]: Freq=%s, avg RSSI = %s\n", "" + k, "" - + one.frequencyMHz, "" + one.averageRSSI + ", RSSIs =" + one.rssiList)); + + one.frequencyMHz, "" + one.averageRSSI + ", RSSIs =" + one.rssiList)); } LOG.info(stringBuilder.toString()); @@ -338,7 +338,7 @@ public abstract class RileyLinkCommunicationManager { // RLMessage msg = makeRLMessage(RLMessageType.ReadSimpleData); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); RadioPacket pkt = new RadioPacket(pumpMsgContent); - RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte)0, (byte)0, (byte)0, (byte)0, SCAN_TIMEOUT, (byte)0); + RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, SCAN_TIMEOUT, (byte) 0); if (resp.wasTimeout()) { LOG.warn("tune_tryFrequency: no pump response at frequency {}", freqMHz); } else if (resp.looksLikeRadioPacket()) { @@ -350,8 +350,8 @@ public abstract class RileyLinkCommunicationManager { LOG.warn("tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz); return calculateRssi(radioResponse.rssi); } else { - LOG.warn("tune_tryFrequency: invalid radio response:" - + ByteUtil.shortHexString(radioResponse.getPayload())); + LOG.warn("tune_tryFrequency: invalid radio response:" + + ByteUtil.shortHexString(radioResponse.getPayload())); } } catch (RileyLinkCommunicationException e) { @@ -373,7 +373,7 @@ public abstract class RileyLinkCommunicationManager { // Try again at larger step size stepsize += 0.05; } else { - if ((int)(evenBetterFrequency * 100) == (int)(betterFrequency * 100)) { + if ((int) (evenBetterFrequency * 100) == (int) (betterFrequency * 100)) { // value did not change, so we're done. break; } @@ -426,17 +426,15 @@ public abstract class RileyLinkCommunicationManager { protected void rememberLastGoodDeviceCommunicationTime() { lastGoodReceiverCommunicationTime = System.currentTimeMillis(); - SP.putLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, lastGoodReceiverCommunicationTime); - if(pumpStatus != null) { - pumpStatus.setLastCommunicationToNow(); - } + sp.putLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, lastGoodReceiverCommunicationTime); + getPumpStatus().setLastCommunicationToNow(); } private long getLastGoodReceiverCommunicationTime() { // If we have a value of zero, we need to load from prefs. if (lastGoodReceiverCommunicationTime == 0L) { - lastGoodReceiverCommunicationTime = SP.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); + lastGoodReceiverCommunicationTime = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); // Might still be zero, but that's fine. } double minutesAgo = (System.currentTimeMillis() - lastGoodReceiverCommunicationTime) / (1000.0 * 60.0); @@ -445,12 +443,6 @@ public abstract class RileyLinkCommunicationManager { return lastGoodReceiverCommunicationTime; } - - public PumpStatus getPumpStatus() { - return pumpStatus; - } - - public void clearNotConnectedCount() { if (rfspy != null) { rfspy.notConnectedCount = 0; @@ -461,7 +453,5 @@ public abstract class RileyLinkCommunicationManager { return L.isEnabled(L.PUMPCOMM); } - public void setPumpStatus(PumpStatus pumpStatus) { - this.pumpStatus = pumpStatus; - } + public abstract PumpStatus getPumpStatus(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index 338966191d..b5dc772d80 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java @@ -13,7 +13,6 @@ import java.util.Locale; import javax.inject.Inject; import dagger.android.support.DaggerFragment; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; @@ -24,6 +23,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.Riley import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by andy on 5/19/18. @@ -33,6 +33,8 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re @Inject RileyLinkUtil rileyLinkUtil; @Inject MedtronicUtil medtronicUtil; + @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject ResourceHelper resourceHelper; TextView connectionStatus; TextView configuredAddress; @@ -100,15 +102,15 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re RileyLinkTargetDevice targetDevice = rileyLinkUtil.getTargetDevice(); if (rileyLinkUtil.getServiceState() == null) - this.connectionStatus.setText(MainApp.gs(RileyLinkServiceState.NotStarted.getResourceId(targetDevice))); + this.connectionStatus.setText(resourceHelper.gs(RileyLinkServiceState.NotStarted.getResourceId(targetDevice))); else - this.connectionStatus.setText(MainApp.gs(rileyLinkUtil.getServiceState().getResourceId(targetDevice))); + this.connectionStatus.setText(resourceHelper.gs(rileyLinkUtil.getServiceState().getResourceId(targetDevice))); if (rileyLinkServiceData != null) { this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress); this.connectionError.setText(rileyLinkServiceData.errorCode == null ? // "-" - : MainApp.gs(rileyLinkServiceData.errorCode.getResourceId(targetDevice))); + : resourceHelper.gs(rileyLinkServiceData.errorCode.getResourceId(targetDevice))); RileyLinkFirmwareVersion firmwareVersion = rileyLinkServiceData.versionCC110; @@ -123,13 +125,12 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re } // TODO add handling for Omnipod pump status - MedtronicPumpStatus medtronicPumpStatus = medtronicUtil.getPumpStatus(); if (medtronicPumpStatus != null) { - this.deviceType.setText(MainApp.gs(RileyLinkTargetDevice.MedtronicPump.getResourceId())); + this.deviceType.setText(resourceHelper.gs(RileyLinkTargetDevice.MedtronicPump.getResourceId())); this.deviceModel.setText(medtronicPumpStatus.pumpType.getDescription()); this.serialNumber.setText(medtronicPumpStatus.serialNumber); - this.pumpFrequency.setText(MainApp.gs(medtronicPumpStatus.pumpFrequency.equals("medtronic_pump_frequency_us_ca") ? R.string.medtronic_pump_frequency_us_ca : R.string.medtronic_pump_frequency_worldwide)); + this.pumpFrequency.setText(resourceHelper.gs(medtronicPumpStatus.pumpFrequency.equals("medtronic_pump_frequency_us_ca") ? R.string.medtronic_pump_frequency_us_ca : R.string.medtronic_pump_frequency_worldwide)); // TODO extend when Omnipod used diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index fe600dfdd4..b14412d7c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -59,6 +59,7 @@ class MedtronicFragment : DaggerFragment() { @Inject lateinit var warnColors: WarnColors @Inject lateinit var rileyLinkUtil: RileyLinkUtil @Inject lateinit var medtronicUtil: MedtronicUtil + @Inject lateinit var medtronicPumpStatus: MedtronicPumpStatus private var disposable: CompositeDisposable = CompositeDisposable() @@ -87,7 +88,7 @@ class MedtronicFragment : DaggerFragment() { medtronic_pump_status.text = "{fa-bed}" medtronic_history.setOnClickListener { - if (medtronicUtil.getPumpStatus().verifyConfiguration()) { + if (medtronicPumpStatus.verifyConfiguration()) { startActivity(Intent(context, MedtronicHistoryActivity::class.java)) } else { displayNotConfiguredDialog() @@ -95,7 +96,7 @@ class MedtronicFragment : DaggerFragment() { } medtronic_refresh.setOnClickListener { - if (!medtronicUtil.getPumpStatus().verifyConfiguration()) { + if (!medtronicPumpStatus.verifyConfiguration()) { displayNotConfiguredDialog() } else { medtronic_refresh.isEnabled = false @@ -109,7 +110,7 @@ class MedtronicFragment : DaggerFragment() { } medtronic_stats.setOnClickListener { - if (medtronicUtil.getPumpStatus().verifyConfiguration()) { + if (medtronicPumpStatus.verifyConfiguration()) { startActivity(Intent(context, RileyLinkStatusActivity::class.java)) } else { displayNotConfiguredDialog() @@ -149,7 +150,7 @@ class MedtronicFragment : DaggerFragment() { .observeOn(AndroidSchedulers.mainThread()) .subscribe({ aapsLogger.debug(LTag.PUMP, "EventMedtronicPumpConfigurationChanged triggered") - medtronicUtil.getPumpStatus().verifyConfiguration() + medtronicPumpStatus.verifyConfiguration() updateGUI() }, { fabricPrivacy.logException(it) }) disposable += rxBus @@ -173,33 +174,32 @@ class MedtronicFragment : DaggerFragment() { @Synchronized private fun setDeviceStatus() { - val pumpStatus: MedtronicPumpStatus = medtronicUtil.getPumpStatus() - pumpStatus.rileyLinkServiceState = checkStatusSet(pumpStatus.rileyLinkServiceState, + medtronicPumpStatus.rileyLinkServiceState = checkStatusSet(medtronicPumpStatus.rileyLinkServiceState, rileyLinkUtil.getServiceState()) as RileyLinkServiceState? - val resourceId = pumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) + val resourceId = medtronicPumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) val rileyLinkError = rileyLinkUtil.getError() medtronic_rl_status.text = when { - pumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) - pumpStatus.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) - pumpStatus.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) - pumpStatus.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) + medtronicPumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) + medtronicPumpStatus.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) + medtronicPumpStatus.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) + medtronicPumpStatus.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) } medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) - pumpStatus.rileyLinkError = checkStatusSet(pumpStatus.rileyLinkError, rileyLinkUtil.getError()) as RileyLinkError? + medtronicPumpStatus.rileyLinkError = checkStatusSet(medtronicPumpStatus.rileyLinkError, rileyLinkUtil.getError()) as RileyLinkError? medtronic_errors.text = - pumpStatus.rileyLinkError?.let { + medtronicPumpStatus.rileyLinkError?.let { resourceHelper.gs(it.getResourceId(RileyLinkTargetDevice.MedtronicPump)) } ?: "-" - pumpStatus.pumpDeviceState = checkStatusSet(pumpStatus.pumpDeviceState, - medtronicUtil.getPumpDeviceState()) as PumpDeviceState? + medtronicPumpStatus.pumpDeviceState = checkStatusSet(medtronicPumpStatus.pumpDeviceState, + medtronicUtil.pumpDeviceState) as PumpDeviceState? - when (pumpStatus.pumpDeviceState) { + when (medtronicPumpStatus.pumpDeviceState) { null, PumpDeviceState.Sleeping -> medtronic_pump_status.text = "{fa-bed} " // + pumpStatus.pumpDeviceState.name()); PumpDeviceState.NeverContacted, @@ -207,12 +207,12 @@ class MedtronicFragment : DaggerFragment() { PumpDeviceState.PumpUnreachable, PumpDeviceState.ErrorWhenCommunicating, PumpDeviceState.TimeoutWhenCommunicating, - PumpDeviceState.InvalidConfiguration -> medtronic_pump_status.text = " " + resourceHelper.gs(pumpStatus.pumpDeviceState.resourceId) + PumpDeviceState.InvalidConfiguration -> medtronic_pump_status.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId) PumpDeviceState.Active -> { val cmd = medtronicUtil.getCurrentCommand() if (cmd == null) - medtronic_pump_status.text = " " + resourceHelper.gs(pumpStatus.pumpDeviceState.resourceId) + medtronic_pump_status.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId) else { aapsLogger.debug(LTag.PUMP, "Command: " + cmd) val cmdResourceId = cmd.resourceId @@ -228,7 +228,7 @@ class MedtronicFragment : DaggerFragment() { } } - else -> aapsLogger.warn(LTag.PUMP, "Unknown pump state: " + pumpStatus.pumpDeviceState) + else -> aapsLogger.warn(LTag.PUMP, "Unknown pump state: " + medtronicPumpStatus.pumpDeviceState) } val status = commandQueue.spannedStatus() @@ -262,18 +262,17 @@ class MedtronicFragment : DaggerFragment() { @Synchronized fun updateGUI() { if (medtronic_rl_status == null) return - val pumpStatus = medtronicUtil.getPumpStatus() setDeviceStatus() // last connection - if (pumpStatus.lastConnection != 0L) { - val minAgo = DateUtil.minAgo(resourceHelper, pumpStatus.lastConnection) - val min = (System.currentTimeMillis() - pumpStatus.lastConnection) / 1000 / 60 - if (pumpStatus.lastConnection + 60 * 1000 > System.currentTimeMillis()) { + if (medtronicPumpStatus.lastConnection != 0L) { + val minAgo = DateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastConnection) + val min = (System.currentTimeMillis() - medtronicPumpStatus.lastConnection) / 1000 / 60 + if (medtronicPumpStatus.lastConnection + 60 * 1000 > System.currentTimeMillis()) { medtronic_lastconnection.setText(R.string.combo_pump_connected_now) medtronic_lastconnection.setTextColor(Color.WHITE) - } else if (pumpStatus.lastConnection + 30 * 60 * 1000 < System.currentTimeMillis()) { + } else if (medtronicPumpStatus.lastConnection + 30 * 60 * 1000 < System.currentTimeMillis()) { if (min < 60) { medtronic_lastconnection.text = resourceHelper.gs(R.string.minago, min) @@ -296,19 +295,19 @@ class MedtronicFragment : DaggerFragment() { } // last bolus - val bolus = pumpStatus.lastBolusAmount - val bolusTime = pumpStatus.lastBolusTime + val bolus = medtronicPumpStatus.lastBolusAmount + val bolusTime = medtronicPumpStatus.lastBolusTime if (bolus != null && bolusTime != null) { - val agoMsc = System.currentTimeMillis() - pumpStatus.lastBolusTime.time + val agoMsc = System.currentTimeMillis() - medtronicPumpStatus.lastBolusTime.time val bolusMinAgo = agoMsc.toDouble() / 60.0 / 1000.0 val unit = resourceHelper.gs(R.string.insulin_unit_shortname) val ago: String if (agoMsc < 60 * 1000) { ago = resourceHelper.gs(R.string.combo_pump_connected_now) } else if (bolusMinAgo < 60) { - ago = DateUtil.minAgo(resourceHelper, pumpStatus.lastBolusTime.time) + ago = DateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastBolusTime.time) } else { - ago = DateUtil.hourAgo(pumpStatus.lastBolusTime.time, resourceHelper) + ago = DateUtil.hourAgo(medtronicPumpStatus.lastBolusTime.time, resourceHelper) } medtronic_lastbolus.text = resourceHelper.gs(R.string.combo_last_bolus, bolus, unit, ago) } else { @@ -316,24 +315,24 @@ class MedtronicFragment : DaggerFragment() { } // base basal rate - medtronic_basabasalrate.text = ("(" + pumpStatus.activeProfileName + ") " + medtronic_basabasalrate.text = ("(" + medtronicPumpStatus.activeProfileName + ") " + resourceHelper.gs(R.string.pump_basebasalrate, medtronicPumpPlugin.baseBasalRate)) medtronic_tempbasal.text = activePlugin.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: "" // battery - if (medtronicUtil.getBatteryType() == BatteryType.None || pumpStatus.batteryVoltage == null) { - medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} " + if (medtronicUtil.getBatteryType() == BatteryType.None || medtronicPumpStatus.batteryVoltage == null) { + medtronic_pumpstate_battery.text = "{fa-battery-" + medtronicPumpStatus.batteryRemaining / 25 + "} " } else { - medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} " + pumpStatus.batteryRemaining + "%" + String.format(" (%.2f V)", pumpStatus.batteryVoltage) + medtronic_pumpstate_battery.text = "{fa-battery-" + medtronicPumpStatus.batteryRemaining / 25 + "} " + medtronicPumpStatus.batteryRemaining + "%" + String.format(" (%.2f V)", medtronicPumpStatus.batteryVoltage) } - warnColors.setColorInverse(medtronic_pumpstate_battery, pumpStatus.batteryRemaining.toDouble(), 25.0, 10.0) + warnColors.setColorInverse(medtronic_pumpstate_battery, medtronicPumpStatus.batteryRemaining.toDouble(), 25.0, 10.0) // reservoir - medtronic_reservoir.text = resourceHelper.gs(R.string.reservoirvalue, pumpStatus.reservoirRemainingUnits, pumpStatus.reservoirFullUnits) - warnColors.setColorInverse(medtronic_reservoir, pumpStatus.reservoirRemainingUnits, 50.0, 20.0) + medtronic_reservoir.text = resourceHelper.gs(R.string.reservoirvalue, medtronicPumpStatus.reservoirRemainingUnits, medtronicPumpStatus.reservoirFullUnits) + warnColors.setColorInverse(medtronic_reservoir, medtronicPumpStatus.reservoirRemainingUnits, 50.0, 20.0) - medtronic_errors.text = pumpStatus.errorInfo + medtronic_errors.text = medtronicPumpStatus.errorInfo } } 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 21198a2a37..fe50f06a04 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 @@ -99,10 +99,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final RileyLinkUtil rileyLinkUtil; private final MedtronicUtil medtronicUtil; private final MedtronicPumpStatus medtronicPumpStatus; + private final MedtronicUIComm medtronicUIComm; protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService rileyLinkMedtronicService; - private MedtronicUIComm medtronicUIComm; // variables for handling statuses and history private boolean firstRun = true; @@ -131,7 +131,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter FabricPrivacy fabricPrivacy, RileyLinkUtil rileyLinkUtil, MedtronicUtil medtronicUtil, - MedtronicPumpStatus medtronicPumpStatus + MedtronicPumpStatus medtronicPumpStatus, + MedtronicUIComm medtronicUIComm ) { super(new PluginDescription() // @@ -150,6 +151,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.medtronicUtil = medtronicUtil; this.sp = sp; this.medtronicPumpStatus = medtronicPumpStatus; + this.medtronicUIComm = medtronicUIComm; displayConnectionMessages = false; @@ -170,11 +172,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter for (int i = 0; i < 20; i++) { SystemClock.sleep(5000); - if (medtronicUtil.getPumpStatus() != null) { - aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service"); - if (medtronicUtil.getPumpStatus().setNotInPreInit()) { - break; - } + aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service"); + if (medtronicPumpStatus.setNotInPreInit()) { + break; } } }).start(); @@ -186,7 +186,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Override protected void onStart() { super.onStart(); - medtronicUIComm = new MedtronicUIComm(aapsLogger, rxBus, getResourceHelper(), rileyLinkUtil, medtronicUtil); medtronicHistoryData = new MedtronicHistoryData(aapsLogger, sp, activePlugin); } @@ -211,8 +210,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Override public void initPumpStatusData() { - medtronicUtil.setPumpStatus(medtronicPumpStatus); - medtronicPumpStatus.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); medtronicPumpStatus.lastDataTime = medtronicPumpStatus.lastConnection; medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection; @@ -1532,7 +1529,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter switch (mcat) { case WakeUpAndTune: { - if (medtronicUtil.getPumpStatus().verifyConfiguration()) { + if (medtronicPumpStatus.verifyConfiguration()) { ServiceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); } else { Intent i = new Intent(context, ErrorHelperActivity.class); @@ -1583,5 +1580,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter refreshCustomActionsList(); } + @Deprecated + public MedtronicPumpStatus getMedtronicPumpStatus() { + return medtronicPumpStatus; + } } 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 16b9ad2a32..d0ac644376 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,9 +10,12 @@ import java.util.GregorianCalendar; import java.util.List; import java.util.Map; +import javax.inject.Inject; + import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; 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; @@ -45,8 +48,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; -import info.nightscout.androidaps.utils.SP; /** * Original file created by geoff on 5/30/16. @@ -57,6 +60,8 @@ import info.nightscout.androidaps.utils.SP; */ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager { + @Inject MedtronicPumpStatus medtronicPumpStatus; + private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); private static final int MAX_COMMAND_TRIES = 3; private static final int DEFAULT_TIMEOUT = 2000; @@ -76,7 +81,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager medtronicCommunicationManager = this; this.medtronicConverter = new MedtronicConverter(); this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder(); - MedtronicUtil.getInstance().getPumpStatus().previousConnection = SP.getLong( + medtronicPumpStatus.previousConnection = sp.getLong( RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); } @@ -85,13 +90,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return medtronicCommunicationManager; } - - @Override - protected void configurePumpSpecificSettings() { - pumpStatus = MedtronicUtil.getInstance().getPumpStatus(); - } - - @Override public E createResponseMessage(byte[] payload, Class clazz) { PumpMessage pumpMessage = new PumpMessage(payload); @@ -141,7 +139,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (!canPreventTuneUp) { - long diff = System.currentTimeMillis() - MedtronicUtil.getInstance().getPumpStatus().lastConnection; + long diff = System.currentTimeMillis() - medtronicPumpStatus.lastConnection; if (diff > RILEYLINK_TIMEOUT) { ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); @@ -962,5 +960,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return L.isEnabled(L.PUMPCOMM); } - + @Override public PumpStatus getPumpStatus() { + return medtronicPumpStatus; + } } 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 40b2c12f3d..8405e11e82 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 @@ -2,6 +2,10 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; import org.jetbrains.annotations.NotNull; +import javax.inject.Inject; +import javax.inject.Singleton; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -15,27 +19,32 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by andy on 6/14/18. */ +@Singleton public class MedtronicUIComm { + @NotNull private final HasAndroidInjector injector; @NotNull private final AAPSLogger aapsLogger; @NotNull private final RileyLinkUtil rileyLinkUtil; @NotNull private final MedtronicUtil medtronicUtil; MedtronicCommunicationManager mcmInstance = null; - MedtronicUIPostprocessor uiPostprocessor; + @NotNull private final MedtronicUIPostprocessor medtronicUIPostprocessor; + @Inject public MedtronicUIComm( + HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, RileyLinkUtil rileyLinkUtil, - MedtronicUtil medtronicUtil + MedtronicUtil medtronicUtil, + MedtronicUIPostprocessor medtronicUIPostprocessor ) { + this.injector = injector; this.aapsLogger = aapsLogger; this.rileyLinkUtil = rileyLinkUtil; this.medtronicUtil = medtronicUtil; - - uiPostprocessor = new MedtronicUIPostprocessor(aapsLogger, rxBus, resourceHelper, medtronicUtil); + this.medtronicUIPostprocessor = medtronicUIPostprocessor; } @@ -52,7 +61,7 @@ public class MedtronicUIComm { aapsLogger.warn(LTag.PUMP, "Execute Command: " + commandType.name()); - MedtronicUITask task = new MedtronicUITask(commandType, parameters); + MedtronicUITask task = new MedtronicUITask(injector, commandType, parameters); medtronicUtil.setCurrentCommand(commandType); @@ -88,7 +97,7 @@ public class MedtronicUIComm { aapsLogger.warn(LTag.PUMP, "Reply not received for " + commandType); } - task.postProcess(uiPostprocessor); + task.postProcess(medtronicUIPostprocessor); return task; 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 0812678343..1de2f68e84 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 @@ -7,6 +7,9 @@ import org.joda.time.Duration; import java.util.Date; import java.util.Map; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -26,18 +29,22 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; * Created by andy on 6/15/18. */ +@Singleton class MedtronicUIPostprocessor { @NotNull private final AAPSLogger aapsLogger; @NotNull private final RxBusWrapper rxBus; @NotNull private final ResourceHelper resourceHelper; @NotNull private final MedtronicUtil medtronicUtil; + @NotNull private final MedtronicPumpStatus medtronicPumpStatus; - public MedtronicUIPostprocessor(AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, MedtronicUtil medtronicUtil) { + @Inject + public MedtronicUIPostprocessor(AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, MedtronicUtil medtronicUtil, MedtronicPumpStatus medtronicPumpStatus) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.medtronicUtil = medtronicUtil; + this.medtronicPumpStatus = medtronicPumpStatus; } @@ -53,7 +60,7 @@ class MedtronicUIPostprocessor { if (response) { BasalProfile basalProfile = (BasalProfile) uiTask.getParameter(0); - medtronicUtil.getPumpStatus().basalsByHour = basalProfile.getProfilesByHour(); + medtronicPumpStatus.basalsByHour = basalProfile.getProfilesByHour(); } } break; @@ -65,8 +72,8 @@ class MedtronicUIPostprocessor { Double[] profilesByHour = basalProfile.getProfilesByHour(); if (profilesByHour != null) { - medtronicUtil.getPumpStatus().basalsByHour = profilesByHour; - medtronicUtil.getPumpStatus().basalProfileStatus = BasalProfileStatus.ProfileOK; + medtronicPumpStatus.basalsByHour = profilesByHour; + medtronicPumpStatus.basalProfileStatus = BasalProfileStatus.ProfileOK; } else { uiTask.responseType = MedtronicUIResponseType.Error; uiTask.errorDescription = "No profile found."; @@ -81,20 +88,20 @@ class MedtronicUIPostprocessor { break; case SetBolus: { - medtronicUtil.getPumpStatus().lastBolusAmount = uiTask.getDoubleFromParameters(0); - medtronicUtil.getPumpStatus().lastBolusTime = new Date(); + medtronicPumpStatus.lastBolusAmount = uiTask.getDoubleFromParameters(0); + medtronicPumpStatus.lastBolusTime = new Date(); } break; case GetRemainingInsulin: { - medtronicUtil.getPumpStatus().reservoirRemainingUnits = (Float) uiTask.returnData; + medtronicPumpStatus.reservoirRemainingUnits = (Float) uiTask.returnData; } break; case CancelTBR: { - medtronicUtil.getPumpStatus().tempBasalStart = null; - medtronicUtil.getPumpStatus().tempBasalAmount = null; - medtronicUtil.getPumpStatus().tempBasalLength = null; + medtronicPumpStatus.tempBasalStart = null; + medtronicPumpStatus.tempBasalAmount = null; + medtronicPumpStatus.tempBasalLength = null; } break; @@ -118,10 +125,10 @@ class MedtronicUIPostprocessor { case GetBatteryStatus: { BatteryStatusDTO batteryStatusDTO = (BatteryStatusDTO) uiTask.returnData; - medtronicUtil.getPumpStatus().batteryRemaining = batteryStatusDTO.getCalculatedPercent(medtronicUtil.getPumpStatus().batteryType); + medtronicPumpStatus.batteryRemaining = batteryStatusDTO.getCalculatedPercent(medtronicPumpStatus.batteryType); if (batteryStatusDTO.voltage != null) { - medtronicUtil.getPumpStatus().batteryVoltage = batteryStatusDTO.voltage; + medtronicPumpStatus.batteryVoltage = batteryStatusDTO.voltage; } aapsLogger.debug(LTag.PUMP, "BatteryStatus: {}", batteryStatusDTO.toString()); @@ -130,7 +137,7 @@ class MedtronicUIPostprocessor { break; case PumpModel: { - if (medtronicUtil.getPumpStatus().medtronicDeviceType != medtronicUtil.getMedtronicPumpModel()) { + if (medtronicPumpStatus.medtronicDeviceType != medtronicUtil.getMedtronicPumpModel()) { aapsLogger.warn(LTag.PUMP, "Configured pump is different then pump detected !"); medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, resourceHelper, rxBus); } @@ -190,11 +197,7 @@ class MedtronicUIPostprocessor { PumpSettingDTO checkValue = null; - if (medtronicUtil.getPumpStatus() == null) { - aapsLogger.debug(LTag.PUMP, "Pump Status: was null"); - } - - medtronicUtil.getPumpStatus().verifyConfiguration(); + medtronicPumpStatus.verifyConfiguration(); // check profile if (!"Yes".equals(settings.get("PCFG_BASAL_PROFILES_ENABLED").value)) { @@ -223,16 +226,16 @@ class MedtronicUIPostprocessor { checkValue = settings.get("PCFG_MAX_BOLUS"); - if (!medtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicUtil.getPumpStatus().maxBolus)) { - aapsLogger.error("Wrong Max Bolus set on Pump (current={}, required={}).", checkValue.value, medtronicUtil.getPumpStatus().maxBolus); - medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, medtronicUtil.getPumpStatus().maxBolus); + if (!medtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicPumpStatus.maxBolus)) { + aapsLogger.error("Wrong Max Bolus set on Pump (current={}, required={}).", checkValue.value, medtronicPumpStatus.maxBolus); + medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, medtronicPumpStatus.maxBolus); } checkValue = settings.get("PCFG_MAX_BASAL"); - if (!medtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicUtil.getPumpStatus().maxBasal)) { - aapsLogger.error("Wrong Max Basal set on Pump (current={}, required={}).", checkValue.value, medtronicUtil.getPumpStatus().maxBasal); - medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, medtronicUtil.getPumpStatus().maxBasal); + if (!medtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicPumpStatus.maxBasal)) { + aapsLogger.error("Wrong Max Basal set on Pump (current={}, required={}).", checkValue.value, medtronicPumpStatus.maxBasal); + medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, medtronicPumpStatus.maxBasal); } } 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 7518cba457..4c5960900c 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 @@ -1,10 +1,12 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; +import org.jetbrains.annotations.NotNull; import org.joda.time.LocalDateTime; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBus; @@ -15,6 +17,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicUIResponseType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpValuesChanged; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; @@ -25,6 +28,10 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; public class MedtronicUITask { + @Inject MedtronicPumpStatus medtronicPumpStatus; + + @NotNull private final HasAndroidInjector injector; + private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP); public MedtronicCommandType commandType; @@ -36,12 +43,16 @@ public class MedtronicUITask { MedtronicUIResponseType responseType; - public MedtronicUITask(MedtronicCommandType commandType) { + public MedtronicUITask(HasAndroidInjector injector, MedtronicCommandType commandType) { + this.injector = injector; + injector.androidInjector().inject(this); this.commandType = commandType; } - public MedtronicUITask(MedtronicCommandType commandType, Object... parameters) { + public MedtronicUITask(HasAndroidInjector injector, MedtronicCommandType commandType, Object... parameters) { + this.injector = injector; + injector.androidInjector().inject(this); this.commandType = commandType; this.parameters = parameters; } @@ -200,7 +211,7 @@ public class MedtronicUITask { errorDescription)); } else { RxBus.Companion.getINSTANCE().send(new EventMedtronicPumpValuesChanged()); - MedtronicUtil.getInstance().getPumpStatus().setLastCommunicationToNow(); + medtronicPumpStatus.setLastCommunicationToNow(); } MedtronicUtil.getInstance().setCurrentCommand(null); 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 3f6e2d9f2d..32666819c0 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 @@ -4,7 +4,6 @@ import com.google.gson.annotations.Expose; import org.joda.time.Instant; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; @@ -13,6 +12,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; /** @@ -305,7 +305,7 @@ public class BasalProfile { Double[] basalByHour = new Double[24]; - PumpType pumpType = MedtronicUtil.getInstance().getPumpStatus().pumpType; + PumpType pumpType = MedtronicPumpPlugin.getPlugin().getMedtronicPumpStatus().pumpType; for (int i = 0; i < entries.size(); i++) { BasalProfileEntry current = entries.get(i); 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 2b43890c06..87bce0bd75 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 @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.medtronic.driver; -import org.joda.time.LocalDateTime; - import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; @@ -44,10 +42,10 @@ public class MedtronicPumpStatus extends PumpStatus { private final ResourceHelper resourceHelper; private final SP sp; - public String errorDescription = null; + private String errorDescription = null; public String serialNumber; public String pumpFrequency = null; - public String rileyLinkAddress = null; + private String rileyLinkAddress = null; public Double maxBolus; public Double maxBasal; private boolean inPreInit = true; 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 e54debd30c..160cbd9f25 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 @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.medtronic.service; -import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; @@ -10,11 +9,9 @@ import android.os.IBinder; import javax.inject.Inject; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; 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; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType; @@ -22,15 +19,12 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTask; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; -import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; -import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * RileyLinkMedtronicService is intended to stay running when the gui-app is closed. @@ -41,12 +35,8 @@ public class RileyLinkMedtronicService extends RileyLinkService { @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicUtil medtronicUtil; - @Deprecated // TEDO remove this reference - private static ServiceTask currentTask = null; - // cache of most recently received set of pump history pages. Probably shouldn't be here. - public MedtronicCommunicationManager medtronicCommunicationManager; - MedtronicPumpStatus pumpStatus = null; + private MedtronicCommunicationManager medtronicCommunicationManager; private IBinder mBinder = new LocalBinder(); @@ -100,8 +90,6 @@ public class RileyLinkMedtronicService extends RileyLinkService { aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed"); medtronicUtil.setMedtronicService(this); - pumpStatus = (MedtronicPumpStatus) medtronicPumpPlugin.getPumpStatusData(); - } 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 ad97583cec..5c0578c3c0 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 @@ -56,7 +56,6 @@ public class MedtronicUtil { private MedtronicDeviceType medtronicPumpModel; private RileyLinkMedtronicService medtronicService; @Deprecated // TODO remove this reference - private MedtronicPumpStatus medtronicPumpStatus; private MedtronicCommandType currentCommand; private Map settings; private int BIG_FRAME_LENGTH = 65; @@ -69,17 +68,20 @@ public class MedtronicUtil { @NotNull private final AAPSLogger aapsLogger; @NotNull private final RxBusWrapper rxBus; @NotNull private final RileyLinkUtil rileyLinkUtil; + @NotNull private final MedtronicPumpStatus medtronicPumpStatus; @Inject public MedtronicUtil( AAPSLogger aapsLogger, RxBusWrapper rxBus, - RileyLinkUtil rileyLinkUtil + RileyLinkUtil rileyLinkUtil, + MedtronicPumpStatus medtronicPumpStatus ) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil; + this.medtronicPumpStatus = medtronicPumpStatus; instance = this; } @@ -465,16 +467,10 @@ public class MedtronicUtil { @Deprecated // TODO use singleton - public MedtronicPumpStatus getPumpStatus() { + public MedtronicPumpStatus getPumpStatus1() { return medtronicPumpStatus; } - @Deprecated // TODO use singleton - public void setPumpStatus(MedtronicPumpStatus medtronicPumpStatus) { - this.medtronicPumpStatus = medtronicPumpStatus; - } - - public MedtronicCommandType getCurrentCommand() { return this.currentCommand; } From e2e0de25bc919ad3d913853e25e8879e4919b1f7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 01:12:04 +0200 Subject: [PATCH 05/23] MDT refactor pass 4 --- .../androidaps/logging/AAPSLogger.kt | 1 + .../androidaps/logging/AAPSLoggerDebug.kt | 4 + .../logging/AAPSLoggerProduction.kt | 4 + .../androidaps/logging/AAPSLoggerTest.kt | 4 + .../pump/common/PumpPluginAbstract.java | 3 + .../RileyLinkCommunicationManager.java | 86 ++++++++----------- .../common/hw/rileylink/RileyLinkUtil.java | 11 --- .../rileylink/service/RileyLinkService.java | 3 +- .../tasks/InitializePumpManagerTask.java | 15 +++- .../pump/medtronic/MedtronicPumpPlugin.java | 14 +-- .../comm/MedtronicCommunicationManager.java | 9 +- .../medtronic/comm/ui/MedtronicUIComm.java | 14 ++- .../service/RileyLinkMedtronicService.java | 3 +- 13 files changed, 78 insertions(+), 93 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt index 8c24805261..fe47fea99d 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt @@ -11,6 +11,7 @@ interface AAPSLogger { fun debug(tag: LTag, message: String) fun debug(tag: LTag, format: String, vararg arguments: Any?) fun warn(tag: LTag, message: String) + fun warn(tag: LTag, format: String, vararg arguments: Any?) fun info(tag: LTag, message: String) fun info(tag: LTag, format: String, vararg arguments: Any?) fun error(tag: LTag, message: String) diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt index b930eb4728..ba7f88712d 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt @@ -28,6 +28,10 @@ class AAPSLoggerDebug : AAPSLogger { Log.w(tag.tag, message) } + override fun warn(tag: LTag, format: String, vararg arguments: Any?) { + Log.w(tag.tag, String.format(format, arguments)) + } + override fun info(tag: LTag, message: String) { Log.i(tag.tag, message) } diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt index 27b0946749..6b3c9832a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt @@ -35,6 +35,10 @@ class AAPSLoggerProduction : AAPSLogger { } } + override fun warn(tag: LTag, format: String, vararg arguments: Any?) { + LoggerFactory.getLogger(tag.tag).warn(stackLogMarker() + String.format(format, arguments)) + } + override fun info(tag: LTag, message: String) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).info(stackLogMarker() + message) diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerTest.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerTest.kt index 0503db143f..5f6b798e36 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerTest.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerTest.kt @@ -26,6 +26,10 @@ class AAPSLoggerTest : AAPSLogger { println("WARN: " + tag.tag + " " + message) } + override fun warn(tag: LTag, format: String, vararg arguments: Any?) { + println("INFO: : " + tag.tag + " " + String.format(format, arguments)) + } + override fun info(tag: LTag, message: String) { println("INFO: " + tag.tag + " " + message) } 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 70edbcec19..8bf2f21455 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 @@ -37,6 +37,8 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.utils.DateUtil; @@ -111,6 +113,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public abstract void initPumpStatusData(); public abstract void resetRileyLinkConfiguration(); public abstract void doTuneUpDevice(); + public abstract RileyLinkService getRileyLinkService(); @Override protected void onStart() { 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 35cfd48a5b..91e9be0e1a 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 @@ -1,13 +1,10 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import javax.inject.Inject; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; 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; @@ -35,13 +32,15 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; */ public abstract class RileyLinkCommunicationManager { - @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject protected AAPSLogger aapsLogger; @Inject protected SP sp; - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject RileyLinkUtil rileyLinkUtil; - private static final int SCAN_TIMEOUT = 1500; - private static final int ALLOWED_PUMP_UNREACHABLE = 10 * 60 * 1000; // 10 minutes + + private final int SCAN_TIMEOUT = 1500; + private final int ALLOWED_PUMP_UNREACHABLE = 10 * 60 * 1000; // 10 minutes protected final HasAndroidInjector injector; protected final RFSpy rfspy; @@ -61,8 +60,7 @@ public abstract class RileyLinkCommunicationManager { this.injector = injector; injector.androidInjector().inject(this); this.rfspy = rfspy; - this.rileyLinkServiceData = RileyLinkUtil.getInstance().getRileyLinkServiceData(); - RileyLinkUtil.getInstance().setRileyLinkCommunicationManager(this); + this.rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData(); } @@ -87,8 +85,7 @@ public abstract class RileyLinkCommunicationManager { throws RileyLinkCommunicationException { if (showPumpMessages) { - if (isLogEnabled()) - LOG.info("Sent:" + ByteUtil.shortHexString(msg.getTxData())); + aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); } RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(msg.getTxData()), @@ -101,7 +98,7 @@ public abstract class RileyLinkCommunicationManager { // Mark this as the last time we heard from the pump. rememberLastGoodDeviceCommunicationTime(); } else { - LOG.warn("isDeviceReachable. Response is invalid ! [interrupted={}, timeout={}, unknownCommand={}, invalidParam={}]", rfSpyResponse.wasInterrupted(), + aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Response is invalid ! [interrupted={}, timeout={}, unknownCommand={}, invalidParam={}]", rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout(), rfSpyResponse.isUnknownCommand(), rfSpyResponse.isInvalidParam()); if (rfSpyResponse.wasTimeout()) { @@ -111,7 +108,7 @@ public abstract class RileyLinkCommunicationManager { long diff = System.currentTimeMillis() - getPumpStatus().lastConnection; if (diff > ALLOWED_PUMP_UNREACHABLE) { - LOG.warn("We reached max time that Pump can be unreachable. Starting Tuning."); + aapsLogger.warn(LTag.PUMPBTCOMM, "We reached max time that Pump can be unreachable. Starting Tuning."); ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); timeoutCount = 0; } @@ -124,8 +121,7 @@ public abstract class RileyLinkCommunicationManager { } if (showPumpMessages) { - if (isLogEnabled()) - LOG.info("Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse().getPayload())); + aapsLogger.info(LTag.PUMPBTCOMM, "Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse().getPayload())); } return response; @@ -162,21 +158,18 @@ public abstract class RileyLinkCommunicationManager { nextWakeUpRequired = 0L; if (System.currentTimeMillis() > nextWakeUpRequired) { - if (isLogEnabled()) - LOG.info("Waking pump..."); + aapsLogger.info(LTag.PUMPBTCOMM, "Waking pump..."); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, (byte) 0, (byte) 0, 25000, (byte) 0); - if (isLogEnabled()) - LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); // FIXME wakeUp successful !!!!!!!!!!!!!!!!!! nextWakeUpRequired = System.currentTimeMillis() + (receiverDeviceAwakeForMinutes * 60 * 1000); } else { - if (isLogEnabled()) - LOG.trace("Last pump communication was recent, not waking pump."); + aapsLogger.debug(LTag.PUMPBTCOMM, "Last pump communication was recent, not waking pump."); } // long lastGoodPlus = getLastGoodReceiverCommunicationTime() + (receiverDeviceAwakeForMinutes * 60 * 1000); @@ -233,8 +226,7 @@ public abstract class RileyLinkCommunicationManager { public double scanForDevice(double[] frequencies) { - if (isLogEnabled()) - LOG.info("Scanning for receiver ({})", receiverDeviceID); + aapsLogger.info(LTag.PUMPBTCOMM, "Scanning for receiver ({})", receiverDeviceID); wakeUp(receiverDeviceAwakeForMinutes, false); FrequencyScanResults results = new FrequencyScanResults(); @@ -251,7 +243,7 @@ public abstract class RileyLinkCommunicationManager { RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 0, (byte) 0, (byte) 0, 1250, (byte) 0); if (resp.wasTimeout()) { - LOG.error("scanForPump: Failed to find pump at frequency {}", frequencies[i]); + aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: Failed to find pump at frequency {}", frequencies[i]); } else if (resp.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(); @@ -265,17 +257,17 @@ public abstract class RileyLinkCommunicationManager { trial.rssiList.add(rssi); trial.successes++; } else { - LOG.warn("Failed to parse radio response: " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to parse radio response: " + ByteUtil.shortHexString(resp.getRaw())); trial.rssiList.add(-99); } } catch (RileyLinkCommunicationException rle) { - LOG.warn("Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); trial.rssiList.add(-99); } } else { - LOG.error("scanForPump: raw response is " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: raw response is " + ByteUtil.shortHexString(resp.getRaw())); trial.rssiList.add(-99); } trial.tries++; @@ -299,7 +291,7 @@ public abstract class RileyLinkCommunicationManager { + one.frequencyMHz, "" + one.averageRSSI + ", RSSIs =" + one.rssiList)); } - LOG.info(stringBuilder.toString()); + aapsLogger.info(LTag.PUMPCOMM, stringBuilder.toString()); results.sort(); // sorts in ascending order @@ -307,11 +299,10 @@ public abstract class RileyLinkCommunicationManager { results.bestFrequencyMHz = bestTrial.frequencyMHz; if (bestTrial.successes > 0) { rfspy.setBaseFrequency(results.bestFrequencyMHz); - if (isLogEnabled()) - LOG.debug("Best frequency found: " + results.bestFrequencyMHz); + aapsLogger.debug(LTag.PUMPBTCOMM, "Best frequency found: " + results.bestFrequencyMHz); return results.bestFrequencyMHz; } else { - LOG.error("No pump response during scan."); + aapsLogger.error(LTag.PUMPBTCOMM, "No pump response during scan."); return 0.0; } } @@ -340,22 +331,22 @@ public abstract class RileyLinkCommunicationManager { RadioPacket pkt = new RadioPacket(pumpMsgContent); RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, SCAN_TIMEOUT, (byte) 0); if (resp.wasTimeout()) { - LOG.warn("tune_tryFrequency: no pump response at frequency {}", freqMHz); + aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: no pump response at frequency {}", freqMHz); } else if (resp.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(); try { radioResponse.init(resp.getRaw()); if (radioResponse.isValid()) { - LOG.warn("tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz); + aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz); return calculateRssi(radioResponse.rssi); } else { - LOG.warn("tune_tryFrequency: invalid radio response:" + aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: invalid radio response:" + ByteUtil.shortHexString(radioResponse.getPayload())); } } catch (RileyLinkCommunicationException e) { - LOG.warn("Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); } } @@ -382,16 +373,13 @@ public abstract class RileyLinkCommunicationManager { } if (betterFrequency == 0.0) { // we've failed... caller should try a full scan for pump - if (isLogEnabled()) - LOG.error("quickTuneForPump: failed to find pump"); + aapsLogger.error(LTag.PUMPBTCOMM, "quickTuneForPump: failed to find pump"); } else { rfspy.setBaseFrequency(betterFrequency); if (betterFrequency != startFrequencyMHz) { - if (isLogEnabled()) - LOG.info("quickTuneForPump: new frequency is {}MHz", betterFrequency); + aapsLogger.info(LTag.PUMPBTCOMM, "quickTuneForPump: new frequency is {}MHz", betterFrequency); } else { - if (isLogEnabled()) - LOG.info("quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); + aapsLogger.info(LTag.PUMPBTCOMM, "quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); } } return betterFrequency; @@ -399,8 +387,7 @@ public abstract class RileyLinkCommunicationManager { private double quickTunePumpStep(double startFrequencyMHz, double stepSizeMHz) { - if (isLogEnabled()) - LOG.info("Doing quick radio tune for receiver ({})", receiverDeviceID); + aapsLogger.info(LTag.PUMPBTCOMM, "Doing quick radio tune for receiver ({})", receiverDeviceID); wakeUp(false); int startRssi = tune_tryFrequency(startFrequencyMHz); double lowerFrequency = startFrequencyMHz - stepSizeMHz; @@ -438,8 +425,7 @@ public abstract class RileyLinkCommunicationManager { // Might still be zero, but that's fine. } double minutesAgo = (System.currentTimeMillis() - lastGoodReceiverCommunicationTime) / (1000.0 * 60.0); - if (isLogEnabled()) - LOG.trace("Last good pump communication was " + minutesAgo + " minutes ago."); + aapsLogger.debug(LTag.PUMPBTCOMM, "Last good pump communication was " + minutesAgo + " minutes ago."); return lastGoodReceiverCommunicationTime; } @@ -449,9 +435,7 @@ public abstract class RileyLinkCommunicationManager { } } - private boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); - } - public abstract PumpStatus getPumpStatus(); + + public abstract boolean isDeviceReachable(); } 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 22edb8ce1a..c47720e383 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 @@ -190,17 +190,6 @@ public class RileyLinkUtil { this.rileyLinkService = rileyLinkService; } - - public RileyLinkCommunicationManager getRileyLinkCommunicationManager() { - return rileyLinkCommunicationManager; - } - - - void setRileyLinkCommunicationManager(RileyLinkCommunicationManager rileyLinkCommunicationManager) { - this.rileyLinkCommunicationManager = rileyLinkCommunicationManager; - } - - public static boolean sendNotification(ServiceNotification notification, Integer clientHashcode) { return false; } 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 5779dd63f1..e31eb51412 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 @@ -125,7 +125,6 @@ public abstract class RileyLinkService extends DaggerService { public abstract RileyLinkCommunicationManager getDeviceCommunicationManager(); - // Here is where the wake-lock begins: // We've received a service startCommand, we grab the lock. @Override @@ -236,7 +235,7 @@ public abstract class RileyLinkService extends DaggerService { // error tuning pump, pump not present ?? rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed); } else { - rileyLinkUtil.getRileyLinkCommunicationManager().clearNotConnectedCount(); + getDeviceCommunicationManager().clearNotConnectedCount(); rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); } } 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 0bf78f08c1..64f7c8343b 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,9 +2,14 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.task import org.slf4j.Logger; +import javax.inject.Inject; + import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; +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; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; @@ -20,6 +25,8 @@ import info.nightscout.androidaps.utils.SP; */ public class InitializePumpManagerTask extends ServiceTask { + @Inject ActivePluginProvider activePlugin; + private static final String TAG = "InitPumpManagerTask"; private RileyLinkTargetDevice targetDevice; private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); @@ -54,17 +61,19 @@ public class InitializePumpManagerTask extends ServiceTask { lastGoodFrequency = RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency; } + RileyLinkCommunicationManager rileyLinkCommunicationManager = ((PumpPluginAbstract)activePlugin.getActivePump()).getRileyLinkService().getDeviceCommunicationManager(); + if ((lastGoodFrequency > 0.0d) - && RileyLinkUtil.getInstance().getRileyLinkCommunicationManager().isValidFrequency(lastGoodFrequency)) { + && rileyLinkCommunicationManager.isValidFrequency(lastGoodFrequency)) { RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.RileyLinkReady); if (L.isEnabled(L.PUMPCOMM)) LOG.info("Setting radio frequency to {} MHz", lastGoodFrequency); - RileyLinkUtil.getInstance().getRileyLinkCommunicationManager().setRadioFrequencyForPump(lastGoodFrequency); + rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency); - boolean foundThePump = RileyLinkUtil.getInstance().getRileyLinkCommunicationManager().tryToConnectToDevice(); + boolean foundThePump = rileyLinkCommunicationManager.tryToConnectToDevice(); if (foundThePump) { RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorReady); 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 fe50f06a04..47962883fe 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 @@ -110,7 +110,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private Map statusRefreshMap = new HashMap<>(); private boolean isInitialized = false; private MedtronicHistoryData medtronicHistoryData; - private MedtronicCommunicationManager medtronicCommunicationManager; private PumpHistoryEntry lastPumpHistoryEntry; public static boolean isBusy = false; @@ -316,9 +315,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return rileyLinkMedtronicService != null; } - @Deprecated @Nullable - public RileyLinkMedtronicService getRileyLinkMedtronicService() { + public RileyLinkMedtronicService getRileyLinkService() { return rileyLinkMedtronicService; } @@ -432,7 +430,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return false; } - return (!medtronicCommunicationManager.isDeviceReachable()); + return (!rileyLinkMedtronicService.getDeviceCommunicationManager().isDeviceReachable()); } @@ -537,10 +535,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter aapsLogger.info(LTag.PUMP, getLogPrefix() + "initializePump - start"); - if (medtronicCommunicationManager == null) { - medtronicCommunicationManager = MedtronicCommunicationManager.getInstance(); - medtronicCommunicationManager.setDoWakeUpBeforeCommand(false); - } + rileyLinkMedtronicService.getDeviceCommunicationManager().setDoWakeUpBeforeCommand(false); setRefreshButtonEnabled(false); @@ -633,11 +628,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return isProfileSame(profile); } else if (medtronicPumpStatus.basalProfileStatus == BasalProfileStatus.ProfileChanged) { return false; - } else { - } - return (medtronicPumpStatus.basalProfileStatus != BasalProfileStatus.ProfileOK) || isProfileSame(profile); } 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 d0ac644376..7c3dff66fb 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 @@ -62,10 +62,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager @Inject MedtronicPumpStatus medtronicPumpStatus; - private static final Logger LOG = StacktraceLoggerWrapper.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 + private final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private final int MAX_COMMAND_TRIES = 3; + private final int DEFAULT_TIMEOUT = 2000; + private final long RILEYLINK_TIMEOUT = 15 * 60 * 1000; // 15 min static MedtronicCommunicationManager medtronicCommunicationManager; String errorMessage; @@ -102,6 +102,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } + @Override public boolean isDeviceReachable() { return isDeviceReachable(false); } 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 8405e11e82..f3d6aa7d9a 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 @@ -8,13 +8,11 @@ import javax.inject.Singleton; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by andy on 6/14/18. @@ -32,13 +30,11 @@ public class MedtronicUIComm { @Inject public MedtronicUIComm( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - RxBusWrapper rxBus, - ResourceHelper resourceHelper, - RileyLinkUtil rileyLinkUtil, - MedtronicUtil medtronicUtil, - MedtronicUIPostprocessor medtronicUIPostprocessor + @NotNull HasAndroidInjector injector, + @NotNull AAPSLogger aapsLogger, + @NotNull RileyLinkUtil rileyLinkUtil, + @NotNull MedtronicUtil medtronicUtil, + @NotNull MedtronicUIPostprocessor medtronicUIPostprocessor ) { this.injector = injector; this.aapsLogger = aapsLogger; 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 160cbd9f25..b349f9c341 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 @@ -98,8 +98,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { } - @Override - public RileyLinkCommunicationManager getDeviceCommunicationManager() { + public MedtronicCommunicationManager getDeviceCommunicationManager() { return this.medtronicCommunicationManager; } From 3598e00290d1eb2183dc3987c3931a720dcb690f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 10:33:03 +0200 Subject: [PATCH 06/23] MDT refactor pass 5 --- .../common/hw/rileylink/RileyLinkUtil.java | 5 +- .../rileylink/service/RileyLinkService.java | 9 ++- .../tasks/DiscoverGattServicesTask.java | 9 ++- .../pump/medtronic/MedtronicPumpPlugin.java | 45 ++++++------- .../medtronic/comm/ui/MedtronicUIComm.java | 65 ++++--------------- .../comm/ui/MedtronicUIPostprocessor.java | 2 +- .../medtronic/comm/ui/MedtronicUITask.java | 48 ++++++-------- .../service/RileyLinkMedtronicService.java | 11 +++- .../pump/medtronic/util/MedtronicUtil.java | 4 -- 9 files changed, 82 insertions(+), 116 deletions(-) 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 c47720e383..75937141f6 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 @@ -156,11 +156,13 @@ public class RileyLinkUtil { } + @Deprecated public RileyLinkBLE getRileyLinkBLE() { return rileyLinkBLE; } + @Deprecated public void setRileyLinkBLE(RileyLinkBLE rileyLinkBLEIn) { rileyLinkBLE = rileyLinkBLEIn; } @@ -180,12 +182,13 @@ public class RileyLinkUtil { return rileyLinkServiceData.tuneUpDone; } - + @Deprecated public RileyLinkService getRileyLinkService() { return rileyLinkService; } + @Deprecated public void setRileyLinkService(RileyLinkService rileyLinkService) { this.rileyLinkService = rileyLinkService; } 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 e31eb51412..df17174f66 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 @@ -5,6 +5,8 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import org.jetbrains.annotations.NotNull; + import javax.inject.Inject; import dagger.android.DaggerService; @@ -35,10 +37,10 @@ public abstract class RileyLinkService extends DaggerService { @Inject protected SP sp; @Inject protected Context context; @Inject protected RileyLinkUtil rileyLinkUtil; - @Inject protected MedtronicUtil medtronicUtil; + @Inject protected MedtronicUtil medtronicUtil; // TODO should be avoided here as it's MDT - public RileyLinkBLE rileyLinkBLE; // android-bluetooth management + @NotNull protected RileyLinkBLE rileyLinkBLE; // android-bluetooth management, must be set in initRileyLinkServiceData protected BluetoothAdapter bluetoothAdapter; protected RFSpy rfspy; // interface for RL xxx Mhz radio. protected RileyLinkBroadcastReceiver mBroadcastReceiver; @@ -251,6 +253,9 @@ public abstract class RileyLinkService extends DaggerService { rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); } + public RileyLinkBLE getRileyLinkBLE() { + return rileyLinkBLE; + } /** * Get Target Device for Service diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java index 42b850d4f7..383eb57cb6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java @@ -1,13 +1,18 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import javax.inject.Inject; + import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; /** * Created by geoff on 7/9/16. */ public class DiscoverGattServicesTask extends ServiceTask { + @Inject MedtronicPumpPlugin medtronicPumpPlugin; + public boolean needToConnect = false; @@ -26,8 +31,8 @@ public class DiscoverGattServicesTask extends ServiceTask { public void run() { if (needToConnect) - RileyLinkUtil.getInstance().getRileyLinkBLE().connectGatt(); + medtronicPumpPlugin.getRileyLinkService().getRileyLinkBLE().connectGatt(); - RileyLinkUtil.getInstance().getRileyLinkBLE().discoverServices(); + medtronicPumpPlugin.getRileyLinkService().getRileyLinkBLE().discoverServices(); } } 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 47962883fe..cdc826e887 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 @@ -59,10 +59,8 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; -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.comm.history.pump.PumpHistoryResult; -import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUIComm; import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile; @@ -99,7 +97,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final RileyLinkUtil rileyLinkUtil; private final MedtronicUtil medtronicUtil; private final MedtronicPumpStatus medtronicPumpStatus; - private final MedtronicUIComm medtronicUIComm; protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService rileyLinkMedtronicService; @@ -130,8 +127,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter FabricPrivacy fabricPrivacy, RileyLinkUtil rileyLinkUtil, MedtronicUtil medtronicUtil, - MedtronicPumpStatus medtronicPumpStatus, - MedtronicUIComm medtronicUIComm + MedtronicPumpStatus medtronicPumpStatus ) { super(new PluginDescription() // @@ -150,7 +146,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.medtronicUtil = medtronicUtil; this.sp = sp; this.medtronicPumpStatus = medtronicPumpStatus; - this.medtronicUIComm = medtronicUIComm; displayConnectionMessages = false; @@ -486,14 +481,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter case BatteryStatus: case RemainingInsulin: { - medtronicUIComm.executeCommand(refreshType.getKey().getCommandType()); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(refreshType.getKey().getCommandType()); refreshTypesNeededToReschedule.add(refreshType.getKey()); resetTime = true; } break; case Configuration: { - medtronicUIComm.executeCommand(refreshType.getKey().getCommandType()); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(refreshType.getKey().getCommandType()); resetTime = true; } break; @@ -554,7 +549,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter // model (once) if (medtronicUtil.getMedtronicPumpModel() == null) { - medtronicUIComm.executeCommand(MedtronicCommandType.PumpModel); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.PumpModel); } else { if (medtronicPumpStatus.medtronicDeviceType != medtronicUtil.getMedtronicPumpModel()) { aapsLogger.warn(LTag.PUMP, getLogPrefix() + "Configured pump is not the same as one detected."); @@ -570,20 +565,20 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter readPumpHistory(); // remaining insulin (>50 = 4h; 50-20 = 1h; 15m) - medtronicUIComm.executeCommand(MedtronicCommandType.GetRemainingInsulin); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetRemainingInsulin); scheduleNextRefresh(MedtronicStatusRefreshType.RemainingInsulin, 10); // remaining power (1h) - medtronicUIComm.executeCommand(MedtronicCommandType.GetBatteryStatus); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetBatteryStatus); scheduleNextRefresh(MedtronicStatusRefreshType.BatteryStatus, 20); // configuration (once and then if history shows config changes) - medtronicUIComm.executeCommand(MedtronicCommandType.getSettings(medtronicUtil.getMedtronicPumpModel())); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.getSettings(medtronicUtil.getMedtronicPumpModel())); // read profile (once, later its controlled by isThisProfileSet method) getBasalProfiles(); - int errorCount = medtronicUIComm.getInvalidResponsesCount(); + int errorCount = rileyLinkMedtronicService.getMedtronicUIComm().getInvalidResponsesCount(); if (errorCount >= 5) { aapsLogger.error("Number of error counts was 5 or more. Starting tunning."); @@ -607,10 +602,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private void getBasalProfiles() { - MedtronicUITask medtronicUITask = medtronicUIComm.executeCommand(MedtronicCommandType.GetBasalProfileSTD); + MedtronicUITask medtronicUITask = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetBasalProfileSTD); if (medtronicUITask.getResponseType() == MedtronicUIResponseType.Error) { - medtronicUIComm.executeCommand(MedtronicCommandType.GetBasalProfileSTD); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetBasalProfileSTD); } } @@ -732,12 +727,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); - medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetRealTimeClock); ClockDTO clock = medtronicUtil.getPumpTime(); if (clock == null) { // retry - medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetRealTimeClock); clock = medtronicUtil.getPumpTime(); } @@ -753,7 +748,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is {} s. Set time on pump." + timeDiff); - medtronicUIComm.executeCommand(MedtronicCommandType.SetRealTimeClock); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.SetRealTimeClock); if (clock.timeDifference == 0) { Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, getResourceHelper().gs(R.string.pump_time_updated), Notification.INFO, 60); @@ -823,7 +818,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter // LOG.debug("MedtronicPumpPlugin::deliverBolus - Start delivery"); - MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetBolus, + MedtronicUITask responseTask = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.SetBolus, detailedBolusInfo.insulin); Boolean response = (Boolean) responseTask.returnData; @@ -989,7 +984,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter // CANCEL - MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR); + MedtronicUITask responseTask2 = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.CancelTBR); Boolean response = (Boolean) responseTask2.returnData; @@ -1006,7 +1001,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } // now start new TBR - MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetTemporaryBasal, + MedtronicUITask responseTask = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.SetTemporaryBasal, absoluteRate, durationInMinutes); Boolean response = (Boolean) responseTask.returnData; @@ -1160,7 +1155,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter aapsLogger.debug(LTag.PUMP, "HST: Target Date: " + targetDate); - MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.GetHistoryData, + MedtronicUITask responseTask2 = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.GetHistoryData, lastPumpHistoryEntry, targetDate); aapsLogger.debug(LTag.PUMP, "HST: After task"); @@ -1300,7 +1295,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private TempBasalPair readTBR() { - MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.ReadTemporaryBasal); + MedtronicUITask responseTask = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.ReadTemporaryBasal); if (responseTask.hasData()) { TempBasalPair tbr = (TempBasalPair) responseTask.returnData; @@ -1350,7 +1345,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .comment(getResourceHelper().gs(R.string.medtronic_cmd_cant_read_tbr)); } - MedtronicUITask responseTask2 = medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR); + MedtronicUITask responseTask2 = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.CancelTBR); Boolean response = (Boolean) responseTask2.returnData; @@ -1428,7 +1423,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .comment(getResourceHelper().gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid)); } - MedtronicUITask responseTask = medtronicUIComm.executeCommand(MedtronicCommandType.SetBasalProfileSTD, + MedtronicUITask responseTask = rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(MedtronicCommandType.SetBasalProfileSTD, basalProfile); Boolean response = (Boolean) responseTask.returnData; 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 f3d6aa7d9a..c65d96b1be 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 @@ -1,15 +1,10 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; -import org.jetbrains.annotations.NotNull; - import javax.inject.Inject; -import javax.inject.Singleton; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -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; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; @@ -17,42 +12,29 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; /** * Created by andy on 6/14/18. */ -@Singleton public class MedtronicUIComm { - @NotNull private final HasAndroidInjector injector; - @NotNull private final AAPSLogger aapsLogger; - @NotNull private final RileyLinkUtil rileyLinkUtil; - @NotNull private final MedtronicUtil medtronicUtil; - - MedtronicCommunicationManager mcmInstance = null; - @NotNull private final MedtronicUIPostprocessor medtronicUIPostprocessor; + private final HasAndroidInjector injector; + private final AAPSLogger aapsLogger; + private final MedtronicUtil medtronicUtil; + private final MedtronicCommunicationManager medtronicCommunicationManager; + private final MedtronicUIPostprocessor medtronicUIPostprocessor; @Inject public MedtronicUIComm( - @NotNull HasAndroidInjector injector, - @NotNull AAPSLogger aapsLogger, - @NotNull RileyLinkUtil rileyLinkUtil, - @NotNull MedtronicUtil medtronicUtil, - @NotNull MedtronicUIPostprocessor medtronicUIPostprocessor + HasAndroidInjector injector, + AAPSLogger aapsLogger, + MedtronicUtil medtronicUtil, + MedtronicUIPostprocessor medtronicUIPostprocessor, + MedtronicCommunicationManager medtronicCommunicationManager ) { this.injector = injector; this.aapsLogger = aapsLogger; - this.rileyLinkUtil = rileyLinkUtil; this.medtronicUtil = medtronicUtil; this.medtronicUIPostprocessor = medtronicUIPostprocessor; + this.medtronicCommunicationManager = medtronicCommunicationManager; } - - private MedtronicCommunicationManager getCommunicationManager() { - if (mcmInstance == null) { - mcmInstance = MedtronicCommunicationManager.getInstance(); - } - - return mcmInstance; - } - - public synchronized MedtronicUITask executeCommand(MedtronicCommandType commandType, Object... parameters) { aapsLogger.warn(LTag.PUMP, "Execute Command: " + commandType.name()); @@ -69,7 +51,7 @@ public class MedtronicUIComm { // LOG.warn("@@@ End Thread"); // }); - task.execute(getCommunicationManager()); + task.execute(medtronicCommunicationManager); // for (int i = 0; i < getMaxWaitTime(commandType); i++) { // synchronized (task) { @@ -99,28 +81,7 @@ public class MedtronicUIComm { } - - /** - * We return 25s as waitTime (17 for wakeUp, and addtional 8 for data retrieval) for normal commands and - * 120s for History. Real time for returning data would be arround 5s, but lets be sure. - * - * @param commandType - * @return - */ - private int getMaxWaitTime(MedtronicCommandType commandType) { - if (commandType == MedtronicCommandType.GetHistoryData) - return 120; - else - return 25; - } - - public int getInvalidResponsesCount() { - return getCommunicationManager().getNotConnectedCount(); - } - - - public void startTunning() { - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + return medtronicCommunicationManager.getNotConnectedCount(); } } 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 1de2f68e84..d4f6a5d377 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 @@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; */ @Singleton -class MedtronicUIPostprocessor { +public class MedtronicUIPostprocessor { @NotNull private final AAPSLogger aapsLogger; @NotNull private final RxBusWrapper rxBus; 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 4c5960900c..51a8020fcd 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 @@ -1,15 +1,13 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; -import org.jetbrains.annotations.NotNull; import org.joda.time.LocalDateTime; -import org.slf4j.Logger; import javax.inject.Inject; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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; @@ -28,11 +26,12 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; public class MedtronicUITask { + @Inject RxBusWrapper rxBus; + @Inject AAPSLogger aapsLogger; @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject MedtronicUtil medtronicUtil; - @NotNull private final HasAndroidInjector injector; - - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP); + private final HasAndroidInjector injector; public MedtronicCommandType commandType; public Object returnData; @@ -45,14 +44,14 @@ public class MedtronicUITask { public MedtronicUITask(HasAndroidInjector injector, MedtronicCommandType commandType) { this.injector = injector; - injector.androidInjector().inject(this); + this.injector.androidInjector().inject(this); this.commandType = commandType; } public MedtronicUITask(HasAndroidInjector injector, MedtronicCommandType commandType, Object... parameters) { this.injector = injector; - injector.androidInjector().inject(this); + this.injector.androidInjector().inject(this); this.commandType = commandType; this.parameters = parameters; } @@ -60,8 +59,7 @@ public class MedtronicUITask { public void execute(MedtronicCommunicationManager communicationManager) { - if (isLogEnabled()) - LOG.debug("MedtronicUITask: @@@ In execute. {}", commandType); + aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. {}", commandType); switch (commandType) { case PumpModel: { @@ -81,7 +79,7 @@ public class MedtronicUITask { case GetRealTimeClock: { returnData = communicationManager.getPumpTime(); - MedtronicUtil.getInstance().setPumpTime(null); + medtronicUtil.setPumpTime(null); } break; @@ -143,7 +141,7 @@ public class MedtronicUITask { break; default: { - LOG.warn("This commandType is not supported (yet) - {}.", commandType); + aapsLogger.warn(LTag.PUMP, "This commandType is not supported (yet) - {}.", commandType); // invalid = true; responseType = MedtronicUIResponseType.Invalid; } @@ -174,12 +172,12 @@ public class MedtronicUITask { } - public Double getDoubleFromParameters(int index) { + Double getDoubleFromParameters(int index) { return (Double) parameters[index]; } - public Integer getIntegerFromParameters(int index) { + private Integer getIntegerFromParameters(int index) { return (Integer) parameters[index]; } @@ -196,25 +194,24 @@ public class MedtronicUITask { void postProcess(MedtronicUIPostprocessor postprocessor) { - if (isLogEnabled()) - LOG.debug("MedtronicUITask: @@@ In execute. {}", commandType); + aapsLogger.debug(LTag.PUMP, "MedtronicUITask: @@@ In execute. {}", commandType); if (responseType == MedtronicUIResponseType.Data) { postprocessor.postProcessData(this); } if (responseType == MedtronicUIResponseType.Invalid) { - RxBus.Companion.getINSTANCE().send(new EventMedtronicDeviceStatusChange(PumpDeviceState.ErrorWhenCommunicating, + rxBus.send(new EventMedtronicDeviceStatusChange(PumpDeviceState.ErrorWhenCommunicating, "Unsupported command in MedtronicUITask")); } else if (responseType == MedtronicUIResponseType.Error) { - RxBus.Companion.getINSTANCE().send(new EventMedtronicDeviceStatusChange(PumpDeviceState.ErrorWhenCommunicating, + rxBus.send(new EventMedtronicDeviceStatusChange(PumpDeviceState.ErrorWhenCommunicating, errorDescription)); } else { - RxBus.Companion.getINSTANCE().send(new EventMedtronicPumpValuesChanged()); + rxBus.send(new EventMedtronicPumpValuesChanged()); medtronicPumpStatus.setLastCommunicationToNow(); } - MedtronicUtil.getInstance().setCurrentCommand(null); + medtronicUtil.setCurrentCommand(null); } @@ -223,16 +220,11 @@ public class MedtronicUITask { } - public Object getParameter(int index) { + Object getParameter(int index) { return parameters[index]; } - private boolean isLogEnabled() { - return L.isEnabled(L.PUMP); - } - - public MedtronicUIResponseType getResponseType() { return this.responseType; } 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 b349f9c341..cf8aecba91 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 @@ -22,6 +22,8 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.Riley import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; +import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUIComm; +import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUIPostprocessor; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; @@ -34,8 +36,10 @@ public class RileyLinkMedtronicService extends RileyLinkService { @Inject HasAndroidInjector injector; @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicUtil medtronicUtil; + @Inject MedtronicUIPostprocessor medtronicUIPostprocessor; - // cache of most recently received set of pump history pages. Probably shouldn't be here. + + private MedtronicUIComm medtronicUIComm; private MedtronicCommunicationManager medtronicCommunicationManager; private IBinder mBinder = new LocalBinder(); @@ -87,6 +91,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { // init rileyLinkCommunicationManager medtronicCommunicationManager = new MedtronicCommunicationManager(injector, rfspy); + medtronicUIComm = new MedtronicUIComm(injector, aapsLogger, medtronicUtil, medtronicUIPostprocessor, medtronicCommunicationManager); aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed"); medtronicUtil.setMedtronicService(this); @@ -103,6 +108,10 @@ public class RileyLinkMedtronicService extends RileyLinkService { } + public MedtronicUIComm getMedtronicUIComm() { + return medtronicUIComm; + } + public void setPumpIDString(String pumpID) { if (pumpID.length() != 6) { aapsLogger.error("setPumpIDString: invalid pump id string: " + pumpID); 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 5c0578c3c0..a264178fd9 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,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.medtronic.util; -import android.content.Context; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -17,7 +15,6 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -28,7 +25,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO; From 7b9247b1a09829adfd4238745f9eea13801470a4 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 12:25:07 +0200 Subject: [PATCH 07/23] MDT refactor pass 6 --- .../pump/common/PumpPluginAbstract.java | 38 +-- .../plugins/pump/common/data/PumpStatus.java | 19 -- .../dialog/RileyLinkBLEScanActivity.java | 5 +- .../RileyLinkStatusGeneralFragment.java | 4 +- .../pump/medtronic/MedtronicFragment.kt | 15 +- .../pump/medtronic/MedtronicPumpPlugin.java | 27 +- .../comm/MedtronicCommunicationManager.java | 194 +++++-------- .../medtronic/comm/MedtronicConverter.java | 10 +- .../medtronic/comm/ui/MedtronicUIComm.java | 3 - .../comm/ui/MedtronicUIPostprocessor.java | 28 +- .../medtronic/data/MedtronicHistoryData.java | 5 +- .../pump/medtronic/data/dto/BasalProfile.java | 9 +- .../medtronic/driver/MedtronicPumpStatus.java | 271 +----------------- .../service/RileyLinkMedtronicService.java | 229 ++++++++++++++- .../pump/medtronic/util/MedtronicUtil.java | 15 - 15 files changed, 388 insertions(+), 484 deletions(-) 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 8bf2f21455..669adeff31 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 @@ -72,8 +72,6 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump)); */ protected PumpDescription pumpDescription = new PumpDescription(); - @Deprecated // TODO remove this reference - protected PumpStatus pumpStatus; protected ServiceConnection serviceConnection = null; protected boolean serviceRunning = false; // protected boolean isInitialized = false; @@ -158,9 +156,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI */ public abstract Class getServiceClass(); - public PumpStatus getPumpStatusData() { - return pumpStatus; - } + public abstract PumpStatus getPumpStatusData(); public boolean isInitialized() { @@ -224,12 +220,6 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI aapsLogger.debug(LTag.PUMP, "finishHandshaking [PumpPluginAbstract] - default (empty) implementation."); } - - public void getPumpStatus() { - aapsLogger.debug(LTag.PUMP, "getPumpStatus [PumpPluginAbstract] - Not implemented."); - } - - // Upload to pump new basal profile @NonNull public PumpEnactResult setNewBasalProfile(Profile profile) { aapsLogger.debug(LTag.PUMP, "setNewBasalProfile [PumpPluginAbstract] - Not implemented."); @@ -245,7 +235,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public long lastDataTime() { aapsLogger.debug(LTag.PUMP, "lastDataTime [PumpPluginAbstract]."); - return pumpStatus.lastConnection; + return getPumpStatusData().lastConnection; } @@ -334,7 +324,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI @NonNull @Override public JSONObject getJSONStatus(Profile profile, String profileName) { - if ((pumpStatus.lastConnection + 5 * 60 * 1000L) < System.currentTimeMillis()) { + if ((getPumpStatusData().lastConnection + 5 * 60 * 1000L) < System.currentTimeMillis()) { return new JSONObject(); } @@ -343,8 +333,8 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI JSONObject status = new JSONObject(); JSONObject extended = new JSONObject(); try { - battery.put("percent", pumpStatus.batteryRemaining); - status.put("status", pumpStatus.pumpStatusType != null ? pumpStatus.pumpStatusType.getStatus() : "normal"); + battery.put("percent", getPumpStatusData().batteryRemaining); + status.put("status", getPumpStatusData().pumpStatusType != null ? getPumpStatusData().pumpStatusType.getStatus() : "normal"); extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); try { extended.put("ActiveProfile", profileName); @@ -371,7 +361,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI pump.put("battery", battery); pump.put("status", status); pump.put("extended", extended); - pump.put("reservoir", pumpStatus.reservoirRemainingUnits); + pump.put("reservoir", getPumpStatusData().reservoirRemainingUnits); pump.put("clock", DateUtil.toISOString(new Date())); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); @@ -384,14 +374,14 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI @NonNull @Override public String shortStatus(boolean veryShort) { String ret = ""; - if (pumpStatus.lastConnection != 0) { - long agoMsec = System.currentTimeMillis() - pumpStatus.lastConnection; + if (getPumpStatusData().lastConnection != 0) { + long agoMsec = System.currentTimeMillis() - getPumpStatusData().lastConnection; int agoMin = (int) (agoMsec / 60d / 1000d); ret += "LastConn: " + agoMin + " min ago\n"; } - if (pumpStatus.lastBolusTime != null && pumpStatus.lastBolusTime.getTime() != 0) { - ret += "LastBolus: " + DecimalFormatter.to2Decimal(pumpStatus.lastBolusAmount) + "U @" + // - android.text.format.DateFormat.format("HH:mm", pumpStatus.lastBolusTime) + "\n"; + if (getPumpStatusData().lastBolusTime != null && getPumpStatusData().lastBolusTime.getTime() != 0) { + ret += "LastBolus: " + DecimalFormatter.to2Decimal(getPumpStatusData().lastBolusAmount) + "U @" + // + android.text.format.DateFormat.format("HH:mm", getPumpStatusData().lastBolusTime) + "\n"; } TemporaryBasal activeTemp = activePlugin.getActiveTreatments().getRealTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { @@ -406,9 +396,9 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI // ret += "TDD: " + DecimalFormatter.to0Decimal(pumpStatus.dailyTotalUnits) + " / " // + pumpStatus.maxDailyTotalUnits + " U\n"; // } - ret += "IOB: " + pumpStatus.iob + "U\n"; - ret += "Reserv: " + DecimalFormatter.to0Decimal(pumpStatus.reservoirRemainingUnits) + "U\n"; - ret += "Batt: " + pumpStatus.batteryRemaining + "\n"; + ret += "IOB: " + getPumpStatusData().iob + "U\n"; + ret += "Reserv: " + DecimalFormatter.to0Decimal(getPumpStatusData().reservoirRemainingUnits) + "U\n"; + ret += "Batt: " + getPumpStatusData().batteryRemaining + "\n"; return ret; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java index 8f241feb3d..b704de584f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java @@ -40,7 +40,6 @@ public abstract class PumpStatus { public Double dailyTotalUnits; public String maxDailyTotalUnits; public boolean validBasalRateProfileSelectedOnPump = true; - public PumpType pumpType = PumpType.GenericAAPS; public ProfileStore profileStore; public String units; // Constants.MGDL or Constants.MMOL public PumpStatusType pumpStatusType = PumpStatusType.Running; @@ -70,23 +69,5 @@ public abstract class PumpStatus { this.lastErrorConnection = System.currentTimeMillis(); } - public abstract String getErrorInfo(); - - - public abstract void refreshConfiguration(); - - - public PumpType getPumpType() { - return pumpType; - } - - - public void setPumpType(PumpType pumpType) { - this.pumpType = pumpType; - } - - // public Date last_bolus_time; - // public double last_bolus_amount = 0; - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java index 389a122ca6..7abf1db894 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java @@ -47,6 +47,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCons 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.utils.LocationHelper; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; @@ -62,7 +63,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { @Inject ResourceHelper resourceHelper; @Inject RileyLinkUtil rileyLinkUtil; @Inject MedtronicUtil medtronicUtil; - @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject MedtronicPumpPlugin medtronicPumpPlugin; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 30241; // arbitrary. private static final int REQUEST_ENABLE_BT = 30242; // arbitrary @@ -113,7 +114,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { rileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress); - medtronicPumpStatus.verifyConfiguration(); // force reloading of address + medtronicPumpPlugin.getRileyLinkService().verifyConfiguration(); // force reloading of address rxBus.send(new EventMedtronicPumpConfigurationChanged()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index b5dc772d80..4365c52757 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java @@ -21,6 +21,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -35,6 +36,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re @Inject MedtronicUtil medtronicUtil; @Inject MedtronicPumpStatus medtronicPumpStatus; @Inject ResourceHelper resourceHelper; + @Inject MedtronicPumpPlugin medtronicPumpPlugin; TextView connectionStatus; TextView configuredAddress; @@ -128,7 +130,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re if (medtronicPumpStatus != null) { this.deviceType.setText(resourceHelper.gs(RileyLinkTargetDevice.MedtronicPump.getResourceId())); - this.deviceModel.setText(medtronicPumpStatus.pumpType.getDescription()); + this.deviceModel.setText(medtronicPumpPlugin.getPumpDescription().pumpType.getDescription()); this.serialNumber.setText(medtronicPumpStatus.serialNumber); this.pumpFrequency.setText(resourceHelper.gs(medtronicPumpStatus.pumpFrequency.equals("medtronic_pump_frequency_us_ca") ? R.string.medtronic_pump_frequency_us_ca : R.string.medtronic_pump_frequency_worldwide)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index b14412d7c1..8d9b24c31b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -37,9 +37,9 @@ import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.WarnColors +import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.android.schedulers.AndroidSchedulers @@ -88,7 +88,7 @@ class MedtronicFragment : DaggerFragment() { medtronic_pump_status.text = "{fa-bed}" medtronic_history.setOnClickListener { - if (medtronicPumpStatus.verifyConfiguration()) { + if (medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() == true) { startActivity(Intent(context, MedtronicHistoryActivity::class.java)) } else { displayNotConfiguredDialog() @@ -96,7 +96,7 @@ class MedtronicFragment : DaggerFragment() { } medtronic_refresh.setOnClickListener { - if (!medtronicPumpStatus.verifyConfiguration()) { + if (medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() != true) { displayNotConfiguredDialog() } else { medtronic_refresh.isEnabled = false @@ -110,7 +110,7 @@ class MedtronicFragment : DaggerFragment() { } medtronic_stats.setOnClickListener { - if (medtronicPumpStatus.verifyConfiguration()) { + if (medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() == true) { startActivity(Intent(context, RileyLinkStatusActivity::class.java)) } else { displayNotConfiguredDialog() @@ -150,7 +150,7 @@ class MedtronicFragment : DaggerFragment() { .observeOn(AndroidSchedulers.mainThread()) .subscribe({ aapsLogger.debug(LTag.PUMP, "EventMedtronicPumpConfigurationChanged triggered") - medtronicPumpStatus.verifyConfiguration() + medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() updateGUI() }, { fabricPrivacy.logException(it) }) disposable += rxBus @@ -185,7 +185,7 @@ class MedtronicFragment : DaggerFragment() { medtronicPumpStatus.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) medtronicPumpStatus.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) medtronicPumpStatus.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) - else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) + else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) } medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) @@ -322,7 +322,7 @@ class MedtronicFragment : DaggerFragment() { ?: "" // battery - if (medtronicUtil.getBatteryType() == BatteryType.None || medtronicPumpStatus.batteryVoltage == null) { + if (medtronicPumpStatus.batteryType == BatteryType.None || medtronicPumpStatus.batteryVoltage == null) { medtronic_pumpstate_battery.text = "{fa-battery-" + medtronicPumpStatus.batteryRemaining / 25 + "} " } else { medtronic_pumpstate_battery.text = "{fa-battery-" + medtronicPumpStatus.batteryRemaining / 25 + "} " + medtronicPumpStatus.batteryRemaining + "%" + String.format(" (%.2f V)", medtronicPumpStatus.batteryVoltage) @@ -333,6 +333,7 @@ class MedtronicFragment : DaggerFragment() { medtronic_reservoir.text = resourceHelper.gs(R.string.reservoirvalue, medtronicPumpStatus.reservoirRemainingUnits, medtronicPumpStatus.reservoirFullUnits) warnColors.setColorInverse(medtronic_reservoir, medtronicPumpStatus.reservoirRemainingUnits, 50.0, 20.0) + medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() medtronic_errors.text = medtronicPumpStatus.errorInfo } } 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 cdc826e887..15f4ccff12 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 @@ -50,6 +50,7 @@ import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; +import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; @@ -167,7 +168,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter SystemClock.sleep(5000); aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service"); - if (medtronicPumpStatus.setNotInPreInit()) { + if (rileyLinkMedtronicService.setNotInPreInit()) { break; } } @@ -208,12 +209,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter medtronicPumpStatus.lastDataTime = medtronicPumpStatus.lastConnection; medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection; - medtronicPumpStatus.refreshConfiguration(); + if (rileyLinkMedtronicService != null) rileyLinkMedtronicService.verifyConfiguration(); aapsLogger.debug(LTag.PUMP, "initPumpStatusData: " + this.medtronicPumpStatus); - this.pumpStatus = medtronicPumpStatus; - // this is only thing that can change, by being configured pumpDescription.maxTempAbsolute = (medtronicPumpStatus.maxBasal != null) ? medtronicPumpStatus.maxBasal : 35.0d; @@ -285,6 +284,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return RileyLinkMedtronicService.class; } + @Override public PumpStatus getPumpStatusData() { + return medtronicPumpStatus; + } @Override public String deviceID() { @@ -633,7 +635,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter boolean invalid = false; Double[] basalsByHour = medtronicPumpStatus.basalsByHour; - PumpType pumpType = medtronicPumpStatus.getPumpType(); aapsLogger.debug(LTag.PUMP, "Current Basals (h): " + (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour))); @@ -647,7 +648,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter for (Profile.ProfileValue basalValue : profile.getBasalValues()) { - double basalValueValue = pumpType.determineCorrectBasalSize(basalValue.value); + double basalValueValue = pumpDescription.pumpType.determineCorrectBasalSize(basalValue.value); int hour = basalValue.timeAsSeconds / (60 * 60); @@ -1046,7 +1047,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew); } else { double absoluteValue = profile.getBasal() * (percent / 100.0d); - absoluteValue = medtronicPumpStatus.pumpType.determineCorrectBasalSize(absoluteValue); + absoluteValue = pumpDescription.pumpType.determineCorrectBasalSize(absoluteValue); aapsLogger.warn(LTag.PUMP, "setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% (" + percent + "). This will start setTempBasalAbsolute, with calculated value (" + absoluteValue + "). Result might not be 100% correct."); return setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew); } @@ -1083,7 +1084,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (this.medtronicPumpStatus.basalProfileStatus != BasalProfileStatus.NotInitialized && medtronicHistoryData.hasBasalProfileChanged()) { - medtronicHistoryData.processLastBasalProfileChange(medtronicPumpStatus); + medtronicHistoryData.processLastBasalProfileChange(pumpDescription.pumpType, medtronicPumpStatus); } PumpDriverState previousState = this.pumpState; @@ -1373,12 +1374,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @NonNull @Override public ManufacturerType manufacturer() { - return medtronicPumpStatus.pumpType.getManufacturer(); + return pumpDescription.pumpType.getManufacturer(); } @NonNull @Override public PumpType model() { - return medtronicPumpStatus.pumpType; + return pumpDescription.pumpType; } @NonNull @Override @@ -1462,14 +1463,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @NonNull private BasalProfile convertProfileToMedtronicProfile(Profile profile) { - PumpType pumpType = pumpStatus.pumpType; - BasalProfile basalProfile = new BasalProfile(); for (int i = 0; i < 24; i++) { double rate = profile.getBasalTimeFromMidnight(i * 60 * 60); - double v = pumpType.determineCorrectBasalSize(rate); + double v = pumpDescription.pumpType.determineCorrectBasalSize(rate); BasalProfileEntry basalEntry = new BasalProfileEntry(v, i, 0); basalProfile.addEntry(basalEntry); @@ -1516,7 +1515,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter switch (mcat) { case WakeUpAndTune: { - if (medtronicPumpStatus.verifyConfiguration()) { + if (rileyLinkMedtronicService.verifyConfiguration()) { ServiceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); } else { Intent i = new Intent(context, ErrorHelperActivity.class); 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 7c3dff66fb..250d819990 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 @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm; import android.os.SystemClock; import org.joda.time.LocalDateTime; -import org.slf4j.Logger; import java.util.Calendar; import java.util.GregorianCalendar; @@ -13,8 +12,8 @@ import java.util.Map; import javax.inject.Inject; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; @@ -29,6 +28,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; 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.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistoryPage; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry; @@ -60,9 +60,10 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; */ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager { + @Inject AAPSLogger aapsLogger; @Inject MedtronicPumpStatus medtronicPumpStatus; + @Inject MedtronicPumpPlugin medtronicPumpPlugin; - private final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); private final int MAX_COMMAND_TRIES = 3; private final int DEFAULT_TIMEOUT = 2000; private final long RILEYLINK_TIMEOUT = 15 * 60 * 1000; // 15 min @@ -123,8 +124,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager for (int retry = 0; retry < 5; retry++) { - if (isLogEnabled()) - LOG.debug("isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : "")); + aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : "")); boolean connected = connectToDevice(); @@ -158,11 +158,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, (byte) 0, (byte) 0, 25000, (byte) 0); - if (isLogEnabled()) - LOG.info("wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); if (rfSpyResponse.wasTimeout()) { - LOG.error("isDeviceReachable. Failed to find pump (timeout)."); + aapsLogger.error(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to find pump (timeout)."); } else if (rfSpyResponse.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(); @@ -175,12 +174,12 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload(), PumpMessage.class); if (!pumpResponse.isValid()) { - LOG.warn("Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), + aapsLogger.warn(LTag.PUMPBTCOMM, "Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout()); } else { // radioResponse.rssi; - Object dataResponse = medtronicConverter.convertResponse(MedtronicCommandType.PumpModel, + Object dataResponse = medtronicConverter.convertResponse(medtronicPumpPlugin.getPumpDescription().pumpType, MedtronicCommandType.PumpModel, pumpResponse.getRawContent()); MedtronicDeviceType pumpModel = (MedtronicDeviceType) dataResponse; @@ -190,9 +189,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel); } - if (isLogEnabled()) - LOG.debug("isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, - radioResponse.rssi); + aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, + radioResponse.rssi); if (valid) { if (state == PumpDeviceState.PumpUnreachable) @@ -212,17 +210,17 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } else { - LOG.warn("isDeviceReachable. Failed to parse radio response: " + aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to parse radio response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } } catch (RileyLinkCommunicationException e) { - LOG.warn("isDeviceReachable. Failed to decode radio response: " + aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to decode radio response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } } else { - LOG.warn("isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } return false; @@ -238,7 +236,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private PumpMessage runCommandWithArgs(PumpMessage msg) throws RileyLinkCommunicationException { if (debugSetCommands) - LOG.debug("Run command with Args: "); + aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Args: "); PumpMessage rval; PumpMessage shortMessage = makePumpMessage(msg.commandType, new CarelinkShortMessageBody(new byte[]{0})); @@ -246,16 +244,15 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage shortResponse = sendAndListen(shortMessage); if (shortResponse.commandType == MedtronicCommandType.CommandACK) { if (debugSetCommands) - LOG.debug("Run command with Args: Got ACK response"); + aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Args: Got ACK response"); rval = sendAndListen(msg); if (debugSetCommands) - LOG.debug("2nd Response: {}", rval); + aapsLogger.debug(LTag.PUMPBTCOMM, "2nd Response: {}", rval); return rval; } else { - if (isLogEnabled()) - LOG.error("runCommandWithArgs: Pump did not ack Attention packet"); + aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithArgs: Pump did not ack Attention packet"); return new PumpMessage("No ACK after Attention packet."); } } @@ -264,8 +261,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private PumpMessage runCommandWithFrames(MedtronicCommandType commandType, List> frames) throws RileyLinkCommunicationException { - if (isLogEnabled()) - LOG.debug("Run command with Frames: {}", commandType.name()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: {}", commandType.name()); PumpMessage rval = null; PumpMessage shortMessage = makePumpMessage(commandType, new CarelinkShortMessageBody(new byte[]{0})); @@ -273,13 +269,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage shortResponse = sendAndListen(shortMessage); if (shortResponse.commandType != MedtronicCommandType.CommandACK) { - if (isLogEnabled()) - LOG.error("runCommandWithFrames: Pump did not ack Attention packet"); + aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithFrames: Pump did not ack Attention packet"); return new PumpMessage("No ACK after start message."); } else { - if (isLogEnabled()) - LOG.debug("Run command with Frames: Got ACK response for Attention packet"); + aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: Got ACK response for Attention packet"); } int frameNr = 1; @@ -288,24 +282,23 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager byte[] frameData = MedtronicUtil.getInstance().createByteArray(frame); - // LOG.debug("Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); + // aapsLogger.debug(LTag.PUMPBTCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(frameData)); rval = sendAndListen(msg); - // LOG.debug("PumpResponse: " + rval); + // aapsLogger.debug(LTag.PUMPBTCOMM,"PumpResponse: " + rval); if (rval.commandType != MedtronicCommandType.CommandACK) { - LOG.error("runCommandWithFrames: Pump did not ACK frame #{}", frameNr); + aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithFrames: Pump did not ACK frame #{}", frameNr); - LOG.error("Run command with Frames FAILED (command={}, response={})", commandType.name(), + aapsLogger.error(LTag.PUMPBTCOMM, "Run command with Frames FAILED (command={}, response={})", commandType.name(), rval.toString()); return new PumpMessage("No ACK after frame #" + frameNr); } else { - if (isLogEnabled()) - LOG.debug("Run command with Frames: Got ACK response for frame #{}", (frameNr)); + aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: Got ACK response for frame #{}", (frameNr)); } frameNr++; @@ -324,8 +317,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false); - if (isLogEnabled()) - LOG.debug("Current command: " + MedtronicUtil.getInstance().getCurrentCommand()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + MedtronicUtil.getInstance().getCurrentCommand()); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); boolean doneWithError = false; @@ -337,9 +329,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, new GetHistoryPageCarelinkMessageBody(pageNumber)); - if (isLogEnabled()) - LOG.info("getPumpHistory: Page {}", pageNumber); - // LOG.info("getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); + aapsLogger.info(LTag.PUMPBTCOMM, "getPumpHistory: Page {}", pageNumber); + // aapsLogger.info(LTag.PUMPBTCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); // Ask the pump to transfer history (we get first frame?) PumpMessage firstResponse = null; @@ -354,8 +345,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager failed = false; break; } catch (RileyLinkCommunicationException e) { - if (isLogEnabled()) - LOG.error("First call for PumpHistory failed (retry={})", retries); + aapsLogger.error(LTag.PUMPBTCOMM, "First call for PumpHistory failed (retry={})", retries); failed = true; } } @@ -365,7 +355,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return pumpTotalResult; } - // LOG.info("getPumpHistoryPage("+pageNumber+"): " + ByteUtil.shortHexString(firstResponse.getContents())); + // aapsLogger.info(LTag.PUMPBTCOMM,"getPumpHistoryPage("+pageNumber+"): " + ByteUtil.shortHexString(firstResponse.getContents())); PumpMessage ackMsg = makePumpMessage(MedtronicCommandType.CommandACK, new PumpAckMessageBody()); GetHistoryPageCarelinkMessageBody currentResponse = new GetHistoryPageCarelinkMessageBody(firstResponse @@ -382,8 +372,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager && currentResponse.getFrameNumber() == expectedFrameNum) { // success! got a frame. if (frameData.length != 64) { - if (isLogEnabled()) - LOG.warn("Expected frame of length 64, got frame of length " + frameData.length); + aapsLogger.warn(LTag.PUMPBTCOMM, "Expected frame of length 64, got frame of length " + frameData.length); // but append it anyway? } // handle successful frame data @@ -393,8 +382,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, currentResponse.getFrameNumber()); - if (isLogEnabled()) - LOG.info("getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber); + aapsLogger.info(LTag.PUMPBTCOMM, "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++; @@ -403,22 +391,18 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } else { if (frameData == null) { - if (isLogEnabled()) - LOG.error("null frame data, retrying"); + aapsLogger.error(LTag.PUMPBTCOMM, "null frame data, retrying"); } else if (currentResponse.getFrameNumber() != expectedFrameNum) { - if (isLogEnabled()) - LOG.warn("Expected frame number {}, received {} (retrying)", expectedFrameNum, - currentResponse.getFrameNumber()); + aapsLogger.warn(LTag.PUMPBTCOMM, "Expected frame number {}, received {} (retrying)", expectedFrameNum, + currentResponse.getFrameNumber()); } else if (frameData.length == 0) { - if (isLogEnabled()) - LOG.warn("Frame has zero length, retrying"); + aapsLogger.warn(LTag.PUMPBTCOMM, "Frame has zero length, retrying"); } failures++; if (failures == 6) { - if (isLogEnabled()) - LOG.error( - "getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.", - expectedFrameNum, pageNumber); + aapsLogger.error(LTag.PUMPBTCOMM, + "getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.", + expectedFrameNum, pageNumber); done = true; // failure completion. doneWithError = true; } @@ -434,30 +418,26 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager nextMsg = sendAndListen(ackMsg); break; } catch (RileyLinkCommunicationException e) { - if (isLogEnabled()) - LOG.error("Problem acknowledging frame response. (retry={})", retries); + aapsLogger.error(LTag.PUMPBTCOMM, "Problem acknowledging frame response. (retry={})", retries); } } if (nextMsg != null) currentResponse = new GetHistoryPageCarelinkMessageBody(nextMsg.getMessageBody().getTxData()); else { - if (isLogEnabled()) - LOG.error("We couldn't acknowledge frame from pump, aborting operation."); + aapsLogger.error(LTag.PUMPBTCOMM, "We couldn't acknowledge frame from pump, aborting operation."); } } } if (rawHistoryPage.getLength() != 1024) { - if (isLogEnabled()) - LOG.warn("getPumpHistory: short page. Expected length of 1024, found length of " - + rawHistoryPage.getLength()); + aapsLogger.warn(LTag.PUMPBTCOMM, "getPumpHistory: short page. Expected length of 1024, found length of " + + rawHistoryPage.getLength()); doneWithError = true; } if (!rawHistoryPage.isChecksumOK()) { - if (isLogEnabled()) - LOG.error("getPumpHistory: checksum is wrong"); + aapsLogger.error(LTag.PUMPBTCOMM, "getPumpHistory: checksum is wrong"); doneWithError = true; } @@ -471,13 +451,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager List medtronicHistoryEntries = pumpHistoryDecoder .processPageAndCreateRecords(rawHistoryPage); - if (isLogEnabled()) - LOG.debug("getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); + aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); pumpTotalResult.addHistoryEntries(medtronicHistoryEntries, pageNumber); - if (isLogEnabled()) - LOG.debug("getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); + aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); if (pumpTotalResult.isSearchFinished()) { MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); @@ -588,8 +566,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private Object sendAndGetResponseWithCheck(MedtronicCommandType commandType, byte[] bodyData) { - if (isLogEnabled()) - LOG.debug("getDataFromPump: {}", commandType); + aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType); for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { @@ -603,12 +580,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (check == null) { - Object dataResponse = medtronicConverter.convertResponse(commandType, response.getRawContent()); + Object dataResponse = medtronicConverter.convertResponse(medtronicPumpPlugin.getPumpDescription().pumpType, commandType, response.getRawContent()); if (dataResponse != null) { this.errorMessage = null; - if (isLogEnabled()) - LOG.debug("Converted response for {} is {}.", commandType.name(), dataResponse); + aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), dataResponse); return dataResponse; } else { @@ -620,8 +596,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } catch (RileyLinkCommunicationException e) { - if (isLogEnabled()) - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.warn(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } @@ -634,8 +609,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (!response.isValid()) { String responseData = String.format("%s: Invalid response.", method); - if (isLogEnabled()) - LOG.warn(responseData); + aapsLogger.warn(LTag.PUMPBTCOMM, responseData); return responseData; } @@ -643,7 +617,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (contents != null) { if (contents.length >= expectedLength) { - LOG.trace("{}: Content: {}", method, ByteUtil.shortHexString(contents)); + aapsLogger.debug(LTag.PUMPBTCOMM, "{}: Content: {}", method, ByteUtil.shortHexString(contents)); return null; } else { @@ -651,13 +625,12 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager "%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, "" + expectedLength, "" + contents.length); - if (isLogEnabled()) - LOG.warn(responseData); + aapsLogger.warn(LTag.PUMPBTCOMM, responseData); return responseData; } } else { String responseData = String.format("%s: Cannot return data. Null response.", method); - LOG.warn(responseData); + aapsLogger.warn(LTag.PUMPBTCOMM, responseData); return responseData; } } @@ -689,8 +662,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicCommandType commandType = MedtronicCommandType.GetBasalProfileSTD; - if (isLogEnabled()) - LOG.debug("getDataFromPump: {}", commandType); + aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType); MedtronicUtil.getInstance().setCurrentCommand(commandType); @@ -709,8 +681,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())); +// aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent())); +// aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData())); String check = checkResponseContent(response, commandType.commandDescription, 1); @@ -726,8 +698,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager response = sendAndListen(ackMsg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); -// LOG.debug("{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent())); -// LOG.debug("{} Response: {}", runs, +// aapsLogger.debug(LTag.PUMPBTCOMM,"{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent())); +// aapsLogger.debug(LTag.PUMPBTCOMM,"{} Response: {}", runs, // HexDump.toHexStringDisplayable(response2.getMessageBody().getTxData())); String check2 = checkResponseContent(response, commandType.commandDescription, 1); @@ -738,7 +710,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } else { this.errorMessage = check2; - LOG.error("Error with response got GetProfile: " + check2); + aapsLogger.error(LTag.PUMPBTCOMM, "Error with response got GetProfile: " + check2); } } @@ -746,11 +718,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager errorMessage = check; } - BasalProfile basalProfile = (BasalProfile) medtronicConverter.convertResponse(commandType, data); + BasalProfile basalProfile = (BasalProfile) medtronicConverter.convertResponse(medtronicPumpPlugin.getPumpDescription().pumpType, commandType, data); if (basalProfile != null) { - if (isLogEnabled()) - LOG.debug("Converted response for {} is {}.", commandType.name(), basalProfile); + aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); MedtronicUtil.getInstance().setCurrentCommand(null); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); @@ -759,11 +730,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } catch (RileyLinkCommunicationException e) { - LOG.error("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.error(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } - LOG.warn("Error reading profile in max retries."); + aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading profile in max retries."); MedtronicUtil.getInstance().setCurrentCommand(null); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); @@ -781,7 +752,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager int last = responseRaw.length - 1; - LOG.debug("Length: " + data.length); + aapsLogger.debug(LTag.PUMPBTCOMM, "Length: " + data.length); if (data.length >= BasalProfile.MAX_RAW_DATA_SIZE) { return false; @@ -833,8 +804,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public Boolean setBolus(double units) { - if (isLogEnabled()) - LOG.info("setBolus: " + units); + aapsLogger.info(LTag.PUMPBTCOMM, "setBolus: " + units); return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getInstance().getBolusStrokes(units)); @@ -843,8 +813,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public boolean setTBR(TempBasalPair tbr) { - if (isLogEnabled()) - LOG.info("setTBR: " + tbr.getDescription()); + aapsLogger.info(LTag.PUMPBTCOMM, "setTBR: " + tbr.getDescription()); return setCommand(MedtronicCommandType.SetTemporaryBasal, tbr.getAsRawData()); } @@ -855,8 +824,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager GregorianCalendar gc = new GregorianCalendar(); gc.add(Calendar.SECOND, 5); - if (isLogEnabled()) - LOG.info("setPumpTime: " + DateTimeUtil.toString(gc)); + aapsLogger.info(LTag.PUMPBTCOMM, "setPumpTime: " + DateTimeUtil.toString(gc)); int i = 1; byte[] data = new byte[8]; @@ -873,7 +841,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager data[i + 5] = (byte) (gc.get(Calendar.MONTH) + 1); data[i + 6] = (byte) gc.get(Calendar.DAY_OF_MONTH); - //LOG.info("setPumpTime: Body: " + ByteUtil.getHex(data)); + //aapsLogger.info(LTag.PUMPBTCOMM,"setPumpTime: Body: " + ByteUtil.getHex(data)); return setCommand(MedtronicCommandType.SetRealTimeClock, data); @@ -889,7 +857,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager wakeUp(false); if (debugSetCommands) - LOG.debug("{}: Body - {}", commandType.getCommandDescription(), + aapsLogger.debug(LTag.PUMPBTCOMM, "{}: Body - {}", commandType.getCommandDescription(), ByteUtil.getHex(body)); PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(body)); @@ -897,17 +865,16 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage pumpMessage = runCommandWithArgs(msg); if (debugSetCommands) - LOG.debug("{}: {}", commandType.getCommandDescription(), pumpMessage.getResponseContent()); + aapsLogger.debug(LTag.PUMPBTCOMM, "{}: {}", commandType.getCommandDescription(), pumpMessage.getResponseContent()); if (pumpMessage.commandType == MedtronicCommandType.CommandACK) { return true; } else { - LOG.warn("We received non-ACK response from pump: {}", pumpMessage.getResponseContent()); + aapsLogger.warn(LTag.PUMPBTCOMM, "We received non-ACK response from pump: {}", pumpMessage.getResponseContent()); } } catch (RileyLinkCommunicationException e) { - if (isLogEnabled()) - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.warn(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } @@ -943,24 +910,19 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return true; } catch (RileyLinkCommunicationException e) { - LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.warn(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } if (responseMessage != null) - LOG.warn("Set Basal Profile: Invalid response: commandType={},rawData={}", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent())); + aapsLogger.warn(LTag.PUMPBTCOMM, "Set Basal Profile: Invalid response: commandType={},rawData={}", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent())); else - LOG.warn("Set Basal Profile: Null response."); + aapsLogger.warn(LTag.PUMPBTCOMM, "Set Basal Profile: Null response."); } return false; } - - private boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); - } - @Override public PumpStatus getPumpStatus() { return medtronicPumpStatus; } 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 cec4df9140..191b752131 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 @@ -3,13 +3,13 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm; import org.joda.time.IllegalFieldValueException; import org.joda.time.LocalDateTime; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +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.StringUtil; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile; @@ -33,7 +33,7 @@ public class MedtronicConverter { MedtronicDeviceType pumpModel; - public Object convertResponse(MedtronicCommandType commandType, byte[] rawContent) { + public Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) { if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) { LOG.warn("Content is empty or too short, no data to convert (type={},isNull={},length={})", @@ -67,7 +67,7 @@ public class MedtronicConverter { case GetBasalProfileSTD: case GetBasalProfileA: case GetBasalProfileB: { - return decodeBasalProfile(rawContent); + return decodeBasalProfile(pumpType, rawContent); } @@ -96,11 +96,11 @@ public class MedtronicConverter { } - private BasalProfile decodeBasalProfile(byte[] rawContent) { + private BasalProfile decodeBasalProfile(PumpType pumpType, byte[] rawContent) { BasalProfile basalProfile = new BasalProfile(rawContent); - return basalProfile.verify() ? basalProfile : null; + return basalProfile.verify(pumpType) ? basalProfile : null; } 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 c65d96b1be..aca286f7a6 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 @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; -import javax.inject.Inject; - import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -20,7 +18,6 @@ public class MedtronicUIComm { private final MedtronicCommunicationManager medtronicCommunicationManager; private final MedtronicUIPostprocessor medtronicUIPostprocessor; - @Inject public MedtronicUIComm( HasAndroidInjector injector, AAPSLogger aapsLogger, 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 d4f6a5d377..39cefd8395 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 @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; -import org.jetbrains.annotations.NotNull; import org.joda.time.DateTimeZone; import org.joda.time.Duration; @@ -13,6 +12,7 @@ import javax.inject.Singleton; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; 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; @@ -32,19 +32,27 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; @Singleton public class MedtronicUIPostprocessor { - @NotNull private final AAPSLogger aapsLogger; - @NotNull private final RxBusWrapper rxBus; - @NotNull private final ResourceHelper resourceHelper; - @NotNull private final MedtronicUtil medtronicUtil; - @NotNull private final MedtronicPumpStatus medtronicPumpStatus; + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + private final ResourceHelper resourceHelper; + private final MedtronicUtil medtronicUtil; + private final MedtronicPumpStatus medtronicPumpStatus; + private final MedtronicPumpPlugin medtronicPumpPlugin; @Inject - public MedtronicUIPostprocessor(AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, MedtronicUtil medtronicUtil, MedtronicPumpStatus medtronicPumpStatus) { + public MedtronicUIPostprocessor( + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + ResourceHelper resourceHelper, + MedtronicUtil medtronicUtil, + MedtronicPumpStatus medtronicPumpStatus, + MedtronicPumpPlugin medtronicPumpPlugin) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.medtronicUtil = medtronicUtil; this.medtronicPumpStatus = medtronicPumpStatus; + this.medtronicPumpPlugin = medtronicPumpPlugin; } @@ -60,7 +68,7 @@ public class MedtronicUIPostprocessor { if (response) { BasalProfile basalProfile = (BasalProfile) uiTask.getParameter(0); - medtronicPumpStatus.basalsByHour = basalProfile.getProfilesByHour(); + medtronicPumpStatus.basalsByHour = basalProfile.getProfilesByHour(medtronicPumpPlugin.getPumpDescription().pumpType); } } break; @@ -69,7 +77,7 @@ public class MedtronicUIPostprocessor { BasalProfile basalProfile = (BasalProfile) uiTask.returnData; try { - Double[] profilesByHour = basalProfile.getProfilesByHour(); + Double[] profilesByHour = basalProfile.getProfilesByHour(medtronicPumpPlugin.getPumpDescription().pumpType); if (profilesByHour != null) { medtronicPumpStatus.basalsByHour = profilesByHour; @@ -197,7 +205,7 @@ public class MedtronicUIPostprocessor { PumpSettingDTO checkValue = null; - medtronicPumpStatus.verifyConfiguration(); + medtronicPumpPlugin.getRileyLinkService().verifyConfiguration(); // check profile if (!"Yes".equals(settings.get("PCFG_BASAL_PROFILES_ENABLED").value)) { 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 2d294d49b6..15ab86cd2e 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 @@ -31,6 +31,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; @@ -1397,7 +1398,7 @@ public class MedtronicHistoryData { } - public void processLastBasalProfileChange(MedtronicPumpStatus mdtPumpStatus) { + public void processLastBasalProfileChange(PumpType pumpType, MedtronicPumpStatus mdtPumpStatus) { List filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile); @@ -1423,7 +1424,7 @@ public class MedtronicHistoryData { aapsLogger.debug(LTag.PUMP, "processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile); BasalProfile basalProfile = (BasalProfile) newProfile.getDecodedData().get("Object"); - mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour(); + mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour(pumpType); } } 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 32666819c0..cebf86372f 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 @@ -12,7 +12,6 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; /** @@ -278,7 +277,7 @@ public class BasalProfile { } - public Double[] getProfilesByHour() { + public Double[] getProfilesByHour(PumpType pumpType) { List entries = null; @@ -305,8 +304,6 @@ public class BasalProfile { Double[] basalByHour = new Double[24]; - PumpType pumpType = MedtronicPumpPlugin.getPlugin().getMedtronicPumpStatus().pumpType; - for (int i = 0; i < entries.size(); i++) { BasalProfileEntry current = entries.get(i); @@ -368,7 +365,7 @@ public class BasalProfile { return L.isEnabled(L.PUMPCOMM); } - public boolean verify() { + public boolean verify(PumpType pumpType) { try { getEntries(); @@ -376,7 +373,7 @@ public class BasalProfile { return false; } - Double[] profilesByHour = getProfilesByHour(); + Double[] profilesByHour = getProfilesByHour(pumpType); for (Double aDouble : profilesByHour) { if (aDouble > 35.0d) 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 87bce0bd75..eb503b7785 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 @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.driver; +import org.jetbrains.annotations.NotNull; + import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; @@ -9,25 +11,15 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; 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; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; -import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; -import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -38,17 +30,14 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton public class MedtronicPumpStatus extends PumpStatus { - private final AAPSLogger aapsLogger; private final ResourceHelper resourceHelper; private final SP sp; - private String errorDescription = null; + public String errorDescription = null; public String serialNumber; public String pumpFrequency = null; - private String rileyLinkAddress = null; public Double maxBolus; public Double maxBasal; - private boolean inPreInit = true; // statuses public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; @@ -65,32 +54,18 @@ public class MedtronicPumpStatus extends PumpStatus { // fixme public Integer tempBasalLength = 0; - private String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}"; - private String regexSN = "[0-9]{6}"; - - private boolean serialChanged = false; - private boolean rileyLinkAddressChanged = false; - private boolean encodingChanged = false; - private boolean targetFrequencyChanged = false; - - private RileyLinkEncodingType encodingType; - private String[] frequencies; - private boolean isFrequencyUS = false; private Map medtronicPumpMap = null; private Map medtronicDeviceTypeMap = null; - private RileyLinkTargetFrequency targetFrequency; public BasalProfileStatus basalProfileStatus = BasalProfileStatus.NotInitialized; public BatteryType batteryType = BatteryType.None; @Inject public MedtronicPumpStatus( - AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp ) { super(); - this.aapsLogger = aapsLogger; this.resourceHelper = resourceHelper; this.sp = sp; initSettings(); @@ -145,242 +120,16 @@ public class MedtronicPumpStatus extends PumpStatus { medtronicPumpMap.put("554", PumpType.Medtronic_554_754_Veo); medtronicPumpMap.put("754", PumpType.Medtronic_554_754_Veo); - frequencies = new String[2]; - frequencies[0] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca); - frequencies[1] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_worldwide); } - - public boolean verifyConfiguration() { - try { - - // FIXME don't reload information several times - if (this.medtronicPumpMap == null) - createMedtronicPumpMap(); - - if (this.medtronicDeviceTypeMap == null) - createMedtronicDeviceTypeMap(); - - this.errorDescription = "-"; - - String serialNr = sp.getStringOrNull(MedtronicConst.Prefs.PumpSerial, null); - - if (serialNr == null) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_not_set); - return false; - } else { - if (!serialNr.matches(regexSN)) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_invalid); - return false; - } else { - if (!serialNr.equals(this.serialNumber)) { - this.serialNumber = serialNr; - serialChanged = true; - } - } - } - - String pumpType = sp.getStringOrNull(MedtronicConst.Prefs.PumpType, null); - - if (pumpType == null) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_not_set); - return false; - } else { - String pumpTypePart = pumpType.substring(0, 3); - - if (!pumpTypePart.matches("[0-9]{3}")) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_invalid); - return false; - } else { - this.pumpType = medtronicPumpMap.get(pumpTypePart); - this.medtronicDeviceType = medtronicDeviceTypeMap.get(pumpTypePart); - MedtronicPumpPlugin.getPlugin().getPumpDescription().setPumpDescription(this.pumpType); - - if (pumpTypePart.startsWith("7")) - this.reservoirFullUnits = 300; - else - this.reservoirFullUnits = 176; - } - } - - String pumpFrequency = sp.getStringOrNull(MedtronicConst.Prefs.PumpFrequency, null); - - if (pumpFrequency == null) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_not_set); - return false; - } else { - if (!pumpFrequency.equals(frequencies[0]) && !pumpFrequency.equals(frequencies[1])) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_invalid); - return false; - } else { - this.pumpFrequency = pumpFrequency; - this.isFrequencyUS = pumpFrequency.equals(frequencies[0]); - - RileyLinkTargetFrequency newTargetFrequency = this.isFrequencyUS ? // - RileyLinkTargetFrequency.Medtronic_US - : RileyLinkTargetFrequency.Medtronic_WorldWide; - - if (targetFrequency != newTargetFrequency) { - RileyLinkUtil.getInstance().setRileyLinkTargetFrequency(newTargetFrequency); - targetFrequency = newTargetFrequency; - targetFrequencyChanged = true; - } - - } - } - - String rileyLinkAddress = sp.getStringOrNull(RileyLinkConst.Prefs.RileyLinkAddress, null); - - if (rileyLinkAddress == null) { - aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: null"); - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); - return false; - } else { - if (!rileyLinkAddress.matches(regexMac)) { - this.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); - aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: {}", rileyLinkAddress); - } else { - if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { - this.rileyLinkAddress = rileyLinkAddress; - rileyLinkAddressChanged = true; - } - } - } - - double maxBolusLcl = checkParameterValue(MedtronicConst.Prefs.MaxBolus, "25.0", 25.0d); - - if (maxBolus == null || !maxBolus.equals(maxBolusLcl)) { - maxBolus = maxBolusLcl; - - //LOG.debug("Max Bolus from AAPS settings is " + maxBolus); - } - - double maxBasalLcl = checkParameterValue(MedtronicConst.Prefs.MaxBasal, "35.0", 35.0d); - - if (maxBasal == null || !maxBasal.equals(maxBasalLcl)) { - maxBasal = maxBasalLcl; - - //LOG.debug("Max Basal from AAPS settings is " + maxBasal); - } - - - String encodingTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.Encoding, null); - - if (encodingTypeStr == null) { - return false; - } - - RileyLinkEncodingType newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr); - - if (this.encodingType == null) { - this.encodingType = newEncodingType; - } else if (this.encodingType != newEncodingType) { - this.encodingType = newEncodingType; - this.encodingChanged = true; - } - - String batteryTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.BatteryType, null); - - if (batteryTypeStr == null) - return false; - - BatteryType batteryType = getBatteryTypeByDescription(batteryTypeStr); - - if (this.batteryType != batteryType) { - this.batteryType = batteryType; - MedtronicUtil.getInstance().setBatteryType(this.batteryType); - } - - String bolusDebugEnabled = sp.getStringOrNull(MedtronicConst.Prefs.BolusDebugEnabled, null); - - boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(resourceHelper.gs(R.string.common_on)); - - MedtronicHistoryData.doubleBolusDebug = bolusDebug; - - reconfigureService(); - - return true; - - } catch (Exception ex) { - this.errorDescription = ex.getMessage(); - aapsLogger.error(LTag.PUMP, "Error on Verification: " + ex.getMessage(), ex); - return false; - } + public Map getMedtronicPumpMap() { + return medtronicPumpMap; } - - private boolean reconfigureService() { - - if (!inPreInit && MedtronicUtil.getInstance().getMedtronicService() != null) { - - if (serialChanged) { - MedtronicUtil.getInstance().getMedtronicService().setPumpIDString(this.serialNumber); // short operation - serialChanged = false; - } - - if (rileyLinkAddressChanged) { - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); - rileyLinkAddressChanged = false; - } - - if (encodingChanged) { - RileyLinkUtil.getInstance().getRileyLinkService().changeRileyLinkEncoding(encodingType); - encodingChanged = false; - } - } - - - // if (targetFrequencyChanged && !inPreInit && MedtronicUtil.getMedtronicService() != null) { - // RileyLinkUtil.setRileyLinkTargetFrequency(targetFrequency); - // // RileyLinkUtil.getRileyLinkCommunicationManager().refreshRileyLinkTargetFrequency(); - // targetFrequencyChanged = false; - // } - - return (!rileyLinkAddressChanged && !serialChanged && !encodingChanged); // && !targetFrequencyChanged); + public Map getMedtronicDeviceTypeMap() { + return medtronicDeviceTypeMap; } - - private double checkParameterValue(int key, String defaultValue, double defaultValueDouble) { - double val = 0.0d; - - String value = sp.getString(key, defaultValue); - - try { - val = Double.parseDouble(value); - } catch (Exception ex) { - aapsLogger.error("Error parsing setting: {}, value found {}", key, value); - val = defaultValueDouble; - } - - if (val > defaultValueDouble) { - sp.putString(key, defaultValue); - val = defaultValueDouble; - } - - return val; - } - - - public String getErrorInfo() { - verifyConfiguration(); - - return (this.errorDescription == null) ? "-" : this.errorDescription; - } - - - @Override - public void refreshConfiguration() { - verifyConfiguration(); - } - - - public boolean setNotInPreInit() { - this.inPreInit = false; - - return reconfigureService(); - } - - public double getBasalProfileForHour() { if (basalsByHour != null) { GregorianCalendar c = new GregorianCalendar(); @@ -395,7 +144,7 @@ public class MedtronicPumpStatus extends PumpStatus { // Battery type private Map mapByDescription; - private BatteryType getBatteryTypeByDescription(String batteryTypeStr) { + public BatteryType getBatteryTypeByDescription(String batteryTypeStr) { if (mapByDescription == null) { mapByDescription = new HashMap<>(); for (BatteryType value : BatteryType.values()) { @@ -408,4 +157,8 @@ public class MedtronicPumpStatus extends PumpStatus { return BatteryType.None; } + @NotNull + public String getErrorInfo() { + return (errorDescription == null) ? "-" : errorDescription; + } } 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 cf8aecba91..820836b32f 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 @@ -9,12 +9,14 @@ import android.os.IBinder; import javax.inject.Inject; import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; +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.ble.RFSpy; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE; 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.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; @@ -24,9 +26,13 @@ import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUIComm; import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUIPostprocessor; +import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; +import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * RileyLinkMedtronicService is intended to stay running when the gui-app is closed. @@ -34,15 +40,26 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; public class RileyLinkMedtronicService extends RileyLinkService { @Inject HasAndroidInjector injector; + @Inject ResourceHelper resourceHelper; @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicUtil medtronicUtil; @Inject MedtronicUIPostprocessor medtronicUIPostprocessor; + @Inject MedtronicPumpStatus medtronicPumpStatus; private MedtronicUIComm medtronicUIComm; private MedtronicCommunicationManager medtronicCommunicationManager; private IBinder mBinder = new LocalBinder(); + private boolean serialChanged = false; + private String[] frequencies; + private RileyLinkTargetFrequency targetFrequency; + private String rileyLinkAddress = null; + private boolean rileyLinkAddressChanged = false; + private RileyLinkEncodingType encodingType; + private boolean encodingChanged = false; + private boolean inPreInit = true; + public RileyLinkMedtronicService() { super(); @@ -73,6 +90,10 @@ public class RileyLinkMedtronicService extends RileyLinkService { */ public void initRileyLinkServiceData() { + frequencies = new String[2]; + frequencies[0] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca); + frequencies[1] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_worldwide); + rileyLinkServiceData = new RileyLinkServiceData(RileyLinkTargetDevice.MedtronicPump); rileyLinkUtil.setRileyLinkServiceData(rileyLinkServiceData); @@ -185,4 +206,210 @@ public class RileyLinkMedtronicService extends RileyLinkService { @Override public void registerDeviceSpecificBroadcasts(IntentFilter intentFilter) { } + + public boolean verifyConfiguration() { + try { + String regexSN = "[0-9]{6}"; + String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}"; + + medtronicPumpStatus.errorDescription = "-"; + + String serialNr = sp.getStringOrNull(MedtronicConst.Prefs.PumpSerial, null); + + if (serialNr == null) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_not_set); + return false; + } else { + if (!serialNr.matches(regexSN)) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_invalid); + return false; + } else { + if (!serialNr.equals(medtronicPumpStatus.serialNumber)) { + medtronicPumpStatus.serialNumber = serialNr; + serialChanged = true; + } + } + } + + String pumpTypePref = sp.getStringOrNull(MedtronicConst.Prefs.PumpType, null); + + if (pumpTypePref == null) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_not_set); + return false; + } else { + String pumpTypePart = pumpTypePref.substring(0, 3); + + if (!pumpTypePart.matches("[0-9]{3}")) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_invalid); + return false; + } else { + PumpType pumpType = medtronicPumpStatus.getMedtronicPumpMap().get(pumpTypePart); + medtronicPumpStatus.medtronicDeviceType = medtronicPumpStatus.getMedtronicDeviceTypeMap().get(pumpTypePart); + medtronicPumpPlugin.getPumpDescription().setPumpDescription(pumpType); + + if (pumpTypePart.startsWith("7")) + medtronicPumpStatus.reservoirFullUnits = 300; + else + medtronicPumpStatus.reservoirFullUnits = 176; + } + } + + String pumpFrequency = sp.getStringOrNull(MedtronicConst.Prefs.PumpFrequency, null); + + if (pumpFrequency == null) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_not_set); + return false; + } else { + if (!pumpFrequency.equals(frequencies[0]) && !pumpFrequency.equals(frequencies[1])) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_invalid); + return false; + } else { + medtronicPumpStatus.pumpFrequency = pumpFrequency; + boolean isFrequencyUS = pumpFrequency.equals(frequencies[0]); + + RileyLinkTargetFrequency newTargetFrequency = isFrequencyUS ? // + RileyLinkTargetFrequency.Medtronic_US + : RileyLinkTargetFrequency.Medtronic_WorldWide; + + if (targetFrequency != newTargetFrequency) { + rileyLinkUtil.setRileyLinkTargetFrequency(newTargetFrequency); + targetFrequency = newTargetFrequency; + } + + } + } + + String rileyLinkAddress = sp.getStringOrNull(RileyLinkConst.Prefs.RileyLinkAddress, null); + + if (rileyLinkAddress == null) { + aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: null"); + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); + return false; + } else { + if (!rileyLinkAddress.matches(regexMac)) { + medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); + aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: {}", rileyLinkAddress); + } else { + if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { + this.rileyLinkAddress = rileyLinkAddress; + rileyLinkAddressChanged = true; + } + } + } + + double maxBolusLcl = checkParameterValue(MedtronicConst.Prefs.MaxBolus, "25.0", 25.0d); + + if (medtronicPumpStatus.maxBolus == null || !medtronicPumpStatus.maxBolus.equals(maxBolusLcl)) { + medtronicPumpStatus.maxBolus = maxBolusLcl; + + //LOG.debug("Max Bolus from AAPS settings is " + maxBolus); + } + + double maxBasalLcl = checkParameterValue(MedtronicConst.Prefs.MaxBasal, "35.0", 35.0d); + + if (medtronicPumpStatus.maxBasal == null || !medtronicPumpStatus.maxBasal.equals(maxBasalLcl)) { + medtronicPumpStatus.maxBasal = maxBasalLcl; + + //LOG.debug("Max Basal from AAPS settings is " + maxBasal); + } + + + String encodingTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.Encoding, null); + + if (encodingTypeStr == null) { + return false; + } + + RileyLinkEncodingType newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr); + + if (encodingType == null) { + encodingType = newEncodingType; + } else if (encodingType != newEncodingType) { + encodingType = newEncodingType; + encodingChanged = true; + } + + String batteryTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.BatteryType, null); + + if (batteryTypeStr == null) + return false; + + BatteryType batteryType = medtronicPumpStatus.getBatteryTypeByDescription(batteryTypeStr); + + if (medtronicPumpStatus.batteryType != batteryType) { + medtronicPumpStatus.batteryType = batteryType; + } + + String bolusDebugEnabled = sp.getStringOrNull(MedtronicConst.Prefs.BolusDebugEnabled, null); + + boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(resourceHelper.gs(R.string.common_on)); + + MedtronicHistoryData.doubleBolusDebug = bolusDebug; + + reconfigureService(); + + return true; + + } catch (Exception ex) { + medtronicPumpStatus.errorDescription = ex.getMessage(); + aapsLogger.error(LTag.PUMP, "Error on Verification: " + ex.getMessage(), ex); + return false; + } + } + + private boolean reconfigureService() { + + if (!inPreInit) { + + if (serialChanged) { + setPumpIDString(medtronicPumpStatus.serialNumber); // short operation + serialChanged = false; + } + + if (rileyLinkAddressChanged) { + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); + rileyLinkAddressChanged = false; + } + + if (encodingChanged) { + changeRileyLinkEncoding(encodingType); + encodingChanged = false; + } + } + + + // if (targetFrequencyChanged && !inPreInit && MedtronicUtil.getMedtronicService() != null) { + // RileyLinkUtil.setRileyLinkTargetFrequency(targetFrequency); + // // RileyLinkUtil.getRileyLinkCommunicationManager().refreshRileyLinkTargetFrequency(); + // targetFrequencyChanged = false; + // } + + return (!rileyLinkAddressChanged && !serialChanged && !encodingChanged); // && !targetFrequencyChanged); + } + + private double checkParameterValue(int key, String defaultValue, double defaultValueDouble) { + double val; + + String value = sp.getString(key, defaultValue); + + try { + val = Double.parseDouble(value); + } catch (Exception ex) { + aapsLogger.error("Error parsing setting: {}, value found {}", key, value); + val = defaultValueDouble; + } + + if (val > defaultValueDouble) { + sp.putString(key, defaultValue); + val = defaultValueDouble; + } + + return val; + } + + public boolean setNotInPreInit() { + this.inPreInit = false; + + return reconfigureService(); + } } 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 a264178fd9..02a64b3e53 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 @@ -59,7 +59,6 @@ public class MedtronicUtil { private ClockDTO pumpTime; public Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); public Gson gsonInstanceCore = new GsonBuilder().create(); - private BatteryType batteryType = BatteryType.None; @NotNull private final AAPSLogger aapsLogger; @NotNull private final RxBusWrapper rxBus; @@ -507,29 +506,15 @@ public class MedtronicUtil { return settings; } - public void setSettings(Map settings) { this.settings = settings; } - public void setPumpTime(ClockDTO pumpTime) { this.pumpTime = pumpTime; } - public ClockDTO getPumpTime() { return this.pumpTime; } - - public void setBatteryType(BatteryType batteryType) { - this.batteryType = batteryType; - } - - - public BatteryType getBatteryType() { - return this.batteryType; - } - - } From f686c81115ed7b16d71b163c576d307c756ac1eb Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 13:24:35 +0200 Subject: [PATCH 08/23] MDT refactor pass 7 --- .../RileyLinkCommunicationManager.java | 11 +-- .../comm/MedtronicCommunicationManager.java | 88 ++++++++----------- .../medtronic/comm/MedtronicConverter.java | 81 +++++++++-------- .../medtronic/comm/ui/MedtronicUIComm.java | 26 ------ .../comm/ui/MedtronicUIPostprocessor.java | 4 +- .../service/RileyLinkMedtronicService.java | 1 - .../pump/medtronic/util/MedtronicUtil.java | 41 +-------- 7 files changed, 90 insertions(+), 162 deletions(-) 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 91e9be0e1a..695f6e3292 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 @@ -37,6 +37,7 @@ public abstract class RileyLinkCommunicationManager { @Inject MedtronicPumpStatus medtronicPumpStatus; @Inject RileyLinkUtil rileyLinkUtil; + @Inject MedtronicUtil medtronicUtil; private final int SCAN_TIMEOUT = 1500; @@ -51,8 +52,6 @@ public abstract class RileyLinkCommunicationManager { protected RileyLinkServiceData rileyLinkServiceData; private long nextWakeUpRequired = 0L; - // internal flag - private boolean showPumpMessages = true; private int timeoutCount = 0; @@ -84,6 +83,8 @@ public abstract class RileyLinkCommunicationManager { public E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class clazz) throws RileyLinkCommunicationException { + // internal flag + boolean showPumpMessages = true; if (showPumpMessages) { aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); } @@ -152,7 +153,7 @@ public abstract class RileyLinkCommunicationManager { // **** FIXME: this wakeup doesn't seem to work well... must revisit // receiverDeviceAwakeForMinutes = duration_minutes; - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp); + medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); if (force) nextWakeUpRequired = 0L; @@ -193,7 +194,7 @@ public abstract class RileyLinkCommunicationManager { public double tuneForDevice() { - return scanForDevice(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies()); + return scanForDevice(rileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies()); } @@ -207,7 +208,7 @@ public abstract class RileyLinkCommunicationManager { */ public boolean isValidFrequency(double frequency) { - double[] scanFrequencies = RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies(); + double[] scanFrequencies = rileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies(); if (scanFrequencies.length == 1) { return RileyLinkUtil.isSame(scanFrequencies[0], frequency); 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 250d819990..48b9be661e 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 @@ -63,14 +63,14 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager @Inject AAPSLogger aapsLogger; @Inject MedtronicPumpStatus medtronicPumpStatus; @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject MedtronicConverter medtronicConverter; + @Inject MedtronicUtil medtronicUtil; private final int MAX_COMMAND_TRIES = 3; private final int DEFAULT_TIMEOUT = 2000; private final long RILEYLINK_TIMEOUT = 15 * 60 * 1000; // 15 min - static MedtronicCommunicationManager medtronicCommunicationManager; - String errorMessage; - private MedtronicConverter medtronicConverter; + private String errorMessage; private boolean debugSetCommands = false; private MedtronicPumpHistoryDecoder pumpHistoryDecoder; @@ -79,25 +79,17 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public MedtronicCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { super(injector, rfspy); - medtronicCommunicationManager = this; - this.medtronicConverter = new MedtronicConverter(); this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder(); medtronicPumpStatus.previousConnection = sp.getLong( RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); } - - public static MedtronicCommunicationManager getInstance() { - return medtronicCommunicationManager; - } - @Override public E createResponseMessage(byte[] payload, Class clazz) { PumpMessage pumpMessage = new PumpMessage(payload); return (E) pumpMessage; } - public void setDoWakeUpBeforeCommand(boolean doWakeUp) { this.doWakeUpBeforeCommand = doWakeUp; } @@ -117,10 +109,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager */ public boolean isDeviceReachable(boolean canPreventTuneUp) { - PumpDeviceState state = MedtronicUtil.getInstance().getPumpDeviceState(); + PumpDeviceState state = medtronicUtil.getPumpDeviceState(); if (state != PumpDeviceState.PumpUnreachable) - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp); + medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); for (int retry = 0; retry < 5; retry++) { @@ -136,7 +128,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } if (state != PumpDeviceState.PumpUnreachable) - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.PumpUnreachable); + medtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable); if (!canPreventTuneUp) { @@ -153,7 +145,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private boolean connectToDevice() { - PumpDeviceState state = MedtronicUtil.getInstance().getPumpDeviceState(); + PumpDeviceState state = medtronicUtil.getPumpDeviceState(); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, @@ -185,8 +177,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicDeviceType pumpModel = (MedtronicDeviceType) dataResponse; boolean valid = (pumpModel != MedtronicDeviceType.Unknown_Device); - if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null && valid) { - MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel); + if (medtronicUtil.getMedtronicPumpModel() == null && valid) { + medtronicUtil.setMedtronicPumpModel(pumpModel); } aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, @@ -194,9 +186,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (valid) { if (state == PumpDeviceState.PumpUnreachable) - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp); + medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); else - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); rememberLastGoodDeviceCommunicationTime(); @@ -204,7 +196,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } else { if (state != PumpDeviceState.PumpUnreachable) - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.PumpUnreachable); + medtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable); } } @@ -280,7 +272,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager for (List frame : frames) { - byte[] frameData = MedtronicUtil.getInstance().createByteArray(frame); + byte[] frameData = medtronicUtil.createByteArray(frame); // aapsLogger.debug(LTag.PUMPBTCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); @@ -317,9 +309,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false); - aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + MedtronicUtil.getInstance().getCurrentCommand()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + medtronicUtil.getCurrentCommand()); - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Active); boolean doneWithError = false; for (int pageNumber = 0; pageNumber < 5; pageNumber++) { @@ -336,7 +328,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage firstResponse = null; boolean failed = false; - MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null); + medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null); for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { @@ -351,7 +343,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } if (failed) { - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; } @@ -379,7 +371,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager rawHistoryPage.appendData(currentResponse.getFrameData()); // RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) * // currentResponse.getFrameNumber() + 1)); - MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, + medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, currentResponse.getFrameNumber()); aapsLogger.info(LTag.PUMPBTCOMM, "getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber); @@ -442,7 +434,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } if (doneWithError) { - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; } @@ -458,13 +450,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); if (pumpTotalResult.isSearchFinished()) { - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; } } - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; @@ -480,11 +472,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public byte[] createPumpMessageContent(RLMessageType type) { switch (type) { case PowerOn: - return MedtronicUtil.getInstance().buildCommandPayload(MedtronicCommandType.RFPowerOn, // + return medtronicUtil.buildCommandPayload(MedtronicCommandType.RFPowerOn, // new byte[]{2, 1, (byte) receiverDeviceAwakeForMinutes}); // maybe this is better FIXME case ReadSimpleData: - return MedtronicUtil.getInstance().buildCommandPayload(MedtronicCommandType.PumpModel, null); + return medtronicUtil.buildCommandPayload(MedtronicCommandType.PumpModel, null); } return new byte[0]; } @@ -528,7 +520,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false); - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Active); // create message PumpMessage msg; @@ -541,7 +533,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager // send and wait for response PumpMessage response = sendAndListen(msg, timeoutMs); - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return response; } @@ -571,12 +563,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { try { - PumpMessage response = null; + PumpMessage response = sendAndGetResponse(commandType, bodyData, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); - response = sendAndGetResponse(commandType, bodyData, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); - - String check = checkResponseContent(response, commandType.commandDescription, - commandType.expectedLength); + String check = checkResponseContent(response, commandType.commandDescription, commandType.expectedLength); if (check == null) { @@ -664,9 +653,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType); - MedtronicUtil.getInstance().setCurrentCommand(commandType); + medtronicUtil.setCurrentCommand(commandType); - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Active); for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { @@ -677,9 +666,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager msg = makePumpMessage(commandType); // send and wait for response - PumpMessage response = null; - response = sendAndListen(msg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); + PumpMessage response = sendAndListen(msg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); // aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent())); // aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData())); @@ -723,8 +711,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (basalProfile != null) { aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); - MedtronicUtil.getInstance().setCurrentCommand(null); - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setCurrentCommand(null); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return basalProfile; } @@ -735,8 +723,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading profile in max retries."); - MedtronicUtil.getInstance().setCurrentCommand(null); - MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicUtil.setCurrentCommand(null); + medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); return null; @@ -795,7 +783,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public Map getPumpSettings() { - Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.getSettings(MedtronicUtil.getInstance() + Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.getSettings(medtronicUtil .getMedtronicPumpModel())); return responseObject == null ? null : (Map) responseObject; @@ -806,7 +794,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.info(LTag.PUMPBTCOMM, "setBolus: " + units); - return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getInstance().getBolusStrokes(units)); + return setCommand(MedtronicCommandType.SetBolus, medtronicUtil.getBolusStrokes(units)); } @@ -833,7 +821,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager data[i + 1] = (byte) gc.get(Calendar.MINUTE); data[i + 2] = (byte) gc.get(Calendar.SECOND); - byte[] yearByte = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(gc.get(Calendar.YEAR), true); + byte[] yearByte = medtronicUtil.getByteArrayFromUnsignedShort(gc.get(Calendar.YEAR), true); data[i + 3] = yearByte[0]; data[i + 4] = yearByte[1]; @@ -897,7 +885,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public Boolean setBasalProfile(BasalProfile basalProfile) { - List> basalProfileFrames = MedtronicUtil.getInstance().getBasalProfileFrames(basalProfile.getRawData()); + List> basalProfileFrames = medtronicUtil.getBasalProfileFrames(basalProfile.getRawData()); for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { 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 191b752131..af73399dc4 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 @@ -2,13 +2,15 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm; import org.joda.time.IllegalFieldValueException; import org.joda.time.LocalDateTime; -import org.slf4j.Logger; import java.util.HashMap; import java.util.Map; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import javax.inject.Inject; +import javax.inject.Singleton; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; @@ -26,25 +28,30 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; * High level decoder for data returned through MedtroniUIComm */ +@Singleton public class MedtronicConverter { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private final AAPSLogger aapsLogger; + private final MedtronicUtil medtronicUtil; - MedtronicDeviceType pumpModel; + @Inject + public MedtronicConverter( + AAPSLogger aapsLogger, + MedtronicUtil medtronicUtil + ) { + this.aapsLogger = aapsLogger; + this.medtronicUtil = medtronicUtil; + } - - public Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) { + Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) { if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) { - LOG.warn("Content is empty or too short, no data to convert (type={},isNull={},length={})", + aapsLogger.warn(LTag.PUMPBTCOMM, "Content is empty or too short, no data to convert (type={},isNull={},length={})", commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length); return null; } - if (isLogEnabled()) - LOG.debug("Raw response before convert: " + ByteUtil.shortHexString(rawContent)); - - this.pumpModel = MedtronicUtil.getInstance().getMedtronicPumpModel(); + aapsLogger.debug(LTag.PUMPBTCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent)); switch (commandType) { @@ -107,18 +114,17 @@ public class MedtronicConverter { private MedtronicDeviceType decodeModel(byte[] rawContent) { if ((rawContent == null || rawContent.length < 4)) { - LOG.warn("Error reading PumpModel, returning Unknown_Device"); + aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading PumpModel, returning Unknown_Device"); return MedtronicDeviceType.Unknown_Device; } String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3)); MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel); - if (isLogEnabled()) - LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); + aapsLogger.debug(LTag.PUMPBTCOMM, "PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); if (pumpModel != MedtronicDeviceType.Unknown_Device) { - if (!MedtronicUtil.getInstance().isModelSet()) { - MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel); + if (!medtronicUtil.isModelSet()) { + medtronicUtil.setMedtronicPumpModel(pumpModel); } } @@ -154,10 +160,10 @@ public class MedtronicConverter { } - protected Float decodeRemainingInsulin(byte[] rawData) { + private Float decodeRemainingInsulin(byte[] rawData) { int startIdx = 0; - this.pumpModel = MedtronicUtil.getInstance().getMedtronicPumpModel(); + MedtronicDeviceType pumpModel = medtronicUtil.getMedtronicPumpModel(); int strokes = pumpModel == null ? 10 : pumpModel.getBolusStrokes(); @@ -167,8 +173,7 @@ public class MedtronicConverter { float value = ByteUtil.toInt(rawData[startIdx], rawData[startIdx + 1]) / (1.0f * strokes); - if (isLogEnabled()) - LOG.debug("Remaining insulin: " + value); + aapsLogger.debug(LTag.PUMPBTCOMM, "Remaining insulin: " + value); return value; } @@ -185,7 +190,7 @@ public class MedtronicConverter { LocalDateTime pumpTime = new LocalDateTime(year, month, day, hours, minutes, seconds); return pumpTime; } catch (IllegalFieldValueException e) { - LOG.error( + aapsLogger.error(LTag.PUMPBTCOMM, "decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d", year, month, day, hours, minutes, seconds); return null; @@ -194,7 +199,7 @@ public class MedtronicConverter { } - public Map decodeSettingsLoop(byte[] rd) { + private Map decodeSettingsLoop(byte[] rd) { Map map = new HashMap<>(); @@ -271,7 +276,7 @@ public class MedtronicConverter { addSettingToMap("CFG_BASE_CLOCK_MODE", rd[getSettingIndexTimeDisplayFormat()] == 0 ? "12h" : "24h", PumpConfigurationGroup.General, map); - if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { + if (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_523andHigher)) { addSettingToMap("PCFG_INSULIN_CONCENTRATION", "" + (rd[9] == 0 ? 50 : 100), PumpConfigurationGroup.Insulin, map); // LOG.debug("Insulin concentration: " + rd[9]); @@ -323,7 +328,7 @@ public class MedtronicConverter { } - public void addSettingToMap(String key, String value, PumpConfigurationGroup group, Map map) { + private void addSettingToMap(String key, String value, PumpConfigurationGroup group, Map map) { map.put(key, new PumpSettingDTO(key, value, group)); } @@ -339,7 +344,7 @@ public class MedtronicConverter { addSettingToMap("CFG_MM_KEYPAD_LOCKED", parseResultEnable(rd[20]), PumpConfigurationGroup.Other, map); - if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { + if (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_523andHigher)) { addSettingToMap("PCFG_BOLUS_SCROLL_STEP_SIZE", "" + rd[21], PumpConfigurationGroup.Bolus, map); addSettingToMap("PCFG_CAPTURE_EVENT_ENABLE", parseResultEnable(rd[22]), PumpConfigurationGroup.Other, map); @@ -352,7 +357,7 @@ public class MedtronicConverter { } - protected String parseResultEnable(int i) { + private String parseResultEnable(int i) { switch (i) { case 0: return "No"; @@ -364,19 +369,19 @@ public class MedtronicConverter { } - public float getStrokesPerUnit(boolean isBasal) { + private float getStrokesPerUnit(boolean isBasal) { return isBasal ? 40.0f : 10; // pumpModel.getBolusStrokes(); } // 512 - public void decodeInsulinActionSetting(byte[] ai, Map map) { - if (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_512_712)) { + private void decodeInsulinActionSetting(byte[] ai, Map map) { + if (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_512_712)) { addSettingToMap("PCFG_INSULIN_ACTION_TYPE", (ai[17] != 0 ? "Regular" : "Fast"), PumpConfigurationGroup.Insulin, map); } else { int i = ai[17]; - String s = ""; + String s; if ((i == 0) || (i == 1)) { s = ai[17] != 0 ? "Regular" : "Fast"; @@ -392,12 +397,12 @@ public class MedtronicConverter { } - public double decodeBasalInsulin(int i) { + private double decodeBasalInsulin(int i) { return (double) i / (double) getStrokesPerUnit(true); } - public double decodeBolusInsulin(int i) { + private double decodeBolusInsulin(int i) { return (double) i / (double) getStrokesPerUnit(false); } @@ -413,19 +418,13 @@ public class MedtronicConverter { } - public double decodeMaxBolus(byte[] ai) { + private double decodeMaxBolus(byte[] ai) { return is523orHigher() ? decodeBolusInsulin(ByteUtil.toInt(ai[5], ai[6])) : decodeBolusInsulin(ByteUtil .asUINT8(ai[5])); } private boolean is523orHigher() { - return (MedtronicDeviceType.isSameDevice(pumpModel, MedtronicDeviceType.Medtronic_523andHigher)); + return (MedtronicDeviceType.isSameDevice(medtronicUtil.getMedtronicPumpModel(), MedtronicDeviceType.Medtronic_523andHigher)); } - - - private boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); - } - } 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 aca286f7a6..f0731d2d8a 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 @@ -40,34 +40,8 @@ public class MedtronicUIComm { medtronicUtil.setCurrentCommand(commandType); - // new Thread(() -> { - // LOG.warn("@@@ Start Thread"); - // - // task.execute(getCommunicationManager()); - // - // LOG.warn("@@@ End Thread"); - // }); - task.execute(medtronicCommunicationManager); - // for (int i = 0; i < getMaxWaitTime(commandType); i++) { - // synchronized (task) { - // // try { - // // - // // //task.wait(1000); - // // } catch (InterruptedException e) { - // // LOG.error("executeCommand InterruptedException", e); - // // } - // - // - // SystemClock.sleep(1000); - // } - // - // if (task.isReceived()) { - // break; - // } - // } - if (!task.isReceived()) { aapsLogger.warn(LTag.PUMP, "Reply not received for " + commandType); } 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 39cefd8395..364337d019 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 @@ -58,7 +58,7 @@ public class MedtronicUIPostprocessor { // this is mostly intended for command that return certain statuses (Remaining Insulin, ...), and // where responses won't be directly used - public void postProcessData(MedtronicUITask uiTask) { + void postProcessData(MedtronicUITask uiTask) { switch (uiTask.commandType) { @@ -203,7 +203,7 @@ public class MedtronicUIPostprocessor { medtronicUtil.setSettings(settings); - PumpSettingDTO checkValue = null; + PumpSettingDTO checkValue; medtronicPumpPlugin.getRileyLinkService().verifyConfiguration(); 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 820836b32f..0891dd39bd 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 @@ -115,7 +115,6 @@ public class RileyLinkMedtronicService extends RileyLinkService { medtronicUIComm = new MedtronicUIComm(injector, aapsLogger, medtronicUtil, medtronicUIPostprocessor, medtronicCommunicationManager); aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed"); - medtronicUtil.setMedtronicService(this); } 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 02a64b3e53..ba1cf20927 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 @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.medtronic.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.jetbrains.annotations.NotNull; import org.joda.time.LocalTime; import java.nio.ByteBuffer; @@ -25,17 +24,13 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; -import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO; -import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; -import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; -import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService; import info.nightscout.androidaps.utils.resources.ResourceHelper; /** @@ -46,12 +41,9 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class MedtronicUtil { private int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS] - int CRC_SIZE = 1; private boolean lowLevelDebug = true; private PumpDeviceState pumpDeviceState; private MedtronicDeviceType medtronicPumpModel; - private RileyLinkMedtronicService medtronicService; - @Deprecated // TODO remove this reference private MedtronicCommandType currentCommand; private Map settings; private int BIG_FRAME_LENGTH = 65; @@ -60,23 +52,20 @@ public class MedtronicUtil { public Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); public Gson gsonInstanceCore = new GsonBuilder().create(); - @NotNull private final AAPSLogger aapsLogger; - @NotNull private final RxBusWrapper rxBus; - @NotNull private final RileyLinkUtil rileyLinkUtil; - @NotNull private final MedtronicPumpStatus medtronicPumpStatus; + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + private final RileyLinkUtil rileyLinkUtil; @Inject public MedtronicUtil( AAPSLogger aapsLogger, RxBusWrapper rxBus, - RileyLinkUtil rileyLinkUtil, - MedtronicPumpStatus medtronicPumpStatus + RileyLinkUtil rileyLinkUtil ) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil; - this.medtronicPumpStatus = medtronicPumpStatus; instance = this; } @@ -445,32 +434,10 @@ public class MedtronicUtil { this.medtronicPumpModel = medtronicPumpModel; } - - public MedtronicCommunicationManager getMedtronicCommunicationManager() { - return (MedtronicCommunicationManager) rileyLinkUtil.rileyLinkCommunicationManager; - } - - - public RileyLinkMedtronicService getMedtronicService() { - return medtronicService; - } - - - public void setMedtronicService(RileyLinkMedtronicService medtronicService) { - this.medtronicService = medtronicService; - } - - - @Deprecated // TODO use singleton - public MedtronicPumpStatus getPumpStatus1() { - return medtronicPumpStatus; - } - public MedtronicCommandType getCurrentCommand() { return this.currentCommand; } - public void setCurrentCommand(MedtronicCommandType currentCommand) { this.currentCommand = currentCommand; From 30e7f8ed3807e5e04cb5598f158de2ebb218f90d Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 14:30:38 +0200 Subject: [PATCH 09/23] MDT refactor pass 8 --- .../pump/medtronic/MedtronicPumpPlugin.java | 19 +--- .../comm/MedtronicCommunicationManager.java | 8 +- .../comm/history/MedtronicHistoryDecoder.java | 45 +++----- .../comm/history/RawHistoryPage.java | 27 ++--- .../cgms/MedtronicCGMSHistoryDecoder.java | 5 +- .../pump/MedtronicPumpHistoryDecoder.java | 97 ++++++++-------- .../comm/history/pump/PumpHistoryEntry.java | 8 +- .../history/pump/PumpHistoryEntryType.java | 46 ++------ .../medtronic/data/MedtronicHistoryData.java | 104 ++++++++++-------- .../dialog/MedtronicHistoryActivity.java | 4 +- .../pump/medtronic/util/MedtronicUtil.java | 10 +- .../comm/MedtronicHistoryDataUTest.java | 4 +- 12 files changed, 167 insertions(+), 210 deletions(-) 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 15f4ccff12..a077d10856 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 @@ -98,6 +98,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final RileyLinkUtil rileyLinkUtil; private final MedtronicUtil medtronicUtil; private final MedtronicPumpStatus medtronicPumpStatus; + private final MedtronicHistoryData medtronicHistoryData; protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService rileyLinkMedtronicService; @@ -107,7 +108,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private boolean isRefresh = false; private Map statusRefreshMap = new HashMap<>(); private boolean isInitialized = false; - private MedtronicHistoryData medtronicHistoryData; private PumpHistoryEntry lastPumpHistoryEntry; public static boolean isBusy = false; @@ -128,7 +128,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter FabricPrivacy fabricPrivacy, RileyLinkUtil rileyLinkUtil, MedtronicUtil medtronicUtil, - MedtronicPumpStatus medtronicPumpStatus + MedtronicPumpStatus medtronicPumpStatus, + MedtronicHistoryData medtronicHistoryData ) { super(new PluginDescription() // @@ -147,6 +148,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.medtronicUtil = medtronicUtil; this.sp = sp; this.medtronicPumpStatus = medtronicPumpStatus; + this.medtronicHistoryData = medtronicHistoryData; displayConnectionMessages = false; @@ -181,7 +183,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @Override protected void onStart() { super.onStart(); - medtronicHistoryData = new MedtronicHistoryData(aapsLogger, sp, activePlugin); } @Deprecated @@ -196,12 +197,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter return "MedtronicPumpPlugin::"; } - - public MedtronicHistoryData getMedtronicHistoryData() { - return this.medtronicHistoryData; - } - - @Override public void initPumpStatusData() { @@ -1565,10 +1560,4 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter refreshCustomActionsList(); } - - @Deprecated - public MedtronicPumpStatus getMedtronicPumpStatus() { - return medtronicPumpStatus; - } - } 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 48b9be661e..bc53b59fd0 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 @@ -65,6 +65,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicConverter medtronicConverter; @Inject MedtronicUtil medtronicUtil; + @Inject MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder; private final int MAX_COMMAND_TRIES = 3; private final int DEFAULT_TIMEOUT = 2000; @@ -73,13 +74,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private String errorMessage; private boolean debugSetCommands = false; - private MedtronicPumpHistoryDecoder pumpHistoryDecoder; private boolean doWakeUpBeforeCommand = true; public MedtronicCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { super(injector, rfspy); - this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder(); medtronicPumpStatus.previousConnection = sp.getLong( RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); } @@ -316,7 +315,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager for (int pageNumber = 0; pageNumber < 5; pageNumber++) { - RawHistoryPage rawHistoryPage = new RawHistoryPage(); + RawHistoryPage rawHistoryPage = new RawHistoryPage(aapsLogger); // wakeUp(receiverDeviceAwakeForMinutes, false); PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, new GetHistoryPageCarelinkMessageBody(pageNumber)); @@ -440,8 +439,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager rawHistoryPage.dumpToDebug(); - List medtronicHistoryEntries = pumpHistoryDecoder - .processPageAndCreateRecords(rawHistoryPage); + List medtronicHistoryEntries = medtronicPumpHistoryDecoder.processPageAndCreateRecords(rawHistoryPage); aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); 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 dfeb465adf..ef810a2efc 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 @@ -1,32 +1,32 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history; import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import javax.inject.Inject; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; 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; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; /** * This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes * management and modified/extended for AAPS. - * + *

* Author: Andy {andy.rozman@gmail.com} */ public abstract class MedtronicHistoryDecoder implements MedtronicHistoryDecoderInterface { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + @Inject AAPSLogger aapsLogger; + @Inject MedtronicUtil medtronicUtil; protected ByteUtil bitUtils; @@ -34,7 +34,6 @@ public abstract class MedtronicHistoryDecoder i protected boolean statisticsEnabled = true; protected Map unknownOpCodes; protected Map> mapStatistics; - protected MedtronicDeviceType deviceType; public MedtronicHistoryDecoder() { @@ -62,8 +61,8 @@ public abstract class MedtronicHistoryDecoder i // return byteList; // } - if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null) { - LOG.error("Device Type is not defined."); + if (medtronicUtil.getMedtronicPumpModel() == null) { + aapsLogger.error(LTag.PUMPBTCOMM, "Device Type is not defined."); return byteList; } @@ -86,17 +85,16 @@ public abstract class MedtronicHistoryDecoder i if (!statisticsEnabled) return; - unknownOpCodes = new HashMap(); - mapStatistics = new HashMap>(); + unknownOpCodes = new HashMap<>(); + mapStatistics = new HashMap<>(); for (RecordDecodeStatus stat : RecordDecodeStatus.values()) { - mapStatistics.put(stat, new HashMap()); + mapStatistics.put(stat, new HashMap<>()); } } - protected void addToStatistics(MedtronicHistoryEntryInterface pumpHistoryEntry, RecordDecodeStatus status, - Integer opCode) { + protected void addToStatistics(MedtronicHistoryEntryInterface pumpHistoryEntry, RecordDecodeStatus status, Integer opCode) { if (!statisticsEnabled) return; @@ -120,11 +118,10 @@ public abstract class MedtronicHistoryDecoder i StringUtil.appendToStringBuilder(sb, "" + unknownEntry.getKey(), ", "); } - if (isLogEnabled()) - LOG.debug("STATISTICS OF PUMP DECODE"); + aapsLogger.error(LTag.PUMPBTCOMM, "STATISTICS OF PUMP DECODE"); if (unknownOpCodes.size() > 0) { - LOG.warn("Unknown Op Codes: {}", sb.toString()); + aapsLogger.warn(LTag.PUMPBTCOMM, "Unknown Op Codes: {}", sb.toString()); } for (Map.Entry> entry : mapStatistics.entrySet()) { @@ -140,12 +137,9 @@ public abstract class MedtronicHistoryDecoder i String spaces = StringUtils.repeat(" ", 14 - entry.getKey().name().length()); - if (isLogEnabled()) - LOG.debug(" {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(), - sb.toString()); + aapsLogger.error(LTag.PUMPBTCOMM, " {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(), sb.toString()); } else { - if (isLogEnabled()) - LOG.debug(" {} - {}", entry.getKey().name(), entry.getValue().size()); + aapsLogger.error(LTag.PUMPBTCOMM, " {} - {}", entry.getKey().name(), entry.getValue().size()); } } } @@ -184,9 +178,4 @@ public abstract class MedtronicHistoryDecoder i return records; } - - protected boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); - } - } 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 6aa51e94df..3203283e4d 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 @@ -2,11 +2,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history; import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; 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; @@ -16,12 +13,13 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; */ public class RawHistoryPage { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + private final AAPSLogger aapsLogger; private byte[] data = new byte[0]; - public RawHistoryPage() { + public RawHistoryPage(AAPSLogger aapsLogger) { + this.aapsLogger = aapsLogger; } @@ -35,7 +33,7 @@ public class RawHistoryPage { } - public byte[] getOnlyData() { + byte[] getOnlyData() { return Arrays.copyOfRange(data, 0, 1022); } @@ -55,11 +53,11 @@ public class RawHistoryPage { int crcStored = ByteUtil.toInt(data[1022], data[1023]); if (crcCalculated != crcStored) { - LOG.error("Stored CRC ({}) is different than calculated ({}), but ignored for now.", crcStored, - crcCalculated); + aapsLogger.error(LTag.PUMPBTCOMM, "Stored CRC ({}) is different than calculated ({}), but ignored for now.", crcStored, + crcCalculated); } else { - if (MedtronicUtil.getInstance().isLowLevelDebug()) - LOG.debug("CRC ok."); + if (MedtronicUtil.isLowLevelDebug()) + aapsLogger.debug(LTag.PUMPBTCOMM, "CRC ok."); } return crcCalculated == crcStored; @@ -70,7 +68,7 @@ public class RawHistoryPage { int linesize = 80; int offset = 0; - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); while (offset < data.length) { int bytesToLog = linesize; @@ -83,7 +81,6 @@ public class RawHistoryPage { offset += linesize; } - LOG.debug("History Page Data:\n{}", sb.toString()); + aapsLogger.debug(LTag.PUMPBTCOMM, "History Page Data:\n{}", sb.toString()); } - } 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 e2bf3a4935..c3d39954a0 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 @@ -17,7 +17,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDeco /** * This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes * management and modified/extended for AAPS. - * + *

* Author: Andy {andy.rozman@gmail.com} */ @@ -209,8 +209,7 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder * Author: Andy {andy.rozman@gmail.com} */ +@Singleton public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private final AAPSLogger aapsLogger; + private final MedtronicUtil medtronicUtil; private PumpHistoryEntry tbrPreviousRecord; private PumpHistoryEntry changeTimeRecord; - private MedtronicDeviceType deviceType; - private static final String TAG = "MdtPumpHistoryDecoder"; - - public MedtronicPumpHistoryDecoder() { + @Inject + public MedtronicPumpHistoryDecoder( + AAPSLogger aapsLogger, + MedtronicUtil medtronicUtil + ) { + this.aapsLogger = aapsLogger; + this.medtronicUtil = medtronicUtil; } @@ -50,15 +53,13 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder outList = new ArrayList(); + List outList = new ArrayList<>(); String skipped = null; - int elementStart = 0; if (dataClear.size() == 0) { - Log.e(TAG, "Empty page."); + aapsLogger.error(LTag.PUMPBTCOMM, "Empty page."); return outList; } @@ -76,7 +77,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder listRawData = new ArrayList(); + List listRawData = new ArrayList<>(); listRawData.add((byte) opCode); if (entryType == PumpHistoryEntryType.UnabsorbedInsulin - || entryType == PumpHistoryEntryType.UnabsorbedInsulin512) { + || entryType == PumpHistoryEntryType.UnabsorbedInsulin512) { int elements = dataClear.get(counter); listRawData.add((byte) elements); counter++; @@ -105,20 +106,20 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder 0) { decodeDateTime(entry); @@ -260,7 +261,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder * Author: Andy {andy.rozman@gmail.com} */ @@ -289,9 +288,9 @@ public enum PumpHistoryEntryType // implements CodeEnum } - public int getTotalLength() { + public int getTotalLength(MedtronicDeviceType medtronicDeviceType) { if (hasSpecialRules()) { - return getHeadLength() + getBodyLength() + getDateLength(); + return getHeadLength(medtronicDeviceType) + getBodyLength(medtronicDeviceType) + getDateLength(); } else { return totalLength; } @@ -305,7 +304,7 @@ public enum PumpHistoryEntryType // implements CodeEnum void addSpecialRuleHead(SpecialRule rule) { if (isEmpty(specialRulesHead)) { - specialRulesHead = new ArrayList(); + specialRulesHead = new ArrayList<>(); } specialRulesHead.add(rule); @@ -315,7 +314,7 @@ public enum PumpHistoryEntryType // implements CodeEnum void addSpecialRuleBody(SpecialRule rule) { if (isEmpty(specialRulesBody)) { - specialRulesBody = new ArrayList(); + specialRulesBody = new ArrayList<>(); } specialRulesBody.add(rule); @@ -333,10 +332,10 @@ public enum PumpHistoryEntryType // implements CodeEnum } - public int getHeadLength() { + public int getHeadLength(MedtronicDeviceType medtronicDeviceType) { if (hasSpecialRules) { if (isNotEmpty(specialRulesHead)) { - return determineSizeByRule(headLength, specialRulesHead); + return determineSizeByRule(medtronicDeviceType, headLength, specialRulesHead); } else { return headLength; } @@ -351,10 +350,10 @@ public enum PumpHistoryEntryType // implements CodeEnum } - public int getBodyLength() { + public int getBodyLength(MedtronicDeviceType medtronicDeviceType) { if (hasSpecialRules) { if (isNotEmpty(specialRulesBody)) { - return determineSizeByRule(bodyLength, specialRulesBody); + return determineSizeByRule(medtronicDeviceType, bodyLength, specialRulesBody); } else { return bodyLength; } @@ -376,11 +375,11 @@ public enum PumpHistoryEntryType // implements CodeEnum // byte[] dh = { 2, 3 }; - private int determineSizeByRule(int defaultValue, List rules) { + private int determineSizeByRule(MedtronicDeviceType medtronicDeviceType, int defaultValue, List rules) { int size = defaultValue; for (SpecialRule rule : rules) { - if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getInstance().getMedtronicPumpModel(), rule.deviceType)) { + if (MedtronicDeviceType.isSameDevice(medtronicDeviceType, rule.deviceType)) { size = rule.size; break; } @@ -395,29 +394,6 @@ public enum PumpHistoryEntryType // implements CodeEnum return group; } - enum DateFormat { - None(0), // - LongDate(5), // - ShortDate(2); - - private int length; - - - DateFormat(int length) { - this.length = length; - } - - - public int getLength() { - return length; - } - - - public void setLength(int length) { - this.length = length; - } - } - public static class SpecialRule { MedtronicDeviceType deviceType; 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 15ab86cd2e..9489f59811 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 @@ -18,10 +18,12 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DbObjectBase; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; @@ -68,11 +70,13 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; // All things marked with "TODO: Fix db code" needs to be updated in new 2.5 database code +@Singleton public class MedtronicHistoryData { - private AAPSLogger aapsLogger; - private SP sp; - private ActivePluginProvider activePlugin; + private final AAPSLogger aapsLogger; + private final SP sp; + private final ActivePluginProvider activePlugin; + private final MedtronicUtil medtronicUtil; private List allHistory = null; private List newHistory = null; @@ -80,10 +84,9 @@ public class MedtronicHistoryData { private Long lastHistoryRecordTime; private boolean isInit = false; - private Gson gson; - private Gson gsonCore; + private Gson gson; // cannot be initialized in constructor because of injection + private Gson gsonCore; // cannot be initialized in constructor because of injection - private DatabaseHelper databaseHelper = MainApp.getDbHelper(); private ClockDTO pumpTime; private long lastIdUsed = 0; @@ -95,17 +98,30 @@ public class MedtronicHistoryData { */ public static boolean doubleBolusDebug = false; - - public MedtronicHistoryData(AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin) { + @Inject + public MedtronicHistoryData( + AAPSLogger aapsLogger, + SP sp, + ActivePluginProvider activePlugin, + MedtronicUtil medtronicUtil + ) { this.allHistory = new ArrayList<>(); - this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); - this.gsonCore = new GsonBuilder().create(); this.aapsLogger = aapsLogger; this.sp = sp; this.activePlugin = activePlugin; + this.medtronicUtil = medtronicUtil; } + private Gson gson() { + if (gson == null) gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + return gson; + } + + private Gson gsonCore() { + if (gsonCore == null) gsonCore = new GsonBuilder().create(); + return gsonCore; + } /** * Add New History entries @@ -127,7 +143,7 @@ public class MedtronicHistoryData { this.newHistory = newEntries; - showLogs("List of history (before filtering): [" + this.newHistory.size() + "]", gson.toJson(this.newHistory)); + showLogs("List of history (before filtering): [" + this.newHistory.size() + "]", gson().toJson(this.newHistory)); } @@ -201,7 +217,7 @@ public class MedtronicHistoryData { aapsLogger.debug(LTag.PUMP, "New History entries found: {}", this.newHistory.size()); - showLogs("List of history (after filtering): [" + this.newHistory.size() + "]", gson.toJson(this.newHistory)); + showLogs("List of history (after filtering): [" + this.newHistory.size() + "]", gson().toJson(this.newHistory)); } @@ -314,7 +330,7 @@ public class MedtronicHistoryData { List items = getDataForPumpSuspends(); - showLogs("isPumpSuspended: ", gson.toJson(items)); + showLogs("isPumpSuspended: ", gson().toJson(items)); if (isCollectionNotEmpty(items)) { @@ -400,7 +416,7 @@ public class MedtronicHistoryData { // Prime (for reseting autosense) List primeRecords = getFilteredItems(PumpHistoryEntryType.Prime); - aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Prime [count={}, items={}]", primeRecords.size(), gson.toJson(primeRecords)); + aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Prime [count={}, items={}]", primeRecords.size(), gson().toJson(primeRecords)); if (isCollectionNotEmpty(primeRecords)) { try { @@ -414,7 +430,7 @@ public class MedtronicHistoryData { // TDD List tdds = getFilteredItems(PumpHistoryEntryType.EndResultTotals, getTDDType()); - aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gson.toJson(tdds)); + aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gson().toJson(tdds)); if (isCollectionNotEmpty(tdds)) { try { @@ -430,7 +446,7 @@ public class MedtronicHistoryData { // Bolus List treatments = getFilteredItems(PumpHistoryEntryType.Bolus); - aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Bolus [count={}, items={}]", treatments.size(), gson.toJson(treatments)); + aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: Bolus [count={}, items={}]", treatments.size(), gson().toJson(treatments)); if (treatments.size() > 0) { try { @@ -444,7 +460,7 @@ public class MedtronicHistoryData { // TBR List tbrs = getFilteredItems(PumpHistoryEntryType.TempBasalCombined); - aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TBRs Processed [count={}, items={}]", tbrs.size(), gson.toJson(tbrs)); + aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: TBRs Processed [count={}, items={}]", tbrs.size(), gson().toJson(tbrs)); if (tbrs.size() > 0) { try { @@ -466,7 +482,7 @@ public class MedtronicHistoryData { } aapsLogger.debug(LTag.PUMP, "ProcessHistoryData: 'Delivery Suspend' Processed [count={}, items={}]", suspends.size(), - gson.toJson(suspends)); + gson().toJson(suspends)); if (isCollectionNotEmpty(suspends)) { try { @@ -532,9 +548,9 @@ public class MedtronicHistoryData { List tdds = filterTDDs(tddsIn); - aapsLogger.debug(LTag.PUMP, getLogPrefix() + "TDDs found: {}.\n{}", tdds.size(), gson.toJson(tdds)); + aapsLogger.debug(LTag.PUMP, getLogPrefix() + "TDDs found: {}.\n{}", tdds.size(), gson().toJson(tdds)); - List tddsDb = databaseHelper.getTDDsForLastXDays(3); + List tddsDb = MainApp.getDbHelper().getTDDsForLastXDays(3); for (PumpHistoryEntry tdd : tdds) { @@ -550,7 +566,7 @@ public class MedtronicHistoryData { aapsLogger.debug(LTag.PUMP, "TDD Add: {}", tddNew); - databaseHelper.createOrUpdateTDD(tddNew); + MainApp.getDbHelper().createOrUpdateTDD(tddNew); } else { @@ -559,7 +575,7 @@ public class MedtronicHistoryData { aapsLogger.debug(LTag.PUMP, "TDD Edit: {}", tddDbEntry); - databaseHelper.createOrUpdateTDD(tddDbEntry); + MainApp.getDbHelper().createOrUpdateTDD(tddDbEntry); } } } @@ -591,8 +607,8 @@ public class MedtronicHistoryData { List entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus); if (doubleBolusDebug) - aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (before filter): {}, FromDb={}", gson.toJson(entryList), - gsonCore.toJson(entriesFromHistory)); + aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (before filter): {}, FromDb={}", gson().toJson(entryList), + gsonCore().toJson(entriesFromHistory)); filterOutAlreadyAddedEntries(entryList, entriesFromHistory); @@ -605,8 +621,8 @@ public class MedtronicHistoryData { filterOutNonInsulinEntries(entriesFromHistory); if (doubleBolusDebug) - aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (after filter): {}, FromDb={}", gson.toJson(entryList), - gsonCore.toJson(entriesFromHistory)); + aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: List (after filter): {}, FromDb={}", gson().toJson(entryList), + gsonCore().toJson(entriesFromHistory)); if (isCollectionEmpty(entriesFromHistory)) { for (PumpHistoryEntry treatment : entryList) { @@ -669,8 +685,8 @@ public class MedtronicHistoryData { List entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.TBR); - aapsLogger.debug(LTag.PUMP, ProcessHistoryRecord.TBR.getDescription() + " List (before filter): {}, FromDb={}", gson.toJson(entryList), - gson.toJson(entriesFromHistory)); + aapsLogger.debug(LTag.PUMP, ProcessHistoryRecord.TBR.getDescription() + " List (before filter): {}, FromDb={}", gson().toJson(entryList), + gson().toJson(entriesFromHistory)); TempBasalProcessDTO processDTO = null; @@ -720,7 +736,7 @@ public class MedtronicHistoryData { tempBasal.durationInMinutes = tempBasalProcessDTO.getDuration(); - databaseHelper.createOrUpdate(tempBasal); + MainApp.getDbHelper().createOrUpdate(tempBasal); aapsLogger.debug(LTag.PUMP, "Edit " + ProcessHistoryRecord.TBR.getDescription() + " - (entryFromDb={}) ", tempBasal); } else { @@ -768,7 +784,7 @@ public class MedtronicHistoryData { } } - TemporaryBasal tempBasal = databaseHelper.findTempBasalByPumpId(pumpId); + TemporaryBasal tempBasal = MainApp.getDbHelper().findTempBasalByPumpId(pumpId); return tempBasal; } @@ -789,7 +805,7 @@ public class MedtronicHistoryData { //proposedTime += (this.pumpTime.timeDifference * 1000); if (doubleBolusDebug) - aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}", treatment, gson.toJson(entriesFromHistory)); + aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}", treatment, gson().toJson(entriesFromHistory)); if (entriesFromHistory.size() == 0) { if (doubleBolusDebug) @@ -843,10 +859,10 @@ public class MedtronicHistoryData { if (min == 0 && sec == 10 && outList.size() > 1) { aapsLogger.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})", - min, sec, outList.size(), gson.toJson(outList)); + min, sec, outList.size(), gson().toJson(outList)); if (doubleBolusDebug) aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: findDbEntry Error - Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})", - min, sec, outList.size(), gson.toJson(outList)); + min, sec, outList.size(), gson().toJson(outList)); } } } @@ -859,7 +875,7 @@ public class MedtronicHistoryData { if (processHistoryRecord == ProcessHistoryRecord.Bolus) { return activePlugin.getActiveTreatments().getTreatmentsFromHistoryAfterTimestamp(startTimestamp); } else { - return databaseHelper.getTemporaryBasalsDataFromTime(startTimestamp, true); + return MainApp.getDbHelper().getTemporaryBasalsDataFromTime(startTimestamp, true); } } @@ -896,8 +912,8 @@ public class MedtronicHistoryData { if (doubleBolusDebug) aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory={}, Treatments={}", - gson.toJson(removeTreatmentsFromPH), - gsonCore.toJson(removeTreatmentsFromHistory)); + gson().toJson(removeTreatmentsFromPH), + gsonCore().toJson(removeTreatmentsFromHistory)); treatmentsFromHistory.removeAll(removeTreatmentsFromHistory); } @@ -1017,7 +1033,7 @@ public class MedtronicHistoryData { treatment.setLinkedObject(temporaryBasalDb); - databaseHelper.createOrUpdate(temporaryBasalDb); + MainApp.getDbHelper().createOrUpdate(temporaryBasalDb); aapsLogger.debug(LTag.PUMP, operation + " - [date={},pumpId={}, rate={} {}, duration={}]", // temporaryBasalDb.date, // @@ -1033,7 +1049,7 @@ public class MedtronicHistoryData { for (TempBasalProcessDTO tempBasalProcess : tempBasalProcessList) { - TemporaryBasal tempBasal = databaseHelper.findTempBasalByPumpId(tempBasalProcess.itemOne.getPumpId()); + TemporaryBasal tempBasal = MainApp.getDbHelper().findTempBasalByPumpId(tempBasalProcess.itemOne.getPumpId()); if (tempBasal == null) { // add @@ -1049,7 +1065,7 @@ public class MedtronicHistoryData { tempBasalProcess.itemOne.setLinkedObject(tempBasal); tempBasalProcess.itemTwo.setLinkedObject(tempBasal); - databaseHelper.createOrUpdate(tempBasal); + MainApp.getDbHelper().createOrUpdate(tempBasal); } } @@ -1196,11 +1212,11 @@ public class MedtronicHistoryData { if (!finishedItems) { - showLogs("NoDeliveryRewindPrimeRecords: Not finished Items: ", gson.toJson(tempData)); + showLogs("NoDeliveryRewindPrimeRecords: Not finished Items: ", gson().toJson(tempData)); return outList; } - showLogs("NoDeliveryRewindPrimeRecords: Records to evaluate: ", gson.toJson(tempData)); + showLogs("NoDeliveryRewindPrimeRecords: Records to evaluate: ", gson().toJson(tempData)); List items = getFilteredItems(tempData, // PumpHistoryEntryType.Prime @@ -1392,7 +1408,7 @@ public class MedtronicHistoryData { List filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile); - aapsLogger.debug(LTag.PUMP, "hasBasalProfileChanged. Items: " + gson.toJson(filteredItems)); + aapsLogger.debug(LTag.PUMP, "hasBasalProfileChanged. Items: " + gson().toJson(filteredItems)); return (filteredItems.size() > 0); } @@ -1462,7 +1478,7 @@ public class MedtronicHistoryData { for (PumpHistoryEntry pumpHistoryEntry : TBRs_Input) { if (map.containsKey(pumpHistoryEntry.DT)) { MedtronicPumpHistoryDecoder.decodeTempBasal(map.get(pumpHistoryEntry.DT), pumpHistoryEntry); - pumpHistoryEntry.setEntryType(PumpHistoryEntryType.TempBasalCombined); + pumpHistoryEntry.setEntryType(medtronicUtil.getMedtronicPumpModel(), PumpHistoryEntryType.TempBasalCombined); TBRs.add(pumpHistoryEntry); map.remove(pumpHistoryEntry.DT); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java index e4673fbc5d..50eebb6813 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java @@ -23,11 +23,13 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry; +import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; public class MedtronicHistoryActivity extends NoSplashAppCompatActivity { @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject MedtronicHistoryData medtronicHistoryData; Spinner historyTypeSpinner; TextView statusView; @@ -49,7 +51,7 @@ public class MedtronicHistoryActivity extends NoSplashAppCompatActivity { this.filteredHistoryList.clear(); List list = new ArrayList<>(); - list.addAll(medtronicPumpPlugin.getMedtronicHistoryData().getAllHistory()); + list.addAll(medtronicHistoryData.getAllHistory()); //LOG.debug("Items on full list: {}", list.size()); 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 ba1cf20927..4587bfd65d 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 @@ -41,7 +41,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class MedtronicUtil { private int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS] - private boolean lowLevelDebug = true; + private static boolean lowLevelDebug = true; private PumpDeviceState pumpDeviceState; private MedtronicDeviceType medtronicPumpModel; private MedtronicCommandType currentCommand; @@ -396,16 +396,10 @@ public class MedtronicUtil { } - public boolean isLowLevelDebug() { + public static boolean isLowLevelDebug() { return lowLevelDebug; } - - public void setLowLevelDebug(boolean lowLevelDebug) { - this.lowLevelDebug = lowLevelDebug; - } - - public PumpDeviceState getPumpDeviceState() { return pumpDeviceState; } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java index cd395842bd..4db64d90b1 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java @@ -21,7 +21,7 @@ import static org.mockito.Mockito.when; * Created by andy on 3/10/19. */ public class MedtronicHistoryDataUTest { - +/* //TestLogger LOGGER = TestLoggerFactory.getTestLogger(MedtronicHistoryDataUTest.class); byte[] historyPageData = ByteUtil @@ -123,5 +123,5 @@ public class MedtronicHistoryDataUTest { } } - +*/ } From 7e712bd612b6ac2670f970c59667a630f7c00477 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 15:18:59 +0200 Subject: [PATCH 10/23] MDT refactor pass 9 --- .../pump/medtronic/MedtronicPumpPlugin.java | 6 +- .../comm/MedtronicCommunicationManager.java | 2 +- .../medtronic/comm/MedtronicConverter.java | 4 +- .../pump/MedtronicPumpHistoryDecoder.java | 6 +- .../comm/message/CarelinkLongMessageBody.java | 14 +---- .../medtronic/comm/ui/MedtronicUITask.java | 2 +- .../medtronic/data/MedtronicHistoryData.java | 21 +++---- .../pump/medtronic/data/dto/BasalProfile.java | 58 ++++++++++--------- .../medtronic/data/dto/BasalProfileEntry.java | 45 ++++++-------- .../medtronic/data/dto/TempBasalPair.java | 44 +++++++------- .../defs/MedtronicStatusRefreshType.java | 6 +- .../pump/medtronic/util/MedtronicUtil.java | 28 +++------ 12 files changed, 103 insertions(+), 133 deletions(-) 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 a077d10856..baa03a3ef1 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 @@ -478,14 +478,14 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter case BatteryStatus: case RemainingInsulin: { - rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(refreshType.getKey().getCommandType()); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(refreshType.getKey().getCommandType(medtronicUtil.getMedtronicPumpModel())); refreshTypesNeededToReschedule.add(refreshType.getKey()); resetTime = true; } break; case Configuration: { - rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(refreshType.getKey().getCommandType()); + rileyLinkMedtronicService.getMedtronicUIComm().executeCommand(refreshType.getKey().getCommandType(medtronicUtil.getMedtronicPumpModel())); resetTime = true; } break; @@ -1458,7 +1458,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter @NonNull private BasalProfile convertProfileToMedtronicProfile(Profile profile) { - BasalProfile basalProfile = new BasalProfile(); + BasalProfile basalProfile = new BasalProfile(aapsLogger); for (int i = 0; i < 24; i++) { double rate = profile.getBasalTimeFromMidnight(i * 60 * 60); 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 bc53b59fd0..178db5a61c 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 @@ -869,7 +869,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public boolean cancelTBR() { - return setTBR(new TempBasalPair(0.0d, false, 0)); + return setTBR(new TempBasalPair(aapsLogger, 0.0d, false, 0)); } 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 af73399dc4..b1377a38af 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 @@ -79,7 +79,7 @@ public class MedtronicConverter { } case ReadTemporaryBasal: { - return new TempBasalPair(rawContent); // 5 + return new TempBasalPair(aapsLogger, rawContent); // 5 } case Settings_512: { @@ -105,7 +105,7 @@ public class MedtronicConverter { private BasalProfile decodeBasalProfile(PumpType pumpType, byte[] rawContent) { - BasalProfile basalProfile = new BasalProfile(rawContent); + BasalProfile basalProfile = new BasalProfile(aapsLogger, rawContent); return basalProfile.verify(pumpType) ? basalProfile : null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java index a43dc42c42..cb680f61f2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java @@ -368,7 +368,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder> 3) == 0); // System.out.println("TBR: amount=" + tbr.getInsulinRate() + ", duration=" + tbr.getDurationMinutes() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/CarelinkLongMessageBody.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/CarelinkLongMessageBody.java index f051976ed9..7f2c51e032 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/CarelinkLongMessageBody.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/CarelinkLongMessageBody.java @@ -1,19 +1,15 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.message; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; - /** * Created by geoff on 6/2/16. */ public class CarelinkLongMessageBody extends MessageBody { - public static final int LONG_MESSAGE_BODY_LENGTH = 65; + private static final int LONG_MESSAGE_BODY_LENGTH = 65; protected byte[] data; - public CarelinkLongMessageBody() { + CarelinkLongMessageBody() { init(new byte[0]); } @@ -22,12 +18,6 @@ public class CarelinkLongMessageBody extends MessageBody { init(payload); } - - public CarelinkLongMessageBody(List payload) { - init(MedtronicUtil.getInstance().createByteArray(payload)); - } - - @Override public void init(byte[] rxData) { 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 51a8020fcd..6262e7ee98 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 @@ -161,7 +161,7 @@ public class MedtronicUITask { private TempBasalPair getTBRSettings() { - return new TempBasalPair(getDoubleFromParameters(0), // + return new TempBasalPair(aapsLogger, getDoubleFromParameters(0), // false, // getIntegerFromParameters(1)); } 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 9489f59811..cfa3fdcc51 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 @@ -77,11 +77,11 @@ public class MedtronicHistoryData { private final SP sp; private final ActivePluginProvider activePlugin; private final MedtronicUtil medtronicUtil; + private final MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder; - private List allHistory = null; + private List allHistory; private List newHistory = null; - private Long lastHistoryRecordTime; private boolean isInit = false; private Gson gson; // cannot be initialized in constructor because of injection @@ -103,7 +103,8 @@ public class MedtronicHistoryData { AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin, - MedtronicUtil medtronicUtil + MedtronicUtil medtronicUtil, + MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder ) { this.allHistory = new ArrayList<>(); @@ -111,6 +112,7 @@ public class MedtronicHistoryData { this.sp = sp; this.activePlugin = activePlugin; this.medtronicUtil = medtronicUtil; + this.medtronicPumpHistoryDecoder = medtronicPumpHistoryDecoder; } private Gson gson() { @@ -441,7 +443,7 @@ public class MedtronicHistoryData { } } - pumpTime = MedtronicUtil.getInstance().getPumpTime(); + pumpTime = medtronicUtil.getPumpTime(); // Bolus List treatments = getFilteredItems(PumpHistoryEntryType.Bolus); @@ -472,7 +474,7 @@ public class MedtronicHistoryData { } // 'Delivery Suspend' - List suspends = null; + List suspends; try { suspends = getSuspends(); @@ -1312,7 +1314,7 @@ public class MedtronicHistoryData { } } - LocalDateTime oldestEntryTime = null; + LocalDateTime oldestEntryTime; try { @@ -1377,11 +1379,11 @@ public class MedtronicHistoryData { private PumpHistoryEntryType getTDDType() { - if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null) { + if (medtronicUtil.getMedtronicPumpModel() == null) { return PumpHistoryEntryType.EndResultTotals; } - switch (MedtronicUtil.getInstance().getMedtronicPumpModel()) { + switch (medtronicUtil.getMedtronicPumpModel()) { case Medtronic_515: case Medtronic_715: @@ -1454,7 +1456,6 @@ public class MedtronicHistoryData { public void setLastHistoryRecordTime(Long lastHistoryRecordTime) { // this.previousLastHistoryRecordTime = this.lastHistoryRecordTime; - this.lastHistoryRecordTime = lastHistoryRecordTime; } @@ -1477,7 +1478,7 @@ public class MedtronicHistoryData { for (PumpHistoryEntry pumpHistoryEntry : TBRs_Input) { if (map.containsKey(pumpHistoryEntry.DT)) { - MedtronicPumpHistoryDecoder.decodeTempBasal(map.get(pumpHistoryEntry.DT), pumpHistoryEntry); + medtronicPumpHistoryDecoder.decodeTempBasal(map.get(pumpHistoryEntry.DT), pumpHistoryEntry); pumpHistoryEntry.setEntryType(medtronicUtil.getMedtronicPumpModel(), PumpHistoryEntryType.TempBasalCombined); TBRs.add(pumpHistoryEntry); map.remove(pumpHistoryEntry.DT); 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 cebf86372f..359663b22c 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 @@ -3,13 +3,13 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; import com.google.gson.annotations.Expose; import org.joda.time.Instant; -import org.slf4j.Logger; import java.util.ArrayList; import java.util.List; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; @@ -31,7 +31,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; */ public class BasalProfile { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private final AAPSLogger aapsLogger; public static final int MAX_RAW_DATA_SIZE = (48 * 3) + 1; private static final boolean DEBUG_BASALPROFILE = false; @@ -40,18 +40,20 @@ public class BasalProfile { private List listEntries; - public BasalProfile() { + public BasalProfile(AAPSLogger aapsLogger) { + this.aapsLogger = aapsLogger; init(); } - public BasalProfile(byte[] data) { + public BasalProfile(AAPSLogger aapsLogger, byte[] data) { + this .aapsLogger = aapsLogger; setRawData(data); } // this asUINT8 should be combined with Record.asUINT8, and placed in a new util class. - protected static int readUnsignedByte(byte b) { + private static int readUnsignedByte(byte b) { return (b < 0) ? b + 256 : b; } @@ -64,15 +66,15 @@ public class BasalProfile { } - public boolean setRawData(byte[] data) { + private boolean setRawData(byte[] data) { if (data == null) { - LOG.error("setRawData: buffer is null!"); + aapsLogger.error(LTag.PUMPBTCOMM,"setRawData: buffer is null!"); return false; } // if we have just one entry through all day it looks like just length 1 if (data.length == 1) { - data = MedtronicUtil.getInstance().createByteArray(data[0], (byte) 0, (byte) 0); + data = MedtronicUtil.createByteArray(data[0], (byte) 0, (byte) 0); } if (data.length == MAX_RAW_DATA_SIZE) { @@ -89,7 +91,7 @@ public class BasalProfile { public boolean setRawDataFromHistory(byte[] data) { if (data == null) { - LOG.error("setRawData: buffer is null!"); + aapsLogger.error(LTag.PUMPBTCOMM,"setRawData: buffer is null!"); return false; } @@ -114,13 +116,13 @@ public class BasalProfile { public void dumpBasalProfile() { - LOG.debug("Basal Profile entries:"); + aapsLogger.debug(LTag.PUMPBTCOMM,"Basal Profile entries:"); List entries = getEntries(); for (int i = 0; i < entries.size(); i++) { BasalProfileEntry entry = entries.get(i); String startString = entry.startTime.toString("HH:mm"); // this doesn't work - LOG.debug(String.format("Entry %d, rate=%.3f (0x%02X), start=%s (0x%02X)", i + 1, entry.rate, + aapsLogger.debug(LTag.PUMPBTCOMM,String.format("Entry %d, rate=%.3f (0x%02X), start=%s (0x%02X)", i + 1, entry.rate, entry.rate_raw, startString, entry.startTime_raw)); } @@ -167,14 +169,14 @@ public class BasalProfile { BasalProfileEntry rval = new BasalProfileEntry(); List entries = getEntries(); if (entries.size() == 0) { - LOG.warn(String.format("getEntryForTime(%s): table is empty", + aapsLogger.warn(LTag.PUMPBTCOMM,String.format("getEntryForTime(%s): table is empty", when.toDateTime().toLocalTime().toString("HH:mm"))); return rval; } // Log.w(TAG,"Assuming first entry"); rval = entries.get(0); if (entries.size() == 1) { - LOG.debug("getEntryForTime: Only one entry in profile"); + aapsLogger.debug(LTag.PUMPBTCOMM,"getEntryForTime: Only one entry in profile"); return rval; } @@ -184,17 +186,17 @@ public class BasalProfile { while (!done) { BasalProfileEntry entry = entries.get(i); if (DEBUG_BASALPROFILE) { - LOG.debug(String.format("Comparing 'now'=%s to entry 'start time'=%s", when.toDateTime().toLocalTime() + aapsLogger.debug(LTag.PUMPBTCOMM,String.format("Comparing 'now'=%s to entry 'start time'=%s", when.toDateTime().toLocalTime() .toString("HH:mm"), entry.startTime.toString("HH:mm"))); } if (localMillis >= entry.startTime.getMillisOfDay()) { rval = entry; if (DEBUG_BASALPROFILE) - LOG.debug("Accepted Entry"); + aapsLogger.debug(LTag.PUMPBTCOMM,"Accepted Entry"); } else { // entry at i has later start time, keep older entry if (DEBUG_BASALPROFILE) - LOG.debug("Rejected Entry"); + aapsLogger.debug(LTag.PUMPBTCOMM,"Rejected Entry"); done = true; } i++; @@ -203,7 +205,7 @@ public class BasalProfile { } } if (DEBUG_BASALPROFILE) { - LOG.debug(String.format("getEntryForTime(%s): Returning entry: rate=%.3f (%d), start=%s (%d)", when + aapsLogger.debug(LTag.PUMPBTCOMM,String.format("getEntryForTime(%s): Returning entry: rate=%.3f (%d), start=%s (%d)", when .toDateTime().toLocalTime().toString("HH:mm"), rval.rate, rval.rate_raw, rval.startTime.toString("HH:mm"), rval.startTime_raw)); } @@ -215,7 +217,7 @@ public class BasalProfile { List entries = new ArrayList<>(); if (mRawData == null || mRawData[2] == 0x3f) { - LOG.warn("Raw Data is empty."); + aapsLogger.warn(LTag.PUMPBTCOMM,"Raw Data is empty."); return entries; // an empty list } boolean done = false; @@ -229,13 +231,13 @@ public class BasalProfile { if ((mRawData[i] == 0) && (mRawData[i + 1] == 0) && (mRawData[i + 2] == 0x3f)) break; - r = MedtronicUtil.getInstance().makeUnsignedShort(mRawData[i + 1], mRawData[i]); // readUnsignedByte(mRawData[i]); + r = MedtronicUtil.makeUnsignedShort(mRawData[i + 1], mRawData[i]); // readUnsignedByte(mRawData[i]); st = readUnsignedByte(mRawData[i + 2]); try { - entries.add(new BasalProfileEntry(r, st)); + entries.add(new BasalProfileEntry(aapsLogger, r, st)); } catch (Exception ex) { - LOG.error("Error decoding basal profile from bytes: {}", ByteUtil.shortHexString(mRawData)); + aapsLogger.error(LTag.PUMPBTCOMM,"Error decoding basal profile from bytes: {}", ByteUtil.shortHexString(mRawData)); throw ex; } @@ -264,14 +266,14 @@ public class BasalProfile { for (BasalProfileEntry profileEntry : listEntries) { - byte[] strokes = MedtronicUtil.getInstance().getBasalStrokes(profileEntry.rate, true); + byte[] strokes = MedtronicUtil.getBasalStrokes(profileEntry.rate, true); outData.add(profileEntry.rate_raw[0]); outData.add(profileEntry.rate_raw[1]); outData.add(profileEntry.startTime_raw); } - this.setRawData(MedtronicUtil.getInstance().createByteArray(outData)); + this.setRawData(MedtronicUtil.createByteArray(outData)); // return this.mRawData; } @@ -284,10 +286,10 @@ public class BasalProfile { try { entries = getEntries(); } catch (Exception ex) { - LOG.error("============================================================================="); - LOG.error(" Error generating entries. Ex.: " + ex, ex); - LOG.error(" rawBasalValues: " + ByteUtil.shortHexString(this.getRawData())); - LOG.error("============================================================================="); + aapsLogger.error(LTag.PUMPBTCOMM,"============================================================================="); + aapsLogger.error(LTag.PUMPBTCOMM," Error generating entries. Ex.: " + ex, ex); + aapsLogger.error(LTag.PUMPBTCOMM," rawBasalValues: " + ByteUtil.shortHexString(this.getRawData())); + aapsLogger.error(LTag.PUMPBTCOMM,"============================================================================="); //FabricUtil.createEvent("MedtronicBasalProfileGetByHourError", null); } 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 e0c7b5a554..8622b0f00b 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 @@ -1,11 +1,9 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; import org.joda.time.LocalTime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; /** @@ -15,24 +13,20 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; */ public class BasalProfileEntry { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - - public byte[] rate_raw; + byte[] rate_raw; public double rate; - public byte startTime_raw; + byte startTime_raw; public LocalTime startTime; // Just a "time of day" - public BasalProfileEntry() { rate = -9.999E6; - rate_raw = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(0xFF, true); + rate_raw = MedtronicUtil.getByteArrayFromUnsignedShort(0xFF, true); startTime = new LocalTime(0); - startTime_raw = (byte)0xFF; + startTime_raw = (byte) 0xFF; } - public BasalProfileEntry(double rate, int hour, int minutes) { - byte[] data = MedtronicUtil.getInstance().getBasalStrokes(rate, true); + byte[] data = MedtronicUtil.getBasalStrokes(rate, true); rate_raw = new byte[2]; rate_raw[0] = data[1]; @@ -44,47 +38,42 @@ public class BasalProfileEntry { interval++; } - startTime_raw = (byte)interval; + startTime_raw = (byte) interval; startTime = new LocalTime(hour, minutes == 30 ? 30 : 0); } - - public BasalProfileEntry(int rateStrokes, int startTimeInterval) { + BasalProfileEntry(AAPSLogger aapsLogger, int rateStrokes, int startTimeInterval) { // rateByte is insulin delivery rate, U/hr, in 0.025 U increments // startTimeByte is time-of-day, in 30 minute increments - rate_raw = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(rateStrokes, true); + rate_raw = MedtronicUtil.getByteArrayFromUnsignedShort(rateStrokes, true); rate = rateStrokes * 0.025; - startTime_raw = (byte)startTimeInterval; + startTime_raw = (byte) startTimeInterval; try { startTime = new LocalTime(startTimeInterval / 2, (startTimeInterval % 2) * 30); } catch (Exception ex) { - LOG.error( - "Error creating BasalProfileEntry: startTimeInterval={}, startTime_raw={}, hours={}, rateStrokes={}", - startTimeInterval, startTime_raw, startTimeInterval / 2, rateStrokes); + aapsLogger.error(LTag.PUMPBTCOMM, + "Error creating BasalProfileEntry: startTimeInterval={}, startTime_raw={}, hours={}, rateStrokes={}", + startTimeInterval, startTime_raw, startTimeInterval / 2, rateStrokes); throw ex; } } - - public BasalProfileEntry(byte rateByte, int startTimeByte) { + BasalProfileEntry(byte rateByte, int startTimeByte) { // rateByte is insulin delivery rate, U/hr, in 0.025 U increments // startTimeByte is time-of-day, in 30 minute increments - rate_raw = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(rateByte, true); + rate_raw = MedtronicUtil.getByteArrayFromUnsignedShort(rateByte, true); rate = rateByte * 0.025; - startTime_raw = (byte)startTimeByte; + startTime_raw = (byte) startTimeByte; startTime = new LocalTime(startTimeByte / 2, (startTimeByte % 2) * 30); } - public void setStartTime(LocalTime localTime) { this.startTime = localTime; } - public void setRate(double rate) { this.rate = rate; } - } 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 b079dc1a67..5cbc5a0a36 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 @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; @@ -19,11 +19,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; */ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - - public TempBasalPair() { - } - + private final AAPSLogger aapsLogger; /** * This constructor is for use with PumpHistoryDecoder @@ -32,8 +28,9 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo * @param startTimeByte * @param isPercent */ - public TempBasalPair(byte rateByte, int startTimeByte, boolean isPercent) { + public TempBasalPair(AAPSLogger aapsLogger, byte rateByte, int startTimeByte, boolean isPercent) { super(); + this.aapsLogger = aapsLogger; int rateInt = ByteUtil.asUINT8(rateByte); @@ -46,45 +43,48 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo } - public TempBasalPair(byte[] response) { + public TempBasalPair(AAPSLogger aapsLogger, byte[] response) { + super(); + this.aapsLogger = aapsLogger; if (L.isEnabled(L.PUMPCOMM)) - LOG.debug("Received TempBasal response: " + ByteUtil.getHex(response)); + aapsLogger.debug(LTag.PUMPBTCOMM, "Received TempBasal response: " + ByteUtil.getHex(response)); isPercent = response[0] == 1; if (isPercent) { insulinRate = response[1]; } else { - int strokes = MedtronicUtil.getInstance().makeUnsignedShort(response[2], response[3]); + int strokes = MedtronicUtil.makeUnsignedShort(response[2], response[3]); insulinRate = strokes / 40.0d; } - if (response.length<6) { + if (response.length < 6) { durationMinutes = ByteUtil.asUINT8(response[4]); } else { - durationMinutes = MedtronicUtil.getInstance().makeUnsignedShort(response[4], response[5]); + durationMinutes = MedtronicUtil.makeUnsignedShort(response[4], response[5]); } - LOG.warn("TempBasalPair (with {} byte response): {}", response.length, toString()); + aapsLogger.warn(LTag.PUMPBTCOMM, "TempBasalPair (with {} byte response): {}", response.length, toString()); } - public TempBasalPair(double insulinRate, boolean isPercent, int durationMinutes) { + public TempBasalPair(AAPSLogger aapsLogger, double insulinRate, boolean isPercent, int durationMinutes) { super(insulinRate, isPercent, durationMinutes); + this.aapsLogger = aapsLogger; } public byte[] getAsRawData() { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add((byte) 5); - byte[] insulinRate = MedtronicUtil.getInstance().getBasalStrokes(this.insulinRate, true); - byte timeMin = (byte) MedtronicUtil.getInstance().getIntervalFromMinutes(durationMinutes); + byte[] insulinRate = MedtronicUtil.getBasalStrokes(this.insulinRate, true); + byte timeMin = (byte) MedtronicUtil.getIntervalFromMinutes(durationMinutes); // list.add((byte) 0); // ? @@ -107,11 +107,11 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo list.add(insulinRate[1]); - return MedtronicUtil.getInstance().createByteArray(list); + return MedtronicUtil.createByteArray(list); } public boolean isCancelTBR() { - return (MedtronicUtil.getInstance().isSame(insulinRate, 0.0d) && durationMinutes == 0); + return (MedtronicUtil.isSame(insulinRate, 0.0d) && durationMinutes == 0); } @@ -128,7 +128,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo } - @Override + @NotNull @Override public String toString() { return "TempBasalPair [" + "Rate=" + insulinRate + ", DurationMinutes=" + durationMinutes + ", IsPercent=" + isPercent + "]"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicStatusRefreshType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicStatusRefreshType.java index e7b361ec13..09af9f3554 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicStatusRefreshType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicStatusRefreshType.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.medtronic.defs; -import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; - /** * Created by andy on 6/28/18. */ @@ -30,9 +28,9 @@ public enum MedtronicStatusRefreshType { } - public MedtronicCommandType getCommandType() { + public MedtronicCommandType getCommandType(MedtronicDeviceType medtronicDeviceType) { if (this == Configuration) { - return MedtronicCommandType.getSettings(MedtronicUtil.getInstance().getMedtronicPumpModel()); + return MedtronicCommandType.getSettings(medtronicDeviceType); } else return commandType; } 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 4587bfd65d..5ea62acdb2 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 @@ -66,16 +66,6 @@ public class MedtronicUtil { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil; - instance = this; - } - - private static MedtronicUtil instance; - - // TODO: replace by injection - @Deprecated - public static MedtronicUtil getInstance() { - if (instance == null) throw new IllegalStateException("MedtronicUtil not initialized"); - return instance; } public LocalTime getTimeFrom30MinInterval(int interval) { @@ -87,17 +77,17 @@ public class MedtronicUtil { } - public int getIntervalFromMinutes(int minutes) { + public static int getIntervalFromMinutes(int minutes) { return minutes / 30; } - public int makeUnsignedShort(int b2, int b1) { + public static int makeUnsignedShort(int b2, int b1) { int k = (b2 & 0xff) << 8 | b1 & 0xff; return k; } - public byte[] getByteArrayFromUnsignedShort(int shortValue, boolean returnFixedSize) { + public static byte[] getByteArrayFromUnsignedShort(int shortValue, boolean returnFixedSize) { byte highByte = (byte) (shortValue >> 8 & 0xFF); byte lowByte = (byte) (shortValue & 0xFF); @@ -110,12 +100,12 @@ public class MedtronicUtil { } - public byte[] createByteArray(byte... data) { + public static byte[] createByteArray(byte... data) { return data; } - public byte[] createByteArray(List data) { + public static byte[] createByteArray(List data) { byte[] array = new byte[data.size()]; @@ -142,7 +132,7 @@ public class MedtronicUtil { } - public byte[] getBasalStrokes(double amount, boolean returnFixedSize) { + public static byte[] getBasalStrokes(double amount, boolean returnFixedSize) { return getStrokes(amount, 40, returnFixedSize); } @@ -190,7 +180,7 @@ public class MedtronicUtil { } - public byte[] getStrokes(double amount, int strokesPerUnit, boolean returnFixedSize) { + public static byte[] getStrokes(double amount, int strokesPerUnit, boolean returnFixedSize) { int strokes = getStrokesInt(amount, strokesPerUnit); @@ -199,7 +189,7 @@ public class MedtronicUtil { } - public int getStrokesInt(double amount, int strokesPerUnit) { + public static int getStrokesInt(double amount, int strokesPerUnit) { int length = 1; int scrollRate = 1; @@ -456,7 +446,7 @@ public class MedtronicUtil { } - public boolean isSame(Double d1, Double d2) { + public static boolean isSame(Double d1, Double d2) { double diff = d1 - d2; return (Math.abs(diff) <= 0.000001); From 85558620fcdf04e81a48c63bdf67c25600375edb Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 16:23:05 +0200 Subject: [PATCH 11/23] MDT refactor pass 10 --- .../common/hw/rileylink/RileyLinkUtil.java | 41 +--------------- .../rileylink/service/RileyLinkService.java | 26 +++++----- .../pump/medtronic/MedtronicFragment.kt | 4 +- .../comm/MedtronicCommunicationManager.java | 14 +++--- .../pump/MedtronicPumpHistoryDecoder.java | 2 +- .../comm/history/pump/PumpHistoryEntry.java | 5 -- .../history/pump/PumpHistoryEntryType.java | 10 ++-- .../comm/history/pump/PumpHistoryResult.java | 49 +++++++------------ .../medtronic/comm/message/PacketType.java | 2 +- .../medtronic/comm/message/PumpMessage.java | 32 +++++------- .../medtronic/comm/ui/MedtronicUITask.java | 2 +- .../medtronic/data/dto/DailyTotalsDTO.java | 2 - .../medtronic/data/dto/TempBasalPair.java | 10 +--- .../medtronic/driver/MedtronicPumpStatus.java | 4 -- .../service/RileyLinkMedtronicService.java | 2 - 15 files changed, 62 insertions(+), 143 deletions(-) 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 75937141f6..d0c5eb73a5 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 @@ -31,7 +31,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistor import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceNotification; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceResult; @@ -50,9 +49,7 @@ public class RileyLinkUtil { public List historyRileyLink = new ArrayList<>(); public RileyLinkCommunicationManager rileyLinkCommunicationManager; static ServiceTask currentTask; - private RileyLinkBLE rileyLinkBLE; private RileyLinkServiceData rileyLinkServiceData; - private RileyLinkService rileyLinkService; private RileyLinkTargetFrequency rileyLinkTargetFrequency; private RileyLinkTargetDevice targetDevice; @@ -112,15 +109,6 @@ public class RileyLinkUtil { setServiceState(newState, null); } - - public RileyLinkError getError() { - if (rileyLinkServiceData != null) - return rileyLinkServiceData.errorCode; - else - return null; - } - - public RileyLinkServiceState getServiceState() { return workWithServiceState(null, null, false); } @@ -156,23 +144,12 @@ public class RileyLinkUtil { } - @Deprecated - public RileyLinkBLE getRileyLinkBLE() { - return rileyLinkBLE; - } - - - @Deprecated - public void setRileyLinkBLE(RileyLinkBLE rileyLinkBLEIn) { - rileyLinkBLE = rileyLinkBLEIn; - } - - public RileyLinkServiceData getRileyLinkServiceData() { return rileyLinkServiceData; } + @Deprecated public void setRileyLinkServiceData(RileyLinkServiceData rileyLinkServiceData) { this.rileyLinkServiceData = rileyLinkServiceData; } @@ -182,22 +159,6 @@ public class RileyLinkUtil { return rileyLinkServiceData.tuneUpDone; } - @Deprecated - public RileyLinkService getRileyLinkService() { - return rileyLinkService; - } - - - @Deprecated - public void setRileyLinkService(RileyLinkService rileyLinkService) { - this.rileyLinkService = rileyLinkService; - } - - public static boolean sendNotification(ServiceNotification notification, Integer clientHashcode) { - return false; - } - - // FIXME remove ? public static void setCurrentTask(ServiceTask task) { if (currentTask == null) { 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 df17174f66..282595a193 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 @@ -51,7 +51,6 @@ public abstract class RileyLinkService extends DaggerService { public void onCreate() { super.onCreate(); - rileyLinkUtil.setRileyLinkService(this); rileyLinkUtil.setEncoding(getEncoding()); initRileyLinkServiceData(); @@ -94,10 +93,7 @@ public abstract class RileyLinkService extends DaggerService { super.onDestroy(); //LOG.error("I die! I die!"); - if (rileyLinkBLE != null) { - rileyLinkBLE.disconnect(); // dispose of Gatt (disconnect and close) - rileyLinkBLE = null; - } + rileyLinkBLE.disconnect(); // dispose of Gatt (disconnect and close) if (mBroadcastReceiver != null) { mBroadcastReceiver.unregisterBroadcasts(); @@ -162,11 +158,6 @@ public abstract class RileyLinkService extends DaggerService { // returns true if our Rileylink configuration changed public boolean reconfigureRileyLink(String deviceAddress) { - if (rileyLinkBLE == null) { - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); - return false; - } - rileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkInitializing); if (rileyLinkBLE.isConnected()) { @@ -191,7 +182,7 @@ public abstract class RileyLinkService extends DaggerService { if (rileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) { if (!bluetoothInit()) { aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. {}", - rileyLinkUtil.getError() != null ? rileyLinkUtil.getError().name() : "Unknown error (null)"); + getError() != null ? getError().name() : "Unknown error (null)"); return false; } } @@ -245,15 +236,15 @@ public abstract class RileyLinkService extends DaggerService { public void disconnectRileyLink() { - if (this.rileyLinkBLE != null && this.rileyLinkBLE.isConnected()) { - this.rileyLinkBLE.disconnect(); + if (rileyLinkBLE.isConnected()) { + rileyLinkBLE.disconnect(); rileyLinkServiceData.rileylinkAddress = null; } rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); } - public RileyLinkBLE getRileyLinkBLE() { + @NotNull public RileyLinkBLE getRileyLinkBLE() { return rileyLinkBLE; } @@ -270,4 +261,11 @@ public abstract class RileyLinkService extends DaggerService { rfspy.setRileyLinkEncoding(encodingType); } } + + public RileyLinkError getError() { + if (rileyLinkServiceData != null) + return rileyLinkServiceData.errorCode; + else + return null; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 8d9b24c31b..b4e2a0739e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -178,7 +178,7 @@ class MedtronicFragment : DaggerFragment() { rileyLinkUtil.getServiceState()) as RileyLinkServiceState? val resourceId = medtronicPumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) - val rileyLinkError = rileyLinkUtil.getError() + val rileyLinkError = medtronicPumpPlugin.rileyLinkService?.error medtronic_rl_status.text = when { medtronicPumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) @@ -189,7 +189,7 @@ class MedtronicFragment : DaggerFragment() { } medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) - medtronicPumpStatus.rileyLinkError = checkStatusSet(medtronicPumpStatus.rileyLinkError, rileyLinkUtil.getError()) as RileyLinkError? + medtronicPumpStatus.rileyLinkError = checkStatusSet(medtronicPumpStatus.rileyLinkError, medtronicPumpPlugin.rileyLinkService?.error) as RileyLinkError? medtronic_errors.text = medtronicPumpStatus.rileyLinkError?.let { 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 178db5a61c..c2fb02dee0 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 @@ -85,7 +85,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager @Override public E createResponseMessage(byte[] payload, Class clazz) { - PumpMessage pumpMessage = new PumpMessage(payload); + PumpMessage pumpMessage = new PumpMessage(aapsLogger, payload); return (E) pumpMessage; } @@ -244,7 +244,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return rval; } else { aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithArgs: Pump did not ack Attention packet"); - return new PumpMessage("No ACK after Attention packet."); + return new PumpMessage(aapsLogger, "No ACK after Attention packet."); } } @@ -262,7 +262,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (shortResponse.commandType != MedtronicCommandType.CommandACK) { aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithFrames: Pump did not ack Attention packet"); - return new PumpMessage("No ACK after start message."); + return new PumpMessage(aapsLogger, "No ACK after start message."); } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: Got ACK response for Attention packet"); } @@ -287,7 +287,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.error(LTag.PUMPBTCOMM, "Run command with Frames FAILED (command={}, response={})", commandType.name(), rval.toString()); - return new PumpMessage("No ACK after frame #" + frameNr); + return new PumpMessage(aapsLogger, "No ACK after frame #" + frameNr); } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: Got ACK response for frame #{}", (frameNr)); } @@ -302,7 +302,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public PumpHistoryResult getPumpHistory(PumpHistoryEntry lastEntry, LocalDateTime targetDate) { - PumpHistoryResult pumpTotalResult = new PumpHistoryResult(lastEntry, targetDate == null ? null + PumpHistoryResult pumpTotalResult = new PumpHistoryResult(aapsLogger, lastEntry, targetDate == null ? null : DateTimeUtil.toATechDate(targetDate)); if (doWakeUpBeforeCommand) @@ -492,7 +492,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private PumpMessage makePumpMessage(MedtronicCommandType messageType, MessageBody messageBody) { - PumpMessage msg = new PumpMessage(); + PumpMessage msg = new PumpMessage(aapsLogger); msg.init(PacketType.Carelink, rileyLinkServiceData.pumpIDBytes, messageType, messageBody); return msg; } @@ -869,7 +869,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public boolean cancelTBR() { - return setTBR(new TempBasalPair(aapsLogger, 0.0d, false, 0)); + return setTBR(new TempBasalPair(0.0d, false, 0)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java index cb680f61f2..1d6f9a72cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java @@ -619,7 +619,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder> 3) == 0); // System.out.println("TBR: amount=" + tbr.getInsulinRate() + ", duration=" + tbr.getDurationMinutes() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.java index 0652339c9d..db9e26cf04 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.java @@ -2,11 +2,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump; import com.google.gson.annotations.Expose; -import org.slf4j.Logger; - import java.util.Objects; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; 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.comm.history.MedtronicHistoryEntry; @@ -21,8 +18,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceTyp public class PumpHistoryEntry extends MedtronicHistoryEntry { - private static Logger LOG = StacktraceLoggerWrapper.getLogger(PumpHistoryEntry.class); - @Expose private PumpHistoryEntryType entryType; private Integer opCode; // this is set only when we have unknown 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 2443948188..cf3067c4ab 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 @@ -158,8 +158,7 @@ public enum PumpHistoryEntryType // implements CodeEnum TempBasalCombined(0xfe, "TBR", PumpHistoryEntryGroup.Basal), // UnknownBasePacket(0xff, "Unknown Base Packet", PumpHistoryEntryGroup.Unknown); - private static Map opCodeMap = new HashMap(); - private static PumpHistoryEntryType tddType; + private static Map opCodeMap = new HashMap<>(); static { for (PumpHistoryEntryType type : values()) { @@ -171,7 +170,7 @@ public enum PumpHistoryEntryType // implements CodeEnum private int opCode; private String description; - private int headLength = 0; + private int headLength; private int dateLength; // private MinimedDeviceType deviceType; private int bodyLength; @@ -181,8 +180,7 @@ public enum PumpHistoryEntryType // implements CodeEnum private List specialRulesHead; private List specialRulesBody; private boolean hasSpecialRules = false; - private PumpHistoryEntryGroup group = PumpHistoryEntryGroup.Unknown; - private static Object TDDType; + private PumpHistoryEntryGroup group; PumpHistoryEntryType(int opCode, String name, PumpHistoryEntryGroup group) { @@ -400,7 +398,7 @@ public enum PumpHistoryEntryType // implements CodeEnum int size; - public SpecialRule(MedtronicDeviceType deviceType, int size) { + SpecialRule(MedtronicDeviceType deviceType, int size) { this.deviceType = deviceType; this.size = size; } 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 f5ffb13a73..4ddf73eafe 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 @@ -1,24 +1,21 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.ArrayList; import java.util.Collections; import java.util.List; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; /** * History page contains data, sorted from newest to oldest (0=newest..n=oldest) - * + *

* Created by andy on 9/23/18. */ public class PumpHistoryResult { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private final AAPSLogger aapsLogger; private boolean searchFinished = false; private PumpHistoryEntry searchEntry = null; @@ -28,23 +25,22 @@ public class PumpHistoryResult { public List validEntries; - public PumpHistoryResult(PumpHistoryEntry searchEntry, Long targetDate) { + public PumpHistoryResult(AAPSLogger aapsLogger, PumpHistoryEntry searchEntry, Long targetDate) { + this.aapsLogger = aapsLogger; if (searchEntry != null) { /* * this.searchEntry = searchEntry; * this.searchType = SearchType.LastEntry; - * LOG.debug("PumpHistoryResult. Search parameters: Last Entry: " + searchEntry.atechDateTime + " type=" + * aapsLogger.debug(LTag.PUMPBTCOMM,"PumpHistoryResult. Search parameters: Last Entry: " + searchEntry.atechDateTime + " type=" * + searchEntry.getEntryType().name()); */ this.searchDate = searchEntry.atechDateTime; this.searchType = SearchType.Date; - if (isLogEnabled()) - LOG.debug("PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate); + aapsLogger.debug(LTag.PUMPBTCOMM, "PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate); } else if (targetDate != null) { this.searchDate = targetDate; this.searchType = SearchType.Date; - if (isLogEnabled()) - LOG.debug("PumpHistoryResult. Search parameters: Date: " + targetDate); + aapsLogger.debug(LTag.PUMPBTCOMM, "PumpHistoryResult. Search parameters: Date: " + targetDate); } // this.unprocessedEntries = new ArrayList<>(); @@ -54,7 +50,7 @@ public class PumpHistoryResult { public void addHistoryEntries(List entries, int page) { this.unprocessedEntries = entries; - //LOG.debug("PumpHistoryResult. Unprocessed entries: {}", MedtronicUtil.getGsonInstance().toJson(entries)); + //aapsLogger.debug(LTag.PUMPBTCOMM,"PumpHistoryResult. Unprocessed entries: {}", MedtronicUtil.getGsonInstance().toJson(entries)); processEntries(); } @@ -66,47 +62,47 @@ public class PumpHistoryResult { switch (searchType) { case None: - //LOG.debug("PE. None search"); + //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. None search"); this.validEntries.addAll(this.unprocessedEntries); break; case LastEntry: { - LOG.debug("PE. Last entry search"); + aapsLogger.debug(LTag.PUMPBTCOMM, "PE. Last entry search"); //Collections.sort(this.unprocessedEntries, new PumpHistoryEntry.Comparator()); - LOG.debug("PE. PumpHistoryResult. Search entry date: " + searchEntry.atechDateTime); + aapsLogger.debug(LTag.PUMPBTCOMM, "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); + //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. Item found {}.", unprocessedEntry); searchFinished = true; break; } - //LOG.debug("PE. Entry {} added.", unprocessedEntry); + //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. Entry {} added.", unprocessedEntry); this.validEntries.add(unprocessedEntry); } } break; case Date: { - LOG.debug("PE. Date search: Search date: {}", this.searchDate); + aapsLogger.debug(LTag.PUMPBTCOMM, "PE. Date search: Search date: {}", this.searchDate); for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) { if (unprocessedEntry.atechDateTime == null || unprocessedEntry.atechDateTime == 0) { - LOG.debug("PE. PumpHistoryResult. Search entry date: Entry with no date: {}", unprocessedEntry); + aapsLogger.debug(LTag.PUMPBTCOMM, "PE. PumpHistoryResult. Search entry date: Entry with no date: {}", unprocessedEntry); continue; } if (unprocessedEntry.isAfter(this.searchDate)) { this.validEntries.add(unprocessedEntry); } else { -// LOG.debug("PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]", +// aapsLogger.debug(LTag.PUMPBTCOMM,"PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]", // DateTimeUtil.getYear(unprocessedEntry.atechDateTime), unprocessedEntry); if (DateTimeUtil.getYear(unprocessedEntry.atechDateTime) > 2015) olderEntries++; @@ -123,7 +119,7 @@ public class PumpHistoryResult { } // switch - //LOG.debug("PE. Valid Entries: {}", validEntries); + //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. Valid Entries: {}", validEntries); } @@ -178,11 +174,4 @@ public class PumpHistoryResult { LastEntry, // Date } - - - private boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); - } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PacketType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PacketType.java index 8d02063d66..03b1ad153c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PacketType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/PacketType.java @@ -25,7 +25,7 @@ public enum PacketType { } } - private byte value = 0; + private byte value; PacketType(int value) { 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 9d63574748..99712eb9bd 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 @@ -1,10 +1,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.message; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; 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.medtronic.defs.MedtronicCommandType; @@ -14,9 +11,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandTy */ public class PumpMessage implements RLMessage { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private final AAPSLogger aapsLogger; - public PacketType packetType = PacketType.Carelink; + private PacketType packetType = PacketType.Carelink; public byte[] address = new byte[]{0, 0, 0}; public MedtronicCommandType commandType; public Byte invalidCommandType; @@ -26,18 +23,20 @@ public class PumpMessage implements RLMessage { public static final int FRAME_DATA_LENGTH = 64; - public PumpMessage(String error) { + public PumpMessage(AAPSLogger aapsLogger, String error) { this.error = error; + this.aapsLogger = aapsLogger; } - public PumpMessage(byte[] rxData) { + public PumpMessage(AAPSLogger aapsLogger, byte[] rxData) { init(rxData); + this.aapsLogger = aapsLogger; } - public PumpMessage() { - + public PumpMessage(AAPSLogger aapsLogger) { + this.aapsLogger = aapsLogger; } @@ -67,8 +66,7 @@ public class PumpMessage implements RLMessage { if (rxData.length > 4) { this.commandType = MedtronicCommandType.getByCode(rxData[4]); if (this.commandType == MedtronicCommandType.InvalidCommand) { - if (isLogEnabled()) - LOG.error("PumpMessage - Unknown commandType " + rxData[4]); + aapsLogger.error(LTag.PUMPBTCOMM, "PumpMessage - Unknown commandType " + rxData[4]); } } if (rxData.length > 5) { @@ -80,7 +78,7 @@ public class PumpMessage implements RLMessage { @Override public byte[] getTxData() { - byte[] rval = ByteUtil.concat(new byte[]{(byte) packetType.getValue()}, address); + byte[] rval = ByteUtil.concat(new byte[]{packetType.getValue()}, address); rval = ByteUtil.concat(rval, commandType.getCommandCode()); rval = ByteUtil.concat(rval, messageBody.getTxData()); return rval; @@ -211,10 +209,4 @@ 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/MedtronicUITask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUITask.java index 6262e7ee98..51a8020fcd 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 @@ -161,7 +161,7 @@ public class MedtronicUITask { private TempBasalPair getTBRSettings() { - return new TempBasalPair(aapsLogger, getDoubleFromParameters(0), // + return new TempBasalPair(getDoubleFromParameters(0), // false, // getIntegerFromParameters(1)); } 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 01327a8ea4..8ca17e152f 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 @@ -24,8 +24,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpH public class DailyTotalsDTO { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - // bg avg, bg low hi, number Bgs, // Sen Avg, Sen Lo/Hi, Sens Cal/Data = 0/0, // Insulin=19.8[8,9], Basal[10,11], Bolus[13,14], Carbs, 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 5cbc5a0a36..09dd929074 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 @@ -19,8 +19,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; */ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair { - private final AAPSLogger aapsLogger; - /** * This constructor is for use with PumpHistoryDecoder * @@ -28,10 +26,8 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo * @param startTimeByte * @param isPercent */ - public TempBasalPair(AAPSLogger aapsLogger, byte rateByte, int startTimeByte, boolean isPercent) { + public TempBasalPair(byte rateByte, int startTimeByte, boolean isPercent) { super(); - this.aapsLogger = aapsLogger; - int rateInt = ByteUtil.asUINT8(rateByte); if (isPercent) @@ -45,7 +41,6 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo public TempBasalPair(AAPSLogger aapsLogger, byte[] response) { super(); - this.aapsLogger = aapsLogger; if (L.isEnabled(L.PUMPCOMM)) aapsLogger.debug(LTag.PUMPBTCOMM, "Received TempBasal response: " + ByteUtil.getHex(response)); @@ -71,9 +66,8 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo } - public TempBasalPair(AAPSLogger aapsLogger, double insulinRate, boolean isPercent, int durationMinutes) { + public TempBasalPair(double insulinRate, boolean isPercent, int durationMinutes) { super(insulinRate, isPercent, durationMinutes); - this.aapsLogger = aapsLogger; } 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 eb503b7785..e722e44818 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 @@ -44,10 +44,6 @@ public class MedtronicPumpStatus extends PumpStatus { public RileyLinkError rileyLinkError; public PumpDeviceState pumpDeviceState = PumpDeviceState.NeverContacted; public MedtronicDeviceType medtronicDeviceType = null; - public double currentBasal = 0; - public int tempBasalInProgress = 0; - public int tempBasalRatio = 0; - public int tempBasalRemainMin = 0; public Date tempBasalStart; public Double tempBasalAmount = 0.0d; 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 0891dd39bd..de6395d908 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 @@ -108,8 +108,6 @@ public class RileyLinkMedtronicService extends RileyLinkService { rfspy = new RFSpy(rileyLinkBLE); rfspy.startReader(); - rileyLinkUtil.setRileyLinkBLE(rileyLinkBLE); - // init rileyLinkCommunicationManager medtronicCommunicationManager = new MedtronicCommunicationManager(injector, rfspy); medtronicUIComm = new MedtronicUIComm(injector, aapsLogger, medtronicUtil, medtronicUIPostprocessor, medtronicCommunicationManager); From 6add8a8d86ad4ed243242b1e3eba2ad43020b1c9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 18:14:06 +0200 Subject: [PATCH 12/23] MDT refactor pass 11 --- .../dependencyInjection/AppComponent.kt | 4 + .../dependencyInjection/AppModule.kt | 4 + .../RileyLinkCommunicationManager.java | 10 +- .../common/hw/rileylink/RileyLinkUtil.java | 78 +-------- .../common/hw/rileylink/ble/RileyLinkBLE.java | 153 ++++++++---------- .../hw/rileylink/ble/data/RFSpyResponse.java | 7 +- .../hw/rileylink/ble/data/RadioResponse.java | 39 ++--- .../dialog/RileyLinkStatusActivity.java | 6 +- .../RileyLinkStatusGeneralFragment.java | 12 +- .../service/RileyLinkBroadcastReceiver.java | 39 ++--- .../rileylink/service/RileyLinkService.java | 32 ++-- .../service/RileyLinkServiceData.java | 60 ++++++- .../tasks/InitializePumpManagerTask.java | 48 +++--- .../rileylink/service/tasks/ServiceTask.java | 1 - .../pump/medtronic/MedtronicFragment.kt | 15 +- .../pump/medtronic/MedtronicPumpPlugin.java | 8 +- .../comm/MedtronicCommunicationManager.java | 8 +- .../medtronic/driver/MedtronicPumpStatus.java | 2 - .../service/RileyLinkMedtronicService.java | 11 +- .../pump/medtronic/util/MedtronicUtil.java | 19 ++- 20 files changed, 255 insertions(+), 301 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index db7cbba831..64f08720e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -30,6 +30,8 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask @@ -199,6 +201,8 @@ interface AppComponent : AndroidInjector { fun injectInitializePumpManagerTask(initializePumpManagerTask: InitializePumpManagerTask) fun injectResetRileyLinkConfigurationTask(resetRileyLinkConfigurationTask: ResetRileyLinkConfigurationTask) fun injectWakeAndTuneTask(wakeAndTuneTask: WakeAndTuneTask) + fun injectRadioResponse(radioResponse: RadioResponse) + fun injectRileyLinkBLE(rileyLinkBLE: RileyLinkBLE) @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 5273cb61d5..25d3d58668 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -47,6 +47,8 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask @@ -292,6 +294,8 @@ open class AppModule { @ContributesAndroidInjector fun initializePumpManagerTaskProvider(): InitializePumpManagerTask @ContributesAndroidInjector fun resetRileyLinkConfigurationTaskProvider(): ResetRileyLinkConfigurationTask @ContributesAndroidInjector fun wakeAndTuneTaskProvider(): WakeAndTuneTask + @ContributesAndroidInjector fun radioResponseProvider(): RadioResponse + @ContributesAndroidInjector fun rileyLinkBLEProvider(): RileyLinkBLE @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider 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 695f6e3292..e96ab06f27 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 @@ -49,7 +49,6 @@ public abstract class RileyLinkCommunicationManager { protected String receiverDeviceID; // String representation of receiver device (ex. Pump (xxxxxx) or Pod (yyyyyy)) protected long lastGoodReceiverCommunicationTime = 0; // protected PumpStatus pumpStatus; - protected RileyLinkServiceData rileyLinkServiceData; private long nextWakeUpRequired = 0L; private int timeoutCount = 0; @@ -59,7 +58,6 @@ public abstract class RileyLinkCommunicationManager { this.injector = injector; injector.androidInjector().inject(this); this.rfspy = rfspy; - this.rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData(); } @@ -92,7 +90,7 @@ public abstract class RileyLinkCommunicationManager { RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(msg.getTxData()), (byte) 0, (byte) repeatCount, (byte) 0, (byte) 0, timeout_ms, (byte) retryCount, extendPreamble_ms); - RadioResponse radioResponse = rfSpyResponse.getRadioResponse(); + RadioResponse radioResponse = rfSpyResponse.getRadioResponse(injector); E response = createResponseMessage(radioResponse.getPayload(), clazz); if (response.isValid()) { @@ -122,7 +120,7 @@ public abstract class RileyLinkCommunicationManager { } if (showPumpMessages) { - aapsLogger.info(LTag.PUMPBTCOMM, "Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse().getPayload())); + aapsLogger.info(LTag.PUMPBTCOMM, "Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse(injector).getPayload())); } return response; @@ -246,7 +244,7 @@ public abstract class RileyLinkCommunicationManager { if (resp.wasTimeout()) { aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: Failed to find pump at frequency {}", frequencies[i]); } else if (resp.looksLikeRadioPacket()) { - RadioResponse radioResponse = new RadioResponse(); + RadioResponse radioResponse = new RadioResponse(injector); try { @@ -334,7 +332,7 @@ public abstract class RileyLinkCommunicationManager { if (resp.wasTimeout()) { aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: no pump response at frequency {}", freqMHz); } else if (resp.looksLikeRadioPacket()) { - RadioResponse radioResponse = new RadioResponse(); + RadioResponse radioResponse = new RadioResponse(injector); try { radioResponse.init(resp.getRaw()); 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 d0c5eb73a5..960173a8bf 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 @@ -46,13 +46,12 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDe @Singleton public class RileyLinkUtil { - public List historyRileyLink = new ArrayList<>(); + private List historyRileyLink = new ArrayList<>(); public RileyLinkCommunicationManager rileyLinkCommunicationManager; + @Deprecated static ServiceTask currentTask; - private RileyLinkServiceData rileyLinkServiceData; private RileyLinkTargetFrequency rileyLinkTargetFrequency; - private RileyLinkTargetDevice targetDevice; private RileyLinkEncodingType encoding; private RileyLinkSelectPreference rileyLinkSelectPreference; private Encoding4b6b encoding4b6b; @@ -104,62 +103,8 @@ public class RileyLinkUtil { LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } - - public void setServiceState(RileyLinkServiceState newState) { - setServiceState(newState, null); - } - - public RileyLinkServiceState getServiceState() { - return workWithServiceState(null, null, false); - } - - - public void setServiceState(RileyLinkServiceState newState, RileyLinkError errorCode) { - workWithServiceState(newState, errorCode, true); - } - - - private synchronized RileyLinkServiceState workWithServiceState(RileyLinkServiceState newState, - RileyLinkError errorCode, boolean set) { - - if (set) { - - rileyLinkServiceData.serviceState = newState; - rileyLinkServiceData.errorCode = errorCode; - - aapsLogger.info(LTag.PUMP, "RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " - + errorCode.name()); - - historyRileyLink.add(new RLHistoryItem(rileyLinkServiceData.serviceState, - rileyLinkServiceData.errorCode, targetDevice)); - rxBus.send(new EventMedtronicDeviceStatusChange(newState, errorCode)); - return null; - - } else { - return (rileyLinkServiceData == null || rileyLinkServiceData.serviceState == null) ? // - RileyLinkServiceState.NotStarted - : rileyLinkServiceData.serviceState; - } - - } - - - public RileyLinkServiceData getRileyLinkServiceData() { - return rileyLinkServiceData; - } - - - @Deprecated - public void setRileyLinkServiceData(RileyLinkServiceData rileyLinkServiceData) { - this.rileyLinkServiceData = rileyLinkServiceData; - } - - - public boolean hasPumpBeenTunned() { - return rileyLinkServiceData.tuneUpDone; - } - // FIXME remove ? + @Deprecated public static void setCurrentTask(ServiceTask task) { if (currentTask == null) { currentTask = task; @@ -169,6 +114,7 @@ public class RileyLinkUtil { } + @Deprecated public static void finishCurrentTask(ServiceTask task) { if (task != currentTask) { //LOG.error("finishCurrentTask: task does not match"); @@ -257,42 +203,26 @@ public class RileyLinkUtil { return new BleAdvertisedData(uuids, name); } - public List getRileyLinkHistory() { return historyRileyLink; } - - public RileyLinkTargetDevice getTargetDevice() { - return targetDevice; - } - - - public void setTargetDevice(RileyLinkTargetDevice targetDevice) { - this.targetDevice = targetDevice; - } - - public void setRileyLinkSelectPreference(RileyLinkSelectPreference rileyLinkSelectPreference) { this.rileyLinkSelectPreference = rileyLinkSelectPreference; } - public RileyLinkSelectPreference getRileyLinkSelectPreference() { return rileyLinkSelectPreference; } - public Encoding4b6b getEncoding4b6b() { return encoding4b6b; } - public void setFirmwareVersion(RileyLinkFirmwareVersion firmwareVersion) { this.firmwareVersion = firmwareVersion; } - public RileyLinkFirmwareVersion getFirmwareVersion() { return firmwareVersion; } 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 49f1b426e3..cb4bc6c615 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 @@ -12,15 +12,16 @@ import android.content.Context; import android.os.SystemClock; import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; import java.util.UUID; import java.util.concurrent.Semaphore; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; 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; @@ -31,6 +32,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operation import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.DescriptorWriteOperation; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; @@ -40,7 +42,9 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; */ public class RileyLinkBLE { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + @Inject AAPSLogger aapsLogger; + @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject RileyLinkUtil rileyLinkUtil; private final Context context; public boolean gattDebugEnabled = true; @@ -55,24 +59,24 @@ public class RileyLinkBLE { private boolean mIsConnected = false; - public RileyLinkBLE(final Context context) { + public RileyLinkBLE(HasAndroidInjector injector, final Context context) { + injector.androidInjector().inject(this); this.context = context; this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (isLogEnabled()) - LOG.debug("BT Adapter: " + this.bluetoothAdapter); + aapsLogger.debug(LTag.PUMPBTCOMM, "BT Adapter: " + this.bluetoothAdapter); bluetoothGattCallback = new BluetoothGattCallback() { @Override public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { super.onCharacteristicChanged(gatt, characteristic); - if (gattDebugEnabled && isLogEnabled()) { - LOG.trace(ThreadUtil.sig() + "onCharacteristicChanged " + if (gattDebugEnabled) { + aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "onCharacteristicChanged " + GattAttributes.lookup(characteristic.getUuid()) + " " + ByteUtil.getHex(characteristic.getValue())); if (characteristic.getUuid().equals(UUID.fromString(GattAttributes.CHARA_RADIO_RESPONSE_COUNT))) { - LOG.debug("Response Count is " + ByteUtil.shortHexString(characteristic.getValue())); + aapsLogger.debug(LTag.PUMPBTCOMM, "Response Count is " + ByteUtil.shortHexString(characteristic.getValue())); } } if (radioResponseCountNotified != null) { @@ -87,8 +91,8 @@ public class RileyLinkBLE { super.onCharacteristicRead(gatt, characteristic, status); final String statusMessage = getGattStatusMessage(status); - if (gattDebugEnabled && isLogEnabled()) { - LOG.trace(ThreadUtil.sig() + "onCharacteristicRead (" + if (gattDebugEnabled) { + aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "onCharacteristicRead (" + GattAttributes.lookup(characteristic.getUuid()) + ") " + statusMessage + ":" + ByteUtil.getHex(characteristic.getValue())); } @@ -102,8 +106,8 @@ public class RileyLinkBLE { super.onCharacteristicWrite(gatt, characteristic, status); final String uuidString = GattAttributes.lookup(characteristic.getUuid()); - if (gattDebugEnabled && isLogEnabled()) { - LOG.trace(ThreadUtil.sig() + "onCharacteristicWrite " + getGattStatusMessage(status) + " " + if (gattDebugEnabled) { + aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "onCharacteristicWrite " + getGattStatusMessage(status) + " " + uuidString + " " + ByteUtil.shortHexString(characteristic.getValue())); } mCurrentOperation.gattOperationCompletionCallback(characteristic.getUuid(), characteristic.getValue()); @@ -116,7 +120,7 @@ public class RileyLinkBLE { // https://github.com/NordicSemiconductor/puck-central-android/blob/master/PuckCentral/app/src/main/java/no/nordicsemi/puckcentral/bluetooth/gatt/GattManager.java#L117 if (status == 133) { - LOG.error("Got the status 133 bug, closing gatt"); + aapsLogger.error(LTag.PUMPBTCOMM, "Got the status 133 bug, closing gatt"); disconnect(); SystemClock.sleep(500); return; @@ -136,29 +140,27 @@ public class RileyLinkBLE { stateMessage = "UNKNOWN newState (" + newState + ")"; } - if (isLogEnabled()) - LOG.warn("onConnectionStateChange " + getGattStatusMessage(status) + " " + stateMessage); + aapsLogger.warn(LTag.PUMPBTCOMM, "onConnectionStateChange " + getGattStatusMessage(status) + " " + stateMessage); } if (newState == BluetoothProfile.STATE_CONNECTED) { if (status == BluetoothGatt.GATT_SUCCESS) { - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); } else { - if (isLogEnabled()) - LOG.debug("BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); + aapsLogger.debug(LTag.PUMPBTCOMM, "BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); } } else if ((newState == BluetoothProfile.STATE_CONNECTING) || // (newState == BluetoothProfile.STATE_DISCONNECTING)) { - // LOG.debug("We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" : + // aapsLogger.debug(LTag.PUMPBTCOMM,"We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" : // "Disconnecting"); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); if (manualDisconnect) close(); - LOG.warn("RileyLink Disconnected."); + aapsLogger.warn(LTag.PUMPBTCOMM, "RileyLink Disconnected."); } else { - LOG.warn("Some other state: (status={},newState={})", status, newState); + aapsLogger.warn(LTag.PUMPBTCOMM, "Some other state: (status={},newState={})", status, newState); } } @@ -166,8 +168,8 @@ public class RileyLinkBLE { @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorWrite(gatt, descriptor, status); - if (gattDebugEnabled && isLogEnabled()) { - LOG.warn("onDescriptorWrite " + GattAttributes.lookup(descriptor.getUuid()) + " " + if (gattDebugEnabled) { + aapsLogger.warn(LTag.PUMPBTCOMM, "onDescriptorWrite " + GattAttributes.lookup(descriptor.getUuid()) + " " + getGattStatusMessage(status) + " written: " + ByteUtil.getHex(descriptor.getValue())); } mCurrentOperation.gattOperationCompletionCallback(descriptor.getUuid(), descriptor.getValue()); @@ -178,8 +180,8 @@ 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 && isLogEnabled()) { - LOG.warn("onDescriptorRead " + getGattStatusMessage(status) + " status " + descriptor); + if (gattDebugEnabled) { + aapsLogger.warn(LTag.PUMPBTCOMM, "onDescriptorRead " + getGattStatusMessage(status) + " status " + descriptor); } } @@ -187,8 +189,8 @@ public class RileyLinkBLE { @Override public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { super.onMtuChanged(gatt, mtu, status); - if (gattDebugEnabled && isLogEnabled()) { - LOG.warn("onMtuChanged " + mtu + " status " + status); + if (gattDebugEnabled) { + aapsLogger.warn(LTag.PUMPBTCOMM, "onMtuChanged " + mtu + " status " + status); } } @@ -196,8 +198,8 @@ public class RileyLinkBLE { @Override public void onReadRemoteRssi(final BluetoothGatt gatt, int rssi, int status) { super.onReadRemoteRssi(gatt, rssi, status); - if (gattDebugEnabled && isLogEnabled()) { - LOG.warn("onReadRemoteRssi " + getGattStatusMessage(status) + ": " + rssi); + if (gattDebugEnabled) { + aapsLogger.warn(LTag.PUMPBTCOMM, "onReadRemoteRssi " + getGattStatusMessage(status) + ": " + rssi); } } @@ -205,8 +207,8 @@ public class RileyLinkBLE { @Override public void onReliableWriteCompleted(BluetoothGatt gatt, int status) { super.onReliableWriteCompleted(gatt, status); - if (gattDebugEnabled && isLogEnabled()) { - LOG.warn("onReliableWriteCompleted status " + status); + if (gattDebugEnabled) { + aapsLogger.warn(LTag.PUMPBTCOMM, "onReliableWriteCompleted status " + status); } } @@ -232,27 +234,26 @@ public class RileyLinkBLE { } } - if (gattDebugEnabled && isLogEnabled()) { - LOG.warn("onServicesDiscovered " + getGattStatusMessage(status)); + if (gattDebugEnabled) { + aapsLogger.warn(LTag.PUMPBTCOMM, "onServicesDiscovered " + getGattStatusMessage(status)); } - LOG.info("Gatt device is RileyLink device: " + rileyLinkFound); + aapsLogger.info(LTag.PUMPBTCOMM, "Gatt device is RileyLink device: " + rileyLinkFound); if (rileyLinkFound) { mIsConnected = true; - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady); // RileyLinkUtil.sendNotification(new // ServiceNotification(RileyLinkConst.Intents.RileyLinkReady), null); } else { mIsConnected = false; - RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.RileyLinkError, + rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkError, RileyLinkError.DeviceIsNotRileyLink); } } else { - if (isLogEnabled()) - LOG.debug("onServicesDiscovered " + getGattStatusMessage(status)); - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed); + aapsLogger.debug(LTag.PUMPBTCOMM, "onServicesDiscovered " + getGattStatusMessage(status)); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed); } } }; @@ -261,9 +262,7 @@ public class RileyLinkBLE { private boolean isAnyRileyLinkServiceFound(BluetoothGattService service) { - boolean found = false; - - found = GattAttributes.isRileyLink(service.getUuid()); + boolean found = GattAttributes.isRileyLink(service.getUuid()); if (found) { return true; @@ -313,7 +312,7 @@ public class RileyLinkBLE { stringBuilder.append("\n\n"); - LOG.warn(stringBuilder.toString()); + aapsLogger.warn(LTag.PUMPBTCOMM, stringBuilder.toString()); List includedServices = service.getIncludedServices(); @@ -324,7 +323,7 @@ public class RileyLinkBLE { } - public void registerRadioResponseCountNotification(Runnable notifier) { + void registerRadioResponseCountNotification(Runnable notifier) { radioResponseCountNotified = notifier; } @@ -342,11 +341,10 @@ public class RileyLinkBLE { } if (bluetoothConnectionGatt.discoverServices()) { - if (isLogEnabled()) - LOG.warn("Starting to discover GATT Services."); + aapsLogger.warn(LTag.PUMPBTCOMM, "Starting to discover GATT Services."); return true; } else { - LOG.error("Cannot discover GATT Services."); + aapsLogger.error(LTag.PUMPBTCOMM, "Cannot discover GATT Services."); return false; } } @@ -356,7 +354,7 @@ public class RileyLinkBLE { BLECommOperationResult result = setNotification_blocking(UUID.fromString(GattAttributes.SERVICE_RADIO), // UUID.fromString(GattAttributes.CHARA_RADIO_RESPONSE_COUNT)); if (result.resultCode != BLECommOperationResult.RESULT_SUCCESS) { - LOG.error("Error setting response count notification"); + aapsLogger.error(LTag.PUMPBTCOMM, "Error setting response count notification"); return false; } return true; @@ -364,36 +362,34 @@ public class RileyLinkBLE { public void findRileyLink(String RileyLinkAddress) { - if (isLogEnabled()) - LOG.debug("RileyLink address: " + RileyLinkAddress); + aapsLogger.debug(LTag.PUMPBTCOMM, "RileyLink address: " + RileyLinkAddress); // Must verify that this is a valid MAC, or crash. rileyLinkDevice = bluetoothAdapter.getRemoteDevice(RileyLinkAddress); // if this succeeds, we get a connection state change callback? - if (rileyLinkDevice!=null) { + if (rileyLinkDevice != null) { connectGatt(); } else { - LOG.error("RileyLink device not found with address: " + RileyLinkAddress); + aapsLogger.error(LTag.PUMPBTCOMM, "RileyLink device not found with address: " + RileyLinkAddress); } } // This function must be run on UI thread. public void connectGatt() { - if (this.rileyLinkDevice==null) { - LOG.error("RileyLink device is null, can't do connectGatt."); + if (this.rileyLinkDevice == null) { + aapsLogger.error(LTag.PUMPBTCOMM, "RileyLink device is null, can't do connectGatt."); return; } bluetoothConnectionGatt = rileyLinkDevice.connectGatt(context, true, bluetoothGattCallback); // , BluetoothDevice.TRANSPORT_LE if (bluetoothConnectionGatt == null) { - LOG.error("Failed to connect to Bluetooth Low Energy device at " + bluetoothAdapter.getAddress()); + aapsLogger.error(LTag.PUMPBTCOMM, "Failed to connect to Bluetooth Low Energy device at " + bluetoothAdapter.getAddress()); } else { if (gattDebugEnabled) { - if (isLogEnabled()) - LOG.debug("Gatt Connected."); + aapsLogger.debug(LTag.PUMPBTCOMM, "Gatt Connected."); } } } @@ -401,8 +397,7 @@ public class RileyLinkBLE { public void disconnect() { mIsConnected = false; - if (isLogEnabled()) - LOG.warn("Closing GATT connection"); + aapsLogger.warn(LTag.PUMPBTCOMM, "Closing GATT connection"); // Close old conenction if (bluetoothConnectionGatt != null) { // Not sure if to disconnect or to close first.. @@ -420,7 +415,7 @@ public class RileyLinkBLE { } - public BLECommOperationResult setNotification_blocking(UUID serviceUUID, UUID charaUUID) { + private BLECommOperationResult setNotification_blocking(UUID serviceUUID, UUID charaUUID) { BLECommOperationResult rval = new BLECommOperationResult(); if (bluetoothConnectionGatt != null) { @@ -428,7 +423,7 @@ public class RileyLinkBLE { gattOperationSema.acquire(); SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow } catch (InterruptedException e) { - LOG.error("setNotification_blocking: interrupted waiting for gattOperationSema"); + aapsLogger.error(LTag.PUMPBTCOMM, "setNotification_blocking: interrupted waiting for gattOperationSema"); return rval; } if (mCurrentOperation != null) { @@ -437,7 +432,7 @@ public class RileyLinkBLE { if (bluetoothConnectionGatt.getService(serviceUUID) == null) { // Catch if the service is not supported by the BLE device rval.resultCode = BLECommOperationResult.RESULT_NONE; - LOG.error("BT Device not supported"); + aapsLogger.error(LTag.PUMPBTCOMM, "BT Device not supported"); // TODO: 11/07/2016 UI update for user } else { BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID) @@ -447,8 +442,7 @@ public class RileyLinkBLE { List list = chara.getDescriptors(); if (gattDebugEnabled) { for (int i = 0; i < list.size(); i++) { - if (isLogEnabled()) - LOG.debug("Found descriptor: " + list.get(i).toString()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Found descriptor: " + list.get(i).toString()); } } BluetoothGattDescriptor descr = list.get(0); @@ -468,7 +462,7 @@ public class RileyLinkBLE { gattOperationSema.release(); } } else { - LOG.error("setNotification_blocking: not configured!"); + aapsLogger.error(LTag.PUMPBTCOMM, "setNotification_blocking: not configured!"); rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED; } return rval; @@ -476,7 +470,7 @@ public class RileyLinkBLE { // call from main - public BLECommOperationResult writeCharacteristic_blocking(UUID serviceUUID, UUID charaUUID, byte[] value) { + BLECommOperationResult writeCharacteristic_blocking(UUID serviceUUID, UUID charaUUID, byte[] value) { BLECommOperationResult rval = new BLECommOperationResult(); if (bluetoothConnectionGatt != null) { rval.value = value; @@ -484,7 +478,7 @@ public class RileyLinkBLE { gattOperationSema.acquire(); SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow } catch (InterruptedException e) { - LOG.error("writeCharacteristic_blocking: interrupted waiting for gattOperationSema"); + aapsLogger.error(LTag.PUMPBTCOMM, "writeCharacteristic_blocking: interrupted waiting for gattOperationSema"); return rval; } @@ -497,7 +491,7 @@ public class RileyLinkBLE { // app that created the bluetoothConnectionGatt has been destroyed/created, // e.g. when the user switches from portrait to landscape. rval.resultCode = BLECommOperationResult.RESULT_NONE; - LOG.error("BT Device not supported"); + aapsLogger.error(LTag.PUMPBTCOMM, "BT Device not supported"); // TODO: 11/07/2016 UI update for user } else { BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID) @@ -516,21 +510,21 @@ public class RileyLinkBLE { gattOperationSema.release(); } } else { - LOG.error("writeCharacteristic_blocking: not configured!"); + aapsLogger.error(LTag.PUMPBTCOMM, "writeCharacteristic_blocking: not configured!"); rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED; } return rval; } - public BLECommOperationResult readCharacteristic_blocking(UUID serviceUUID, UUID charaUUID) { + BLECommOperationResult readCharacteristic_blocking(UUID serviceUUID, UUID charaUUID) { BLECommOperationResult rval = new BLECommOperationResult(); if (bluetoothConnectionGatt != null) { try { gattOperationSema.acquire(); SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow } catch (InterruptedException e) { - LOG.error("readCharacteristic_blocking: Interrupted waiting for gattOperationSema"); + aapsLogger.error(LTag.PUMPBTCOMM, "readCharacteristic_blocking: Interrupted waiting for gattOperationSema"); return rval; } if (mCurrentOperation != null) { @@ -539,7 +533,7 @@ public class RileyLinkBLE { if (bluetoothConnectionGatt.getService(serviceUUID) == null) { // Catch if the service is not supported by the BLE device rval.resultCode = BLECommOperationResult.RESULT_NONE; - LOG.error("BT Device not supported"); + aapsLogger.error(LTag.PUMPBTCOMM, "BT Device not supported"); // TODO: 11/07/2016 UI update for user } else { BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID).getCharacteristic( @@ -559,7 +553,7 @@ public class RileyLinkBLE { mCurrentOperation = null; gattOperationSema.release(); } else { - LOG.error("readCharacteristic_blocking: not configured!"); + aapsLogger.error(LTag.PUMPBTCOMM, "readCharacteristic_blocking: not configured!"); rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED; } return rval; @@ -582,9 +576,4 @@ 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/RFSpyResponse.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RFSpyResponse.java index cf5362427c..a766e92266 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RFSpyResponse.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/RFSpyResponse.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.RileyLinkCommand; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RFSpyRLResponse; @@ -48,12 +49,12 @@ public class RFSpyResponse { } - public RadioResponse getRadioResponse() throws RileyLinkCommunicationException { + public RadioResponse getRadioResponse(HasAndroidInjector injector) throws RileyLinkCommunicationException { if (looksLikeRadioPacket()) { - radioResponse = new RadioResponse(command); + radioResponse = new RadioResponse(injector, command); radioResponse.init(raw); } else { - radioResponse = new RadioResponse(); + radioResponse = new RadioResponse(injector); } return radioResponse; } 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 3caf7872c0..343e32da67 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 @@ -1,16 +1,19 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data; import org.apache.commons.lang3.NotImplementedException; -import org.slf4j.Logger; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; 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; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkCommandType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.CRC; @@ -19,26 +22,24 @@ import info.nightscout.androidaps.plugins.pump.common.utils.CRC; */ public class RadioResponse { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); - public boolean decodedOK = false; + @Inject AAPSLogger aapsLogger; + @Inject RileyLinkServiceData rileyLinkServiceData; + + private boolean decodedOK = false; public int rssi; - public int responseNumber; - public byte[] decodedPayload = new byte[0]; - public byte receivedCRC; + private int responseNumber; + private byte[] decodedPayload = new byte[0]; + private byte receivedCRC; private RileyLinkCommand command; - public RadioResponse() { - + public RadioResponse(HasAndroidInjector injector) { + injector.androidInjector().inject(this); } - - // public RadioResponse(byte[] rxData) { - // init(rxData); - // } - - public RadioResponse(RileyLinkCommand command /* , byte[] raw */) { + public RadioResponse(HasAndroidInjector injector, RileyLinkCommand command /* , byte[] raw */) { + this(injector); this.command = command; // init(raw); } @@ -74,7 +75,7 @@ public class RadioResponse { } byte[] encodedPayload; - if (RileyLinkFirmwareVersion.isSameVersion(RileyLinkUtil.getInstance().getRileyLinkServiceData().versionCC110, + if (RileyLinkFirmwareVersion.isSameVersion(rileyLinkServiceData.versionCC110, RileyLinkFirmwareVersion.Version2)) { encodedPayload = ByteUtil.substring(rxData, 3, rxData.length - 3); rssi = rxData[1]; @@ -116,7 +117,7 @@ public class RadioResponse { receivedCRC = decodeThis[decodeThis.length - 1]; byte calculatedCRC = CRC.crc8(decodedPayload); if (receivedCRC != calculatedCRC) { - LOG.error(String.format("RadioResponse: CRC mismatch, calculated 0x%02x, received 0x%02x", + aapsLogger.error(LTag.PUMPCOMM, String.format("RadioResponse: CRC mismatch, calculated 0x%02x, received 0x%02x", calculatedCRC, receivedCRC)); } } else { @@ -131,7 +132,7 @@ public class RadioResponse { } } catch (NumberFormatException e) { decodedOK = false; - LOG.error("Failed to decode radio data: " + ByteUtil.shortHexString(encodedPayload)); + aapsLogger.error(LTag.PUMPBTCOMM, "Failed to decode radio data: " + ByteUtil.shortHexString(encodedPayload)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java index 09af88b437..4fc0069194 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java @@ -27,12 +27,12 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { @Inject ResourceHelper resourceHelper; @Inject RileyLinkUtil rileyLinkUtil; + @Inject RileyLinkServiceData rileyLinkServiceData; TextView connectionStatus; TextView configuredAddress; TextView connectedDevice; TextView connectionError; - RileyLinkServiceData rileyLinkServiceData; private SectionsPagerAdapter mSectionsPagerAdapter; private FloatingActionButton floatingActionButton; @@ -77,8 +77,6 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { this.connectedDevice = findViewById(R.id.rls_t1_connected_device); this.connectionError = findViewById(R.id.rls_t1_connection_error); - rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData(); - // // 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}; @@ -98,7 +96,7 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { public void refreshData(int position) { if (position == 0) { // FIXME i18n - this.connectionStatus.setText(rileyLinkServiceData.serviceState.name()); + this.connectionStatus.setText(rileyLinkServiceData.rileyLinkServiceState.name()); this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress); // FIXME this.connectedDevice.setText("???"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index 4365c52757..ccf5bd0bcb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java @@ -17,7 +17,6 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; @@ -37,6 +36,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re @Inject MedtronicPumpStatus medtronicPumpStatus; @Inject ResourceHelper resourceHelper; @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject RileyLinkServiceData rileyLinkServiceData; TextView connectionStatus; TextView configuredAddress; @@ -50,8 +50,6 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re TextView lastDeviceContact; TextView firmwareVersion; - RileyLinkServiceData rileyLinkServiceData; - boolean first = false; @@ -66,7 +64,6 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re @Override public void onStart() { super.onStart(); - rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData(); this.connectionStatus = getActivity().findViewById(R.id.rls_t1_connection_status); this.configuredAddress = getActivity().findViewById(R.id.rls_t1_configured_address); @@ -101,12 +98,9 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re public void refreshData() { - RileyLinkTargetDevice targetDevice = rileyLinkUtil.getTargetDevice(); + RileyLinkTargetDevice targetDevice = rileyLinkServiceData.targetDevice; - if (rileyLinkUtil.getServiceState() == null) - this.connectionStatus.setText(resourceHelper.gs(RileyLinkServiceState.NotStarted.getResourceId(targetDevice))); - else - this.connectionStatus.setText(resourceHelper.gs(rileyLinkUtil.getServiceState().getResourceId(targetDevice))); + this.connectionStatus.setText(resourceHelper.gs(rileyLinkServiceData.rileyLinkServiceState.getResourceId(targetDevice))); if (rileyLinkServiceData != null) { this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress); 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 2af0eccfdb..6dd29285f1 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 @@ -46,18 +46,16 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { @Inject HasAndroidInjector injector; @Inject RileyLinkUtil rileyLinkUtil; @Inject SP sp; + @Inject RileyLinkServiceData rileyLinkServiceData; private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); RileyLinkService serviceInstance; protected Map> broadcastIdentifiers = null; String deviceSpecificPrefix; - Context context; - - public RileyLinkBroadcastReceiver(RileyLinkService serviceInstance, Context context) { + public RileyLinkBroadcastReceiver(RileyLinkService serviceInstance) { this.serviceInstance = serviceInstance; - this.context = context; createBroadcastIdentifiers(); } @@ -120,7 +118,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } - public void registerBroadcasts() { + public void registerBroadcasts(Context context) { IntentFilter intentFilter = new IntentFilter(); @@ -143,9 +141,9 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnected)) { if (BluetoothAdapter.getDefaultAdapter().isEnabled()) { - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable); + rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable); } else { - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); + rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); } return true; @@ -155,25 +153,22 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { LOG.warn("MedtronicConst.Intents.RileyLinkReady"); // sendIPCNotification(RT2Const.IPC.MSG_note_WakingPump); - if (this.serviceInstance.rileyLinkBLE == null) - return false; + serviceInstance.rileyLinkBLE.enableNotifications(); + serviceInstance.rfspy.startReader(); // call startReader from outside? - this.serviceInstance.rileyLinkBLE.enableNotifications(); - this.serviceInstance.rfspy.startReader(); // call startReader from outside? - - this.serviceInstance.rfspy.initializeRileyLink(); - String bleVersion = this.serviceInstance.rfspy.getBLEVersionCached(); - RileyLinkFirmwareVersion rlVersion = this.serviceInstance.rfspy.getRLVersionCached(); + serviceInstance.rfspy.initializeRileyLink(); + String bleVersion = serviceInstance.rfspy.getBLEVersionCached(); + RileyLinkFirmwareVersion rlVersion = serviceInstance.rfspy.getRLVersionCached(); // if (isLoggingEnabled()) LOG.debug("RfSpy version (BLE113): " + bleVersion); - this.serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion; + serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion; // if (isLoggingEnabled()) LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); - this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; + serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; - ServiceTask task = new InitializePumpManagerTask(injector, rileyLinkUtil.getTargetDevice()); + ServiceTask task = new InitializePumpManagerTask(injector); ServiceTaskExecutor.startTask(task); if (isLoggingEnabled()) LOG.info("Announcing RileyLink open For business"); @@ -186,13 +181,13 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } else { // showBusy("Configuring Service", 50); // rileyLinkBLE.findRileyLink(RileylinkBLEAddress); - this.serviceInstance.reconfigureRileyLink(RileylinkBLEAddress); + serviceInstance.reconfigureRileyLink(RileylinkBLEAddress); // MainApp.getServiceClientConnection().setThisRileylink(RileylinkBLEAddress); } return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnect)) { - this.serviceInstance.disconnectRileyLink(); + serviceInstance.disconnectRileyLink(); return true; } else { @@ -247,7 +242,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } if (action.startsWith(this.deviceSpecificPrefix)) { - return this.serviceInstance.handleDeviceSpecificBroadcasts(intent); + return serviceInstance.handleDeviceSpecificBroadcasts(intent); } else return false; } @@ -262,7 +257,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { return (L.isEnabled(L.PUMPCOMM)); } - public void unregisterBroadcasts() { + public void unregisterBroadcasts(Context context) { LocalBroadcastManager.getInstance(context).unregisterReceiver(this); } } 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 282595a193..371a74b576 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 @@ -12,6 +12,7 @@ import javax.inject.Inject; import dagger.android.DaggerService; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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; @@ -36,17 +37,18 @@ public abstract class RileyLinkService extends DaggerService { @Inject protected AAPSLogger aapsLogger; @Inject protected SP sp; @Inject protected Context context; + @Inject protected RxBusWrapper rxBus; @Inject protected RileyLinkUtil rileyLinkUtil; @Inject protected MedtronicUtil medtronicUtil; // TODO should be avoided here as it's MDT - + @Inject protected RileyLinkServiceData rileyLinkServiceData; @NotNull protected RileyLinkBLE rileyLinkBLE; // android-bluetooth management, must be set in initRileyLinkServiceData protected BluetoothAdapter bluetoothAdapter; protected RFSpy rfspy; // interface for RL xxx Mhz radio. protected RileyLinkBroadcastReceiver mBroadcastReceiver; - protected RileyLinkServiceData rileyLinkServiceData; protected RileyLinkBluetoothStateReceiver bluetoothStateReceiver; + @Override public void onCreate() { super.onCreate(); @@ -54,8 +56,8 @@ public abstract class RileyLinkService extends DaggerService { rileyLinkUtil.setEncoding(getEncoding()); initRileyLinkServiceData(); - mBroadcastReceiver = new RileyLinkBroadcastReceiver(this, this.context); - mBroadcastReceiver.registerBroadcasts(); + mBroadcastReceiver = new RileyLinkBroadcastReceiver(this); + mBroadcastReceiver.registerBroadcasts(this); bluetoothStateReceiver = new RileyLinkBluetoothStateReceiver(); @@ -96,7 +98,7 @@ public abstract class RileyLinkService extends DaggerService { rileyLinkBLE.disconnect(); // dispose of Gatt (disconnect and close) if (mBroadcastReceiver != null) { - mBroadcastReceiver.unregisterBroadcasts(); + mBroadcastReceiver.unregisterBroadcasts(this); } if (bluetoothStateReceiver != null) { @@ -133,20 +135,20 @@ public abstract class RileyLinkService extends DaggerService { public boolean bluetoothInit() { aapsLogger.debug(LTag.PUMPCOMM, "bluetoothInit: attempting to get an adapter"); - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.BluetoothInitializing); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { aapsLogger.error("Unable to obtain a BluetoothAdapter."); - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter); + rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter); } else { if (!bluetoothAdapter.isEnabled()) { aapsLogger.error("Bluetooth is not enabled."); - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); + rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); } else { - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.BluetoothReady); return true; } } @@ -158,7 +160,7 @@ public abstract class RileyLinkService extends DaggerService { // returns true if our Rileylink configuration changed public boolean reconfigureRileyLink(String deviceAddress) { - rileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkInitializing); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkInitializing); if (rileyLinkBLE.isConnected()) { if (deviceAddress.equals(rileyLinkServiceData.rileylinkAddress)) { @@ -179,7 +181,7 @@ public abstract class RileyLinkService extends DaggerService { } else { aapsLogger.debug(LTag.PUMPCOMM, "Using RL " + deviceAddress); - if (rileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) { + if (rileyLinkServiceData.getRileyLinkServiceState() == RileyLinkServiceState.NotStarted) { if (!bluetoothInit()) { aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. {}", getError() != null ? getError().name() : "Unknown error (null)"); @@ -201,7 +203,7 @@ public abstract class RileyLinkService extends DaggerService { // FIXME: This needs to be run in a session so that is interruptable, has a separate thread, etc. public void doTuneUpDevice() { - rileyLinkUtil.setServiceState(RileyLinkServiceState.TuneUpDevice); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.TuneUpDevice); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); double lastGoodFrequency = 0.0d; @@ -226,10 +228,10 @@ public abstract class RileyLinkService extends DaggerService { if (newFrequency == 0.0d) { // error tuning pump, pump not present ?? - rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed); + rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed); } else { getDeviceCommunicationManager().clearNotConnectedCount(); - rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.PumpConnectorReady); } } @@ -241,7 +243,7 @@ public abstract class RileyLinkService extends DaggerService { rileyLinkServiceData.rileylinkAddress = null; } - rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.BluetoothReady); } @NotNull public RileyLinkBLE getRileyLinkBLE() { 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 dd66255da4..9a2779806d 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 @@ -1,21 +1,35 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service; +import javax.inject.Inject; +import javax.inject.Singleton; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; +import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; /** * Created by andy on 16/05/2018. */ +@Singleton public class RileyLinkServiceData { - public boolean tuneUpDone = false; + @Inject AAPSLogger aapsLogger; + @Inject RileyLinkUtil rileyLinkUtil; + @Inject RxBusWrapper rxBus; + + boolean tuneUpDone = false; public RileyLinkError errorCode; - public RileyLinkServiceState serviceState = RileyLinkServiceState.NotStarted; + public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; public String rileylinkAddress; - public long lastTuneUpTime = 0L; + long lastTuneUpTime = 0L; public Double lastGoodFrequency; // bt version @@ -29,15 +43,45 @@ public class RileyLinkServiceData { public String pumpID; public byte[] pumpIDBytes; - - public RileyLinkServiceData(RileyLinkTargetDevice targetDevice) { - this.targetDevice = targetDevice; - } - + @Inject + public RileyLinkServiceData() {} public void setPumpID(String pumpId, byte[] pumpIdBytes) { this.pumpID = pumpId; this.pumpIDBytes = pumpIdBytes; } + public void setRileyLinkServiceState(RileyLinkServiceState newState) { + setServiceState(newState, null); + } + + public RileyLinkServiceState getRileyLinkServiceState() { + return workWithServiceState(null, null, false); + } + + + public void setServiceState(RileyLinkServiceState newState, RileyLinkError errorCode) { + workWithServiceState(newState, errorCode, true); + } + + + private synchronized RileyLinkServiceState workWithServiceState(RileyLinkServiceState newState, RileyLinkError errorCode, boolean set) { + + if (set) { + + rileyLinkServiceState = newState; + this.errorCode = errorCode; + + aapsLogger.info(LTag.PUMP, "RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " + errorCode.name()); + + rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(rileyLinkServiceState, errorCode, targetDevice)); + rxBus.send(new EventMedtronicDeviceStatusChange(newState, errorCode)); + return null; + + } else { + return rileyLinkServiceState; + } + + } + } 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 64f7c8343b..4f79eb0561 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 @@ -1,22 +1,20 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; -import org.slf4j.Logger; - import javax.inject.Inject; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; 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; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by geoff on 7/9/16. @@ -25,66 +23,62 @@ import info.nightscout.androidaps.utils.SP; */ public class InitializePumpManagerTask extends ServiceTask { + @Inject AAPSLogger aapsLogger; @Inject ActivePluginProvider activePlugin; + @Inject SP sp; + @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject RileyLinkUtil rileyLinkUtil; - private static final String TAG = "InitPumpManagerTask"; - private RileyLinkTargetDevice targetDevice; - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - - public InitializePumpManagerTask(HasAndroidInjector injector, RileyLinkTargetDevice targetDevice) { + public InitializePumpManagerTask(HasAndroidInjector injector) { super(injector); - this.targetDevice = targetDevice; } - public InitializePumpManagerTask(HasAndroidInjector injector, ServiceTransport transport) { super(injector, transport); } - @Override public void run() { - double lastGoodFrequency = 0.0d; + double lastGoodFrequency; - if (RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency == null) { + if (rileyLinkServiceData.lastGoodFrequency == null) { - lastGoodFrequency = SP.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0d); + lastGoodFrequency = sp.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0d); lastGoodFrequency = Math.round(lastGoodFrequency * 1000d) / 1000d; - RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency = lastGoodFrequency; + rileyLinkServiceData.lastGoodFrequency = lastGoodFrequency; // if (RileyLinkUtil.getRileyLinkTargetFrequency() == null) { // String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null); // } } else { - lastGoodFrequency = RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency; + lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency; } - RileyLinkCommunicationManager rileyLinkCommunicationManager = ((PumpPluginAbstract)activePlugin.getActivePump()).getRileyLinkService().getDeviceCommunicationManager(); + RileyLinkCommunicationManager rileyLinkCommunicationManager = ((PumpPluginAbstract) activePlugin.getActivePump()).getRileyLinkService().getDeviceCommunicationManager(); if ((lastGoodFrequency > 0.0d) && rileyLinkCommunicationManager.isValidFrequency(lastGoodFrequency)) { - RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.RileyLinkReady); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady); - if (L.isEnabled(L.PUMPCOMM)) - LOG.info("Setting radio frequency to {} MHz", lastGoodFrequency); + aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to {} MHz", lastGoodFrequency); rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency); boolean foundThePump = rileyLinkCommunicationManager.tryToConnectToDevice(); if (foundThePump) { - RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorReady); + rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.PumpConnectorReady); } else { - RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorError, + rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.NoContactWithDevice); - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); } } else { - RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java index 178c5185f1..7fff8e225a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTask.java @@ -8,7 +8,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data. */ public class ServiceTask implements Runnable { - private static final String TAG = "ServiceTask(base)"; public boolean completed = false; protected ServiceTransport mTransport; protected HasAndroidInjector injector; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index b4e2a0739e..947691a528 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -23,6 +23,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState @@ -60,6 +61,7 @@ class MedtronicFragment : DaggerFragment() { @Inject lateinit var rileyLinkUtil: RileyLinkUtil @Inject lateinit var medtronicUtil: MedtronicUtil @Inject lateinit var medtronicPumpStatus: MedtronicPumpStatus + @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData private var disposable: CompositeDisposable = CompositeDisposable() @@ -174,17 +176,14 @@ class MedtronicFragment : DaggerFragment() { @Synchronized private fun setDeviceStatus() { - medtronicPumpStatus.rileyLinkServiceState = checkStatusSet(medtronicPumpStatus.rileyLinkServiceState, - rileyLinkUtil.getServiceState()) as RileyLinkServiceState? - - val resourceId = medtronicPumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) + val resourceId = rileyLinkServiceData.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) val rileyLinkError = medtronicPumpPlugin.rileyLinkService?.error medtronic_rl_status.text = when { - medtronicPumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) - medtronicPumpStatus.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) - medtronicPumpStatus.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) - medtronicPumpStatus.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) + rileyLinkServiceData.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) } medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) 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 baa03a3ef1..56c5c272d8 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 @@ -56,6 +56,7 @@ 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.defs.RileyLinkServiceState; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ResetRileyLinkConfigurationTask; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; @@ -99,6 +100,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final MedtronicUtil medtronicUtil; private final MedtronicPumpStatus medtronicPumpStatus; private final MedtronicHistoryData medtronicHistoryData; + private final RileyLinkServiceData rileyLinkServiceData; protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService rileyLinkMedtronicService; @@ -129,7 +131,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter RileyLinkUtil rileyLinkUtil, MedtronicUtil medtronicUtil, MedtronicPumpStatus medtronicPumpStatus, - MedtronicHistoryData medtronicHistoryData + MedtronicHistoryData medtronicHistoryData, + RileyLinkServiceData rileyLinkServiceData ) { super(new PluginDescription() // @@ -149,6 +152,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.sp = sp; this.medtronicPumpStatus = medtronicPumpStatus; this.medtronicHistoryData = medtronicHistoryData; + this.rileyLinkServiceData = rileyLinkServiceData; displayConnectionMessages = false; @@ -408,7 +412,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private boolean isPumpNotReachable() { - RileyLinkServiceState rileyLinkServiceState = rileyLinkUtil.getServiceState(); + RileyLinkServiceState rileyLinkServiceState = rileyLinkServiceData.rileyLinkServiceState; if (rileyLinkServiceState == null) { aapsLogger.debug(LTag.PUMP, "RileyLink unreachable. RileyLinkServiceState is null."); 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 c2fb02dee0..f0888b84a0 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 @@ -24,6 +24,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMe import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; @@ -66,6 +67,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager @Inject MedtronicConverter medtronicConverter; @Inject MedtronicUtil medtronicUtil; @Inject MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder; + @Inject RileyLinkServiceData rileyLinkServiceData; private final int MAX_COMMAND_TRIES = 3; private final int DEFAULT_TIMEOUT = 2000; @@ -154,7 +156,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (rfSpyResponse.wasTimeout()) { aapsLogger.error(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to find pump (timeout)."); } else if (rfSpyResponse.looksLikeRadioPacket()) { - RadioResponse radioResponse = new RadioResponse(); + RadioResponse radioResponse = new RadioResponse(injector); try { @@ -470,11 +472,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public byte[] createPumpMessageContent(RLMessageType type) { switch (type) { case PowerOn: - return medtronicUtil.buildCommandPayload(MedtronicCommandType.RFPowerOn, // + return medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.RFPowerOn, // new byte[]{2, 1, (byte) receiverDeviceAwakeForMinutes}); // maybe this is better FIXME case ReadSimpleData: - return medtronicUtil.buildCommandPayload(MedtronicCommandType.PumpModel, null); + return medtronicUtil.buildCommandPayload(rileyLinkServiceData, MedtronicCommandType.PumpModel, null); } return new byte[0]; } 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 e722e44818..a6e154cf1f 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 @@ -14,7 +14,6 @@ import javax.inject.Singleton; 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.defs.RileyLinkError; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; @@ -40,7 +39,6 @@ public class MedtronicPumpStatus extends PumpStatus { public Double maxBasal; // statuses - public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; public RileyLinkError rileyLinkError; public PumpDeviceState pumpDeviceState = PumpDeviceState.NeverContacted; public MedtronicDeviceType medtronicDeviceType = null; 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 de6395d908..d29bebb7b1 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 @@ -20,7 +20,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager; @@ -46,7 +45,6 @@ public class RileyLinkMedtronicService extends RileyLinkService { @Inject MedtronicUIPostprocessor medtronicUIPostprocessor; @Inject MedtronicPumpStatus medtronicPumpStatus; - private MedtronicUIComm medtronicUIComm; private MedtronicCommunicationManager medtronicCommunicationManager; private IBinder mBinder = new LocalBinder(); @@ -94,17 +92,14 @@ public class RileyLinkMedtronicService extends RileyLinkService { frequencies[0] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca); frequencies[1] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_worldwide); - rileyLinkServiceData = new RileyLinkServiceData(RileyLinkTargetDevice.MedtronicPump); - - rileyLinkUtil.setRileyLinkServiceData(rileyLinkServiceData); - rileyLinkUtil.setTargetDevice(RileyLinkTargetDevice.MedtronicPump); + rileyLinkServiceData.targetDevice = RileyLinkTargetDevice.MedtronicPump; setPumpIDString(sp.getString(MedtronicConst.Prefs.PumpSerial, "000000")); // get most recently used RileyLink address rileyLinkServiceData.rileylinkAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); - rileyLinkBLE = new RileyLinkBLE(this.context); // or this + rileyLinkBLE = new RileyLinkBLE(injector, this); // or this rfspy = new RFSpy(rileyLinkBLE); rfspy.startReader(); @@ -185,7 +180,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { // PumpInterface - REMOVE public boolean isInitialized() { - return RileyLinkServiceState.isReady(rileyLinkUtil.getRileyLinkServiceData().serviceState); + return RileyLinkServiceState.isReady(rileyLinkServiceData.rileyLinkServiceState); } 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 5ea62acdb2..dabf8ff0a8 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 @@ -23,6 +23,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO; @@ -55,17 +56,19 @@ public class MedtronicUtil { private final AAPSLogger aapsLogger; private final RxBusWrapper rxBus; private final RileyLinkUtil rileyLinkUtil; + private final RileyLinkServiceData rileyLinkServiceData; @Inject public MedtronicUtil( AAPSLogger aapsLogger, RxBusWrapper rxBus, - RileyLinkUtil rileyLinkUtil - + RileyLinkUtil rileyLinkUtil, + RileyLinkServiceData rileyLinkServiceData ) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil; + this.rileyLinkServiceData = rileyLinkServiceData; } public LocalTime getTimeFrom30MinInterval(int interval) { @@ -241,12 +244,12 @@ public class MedtronicUtil { // } - public byte[] buildCommandPayload(MedtronicCommandType commandType, byte[] parameters) { - return buildCommandPayload((byte) commandType.commandCode, parameters); + public byte[] buildCommandPayload(RileyLinkServiceData rileyLinkServiceData, MedtronicCommandType commandType, byte[] parameters) { + return buildCommandPayload(rileyLinkServiceData, (byte) commandType.commandCode, parameters); } - public byte[] buildCommandPayload(byte commandType, byte[] parameters) { + public byte[] buildCommandPayload(RileyLinkServiceData rileyLinkServiceData, byte commandType, byte[] parameters) { // A7 31 65 51 C0 00 52 byte commandLength = (byte) (parameters == null ? 2 : 2 + parameters.length); @@ -254,7 +257,7 @@ public class MedtronicUtil { ByteBuffer sendPayloadBuffer = ByteBuffer.allocate(ENVELOPE_SIZE + commandLength); // + CRC_SIZE sendPayloadBuffer.order(ByteOrder.BIG_ENDIAN); - byte[] serialNumberBCD = rileyLinkUtil.getRileyLinkServiceData().pumpIDBytes; + byte[] serialNumberBCD = rileyLinkServiceData.pumpIDBytes; sendPayloadBuffer.put((byte) 0xA7); sendPayloadBuffer.put(serialNumberBCD[0]); @@ -398,7 +401,7 @@ public class MedtronicUtil { public void setPumpDeviceState(PumpDeviceState pumpDeviceState) { this.pumpDeviceState = pumpDeviceState; - rileyLinkUtil.historyRileyLink.add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.MedtronicPump)); + rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.MedtronicPump)); rxBus.send(new EventMedtronicDeviceStatusChange(pumpDeviceState)); } @@ -426,7 +429,7 @@ public class MedtronicUtil { this.currentCommand = currentCommand; if (currentCommand != null) - rileyLinkUtil.historyRileyLink.add(new RLHistoryItem(currentCommand)); + rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(currentCommand)); } From e21b1e4d3dfb2cf62c69bd4d64be4523452ab2c6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 18:44:41 +0200 Subject: [PATCH 13/23] MDT refactor pass 12 --- .../RileyLinkCommunicationManager.java | 5 +-- .../dialog/RileyLinkStatusActivity.java | 2 +- .../RileyLinkStatusGeneralFragment.java | 4 +-- .../rileylink/service/RileyLinkService.java | 6 ++-- .../service/RileyLinkServiceData.java | 4 +-- .../pump/medtronic/MedtronicFragment.kt | 19 +---------- .../comm/MedtronicCommunicationManager.java | 34 +++++++++---------- .../dialog/MedtronicHistoryActivity.java | 2 -- .../medtronic/driver/MedtronicPumpStatus.java | 30 +++++++++++++--- .../service/RileyLinkMedtronicService.java | 2 +- .../pump/medtronic/util/MedtronicUtil.java | 29 +++------------- 11 files changed, 60 insertions(+), 77 deletions(-) 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 e96ab06f27..375ead3c4a 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 @@ -16,13 +16,11 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Radi import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; -import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.sharedPreferences.SP; /** @@ -37,7 +35,6 @@ public abstract class RileyLinkCommunicationManager { @Inject MedtronicPumpStatus medtronicPumpStatus; @Inject RileyLinkUtil rileyLinkUtil; - @Inject MedtronicUtil medtronicUtil; private final int SCAN_TIMEOUT = 1500; @@ -151,7 +148,7 @@ public abstract class RileyLinkCommunicationManager { // **** FIXME: this wakeup doesn't seem to work well... must revisit // receiverDeviceAwakeForMinutes = duration_minutes; - medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.WakingUp); if (force) nextWakeUpRequired = 0L; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java index 4fc0069194..57aa01123f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java @@ -101,7 +101,7 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { // FIXME this.connectedDevice.setText("???"); // FIXME i18n - this.connectionError.setText(rileyLinkServiceData.errorCode.name()); + this.connectionError.setText(rileyLinkServiceData.rileyLinkError.name()); } else { } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index ccf5bd0bcb..34833f707e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java @@ -104,9 +104,9 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re if (rileyLinkServiceData != null) { this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress); - this.connectionError.setText(rileyLinkServiceData.errorCode == null ? // + this.connectionError.setText(rileyLinkServiceData.rileyLinkError == null ? // "-" - : resourceHelper.gs(rileyLinkServiceData.errorCode.getResourceId(targetDevice))); + : resourceHelper.gs(rileyLinkServiceData.rileyLinkError.getResourceId(targetDevice))); RileyLinkFirmwareVersion firmwareVersion = rileyLinkServiceData.versionCC110; 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 371a74b576..414bc6177b 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 @@ -25,6 +25,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceResult; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -41,6 +42,7 @@ public abstract class RileyLinkService extends DaggerService { @Inject protected RileyLinkUtil rileyLinkUtil; @Inject protected MedtronicUtil medtronicUtil; // TODO should be avoided here as it's MDT @Inject protected RileyLinkServiceData rileyLinkServiceData; + @Inject protected MedtronicPumpStatus medtronicPumpStatus; @NotNull protected RileyLinkBLE rileyLinkBLE; // android-bluetooth management, must be set in initRileyLinkServiceData protected BluetoothAdapter bluetoothAdapter; @@ -204,7 +206,7 @@ public abstract class RileyLinkService extends DaggerService { public void doTuneUpDevice() { rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.TuneUpDevice); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); double lastGoodFrequency = 0.0d; @@ -266,7 +268,7 @@ public abstract class RileyLinkService extends DaggerService { public RileyLinkError getError() { if (rileyLinkServiceData != null) - return rileyLinkServiceData.errorCode; + return rileyLinkServiceData.rileyLinkError; else return null; } 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 9a2779806d..894bbe7706 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 @@ -26,7 +26,7 @@ public class RileyLinkServiceData { @Inject RxBusWrapper rxBus; boolean tuneUpDone = false; - public RileyLinkError errorCode; + public RileyLinkError rileyLinkError; public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; public String rileylinkAddress; long lastTuneUpTime = 0L; @@ -70,7 +70,7 @@ public class RileyLinkServiceData { if (set) { rileyLinkServiceState = newState; - this.errorCode = errorCode; + this.rileyLinkError = errorCode; aapsLogger.info(LTag.PUMP, "RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " + errorCode.name()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 947691a528..da9a2321f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -19,7 +19,6 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity @@ -188,16 +187,11 @@ class MedtronicFragment : DaggerFragment() { } medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) - medtronicPumpStatus.rileyLinkError = checkStatusSet(medtronicPumpStatus.rileyLinkError, medtronicPumpPlugin.rileyLinkService?.error) as RileyLinkError? - medtronic_errors.text = - medtronicPumpStatus.rileyLinkError?.let { + rileyLinkServiceData.rileyLinkError?.let { resourceHelper.gs(it.getResourceId(RileyLinkTargetDevice.MedtronicPump)) } ?: "-" - medtronicPumpStatus.pumpDeviceState = checkStatusSet(medtronicPumpStatus.pumpDeviceState, - medtronicUtil.pumpDeviceState) as PumpDeviceState? - when (medtronicPumpStatus.pumpDeviceState) { null, PumpDeviceState.Sleeping -> medtronic_pump_status.text = "{fa-bed} " // + pumpStatus.pumpDeviceState.name()); @@ -239,17 +233,6 @@ class MedtronicFragment : DaggerFragment() { } } - private fun checkStatusSet(object1: Any?, object2: Any?): Any? { - return if (object1 == null) { - object2 - } else { - if (object1 != object2) { - object2 - } else - object1 - } - } - private fun displayNotConfiguredDialog() { context?.let { OKDialog.show(it, resourceHelper.gs(R.string.combo_warning), 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 f0888b84a0..fb33bc5fa9 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 @@ -110,10 +110,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager */ public boolean isDeviceReachable(boolean canPreventTuneUp) { - PumpDeviceState state = medtronicUtil.getPumpDeviceState(); + PumpDeviceState state = medtronicPumpStatus.getPumpDeviceState(); if (state != PumpDeviceState.PumpUnreachable) - medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.WakingUp); for (int retry = 0; retry < 5; retry++) { @@ -129,7 +129,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } if (state != PumpDeviceState.PumpUnreachable) - medtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.PumpUnreachable); if (!canPreventTuneUp) { @@ -146,7 +146,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private boolean connectToDevice() { - PumpDeviceState state = medtronicUtil.getPumpDeviceState(); + PumpDeviceState state = medtronicPumpStatus.getPumpDeviceState(); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, @@ -187,9 +187,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (valid) { if (state == PumpDeviceState.PumpUnreachable) - medtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.WakingUp); else - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); rememberLastGoodDeviceCommunicationTime(); @@ -197,7 +197,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } else { if (state != PumpDeviceState.PumpUnreachable) - medtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.PumpUnreachable); } } @@ -312,7 +312,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + medtronicUtil.getCurrentCommand()); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Active); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Active); boolean doneWithError = false; for (int pageNumber = 0; pageNumber < 5; pageNumber++) { @@ -344,7 +344,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } if (failed) { - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; } @@ -435,7 +435,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } if (doneWithError) { - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; } @@ -450,13 +450,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); if (pumpTotalResult.isSearchFinished()) { - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; } } - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return pumpTotalResult; @@ -520,7 +520,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Active); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Active); // create message PumpMessage msg; @@ -533,7 +533,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager // send and wait for response PumpMessage response = sendAndListen(msg, timeoutMs); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return response; } @@ -655,7 +655,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager medtronicUtil.setCurrentCommand(commandType); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Active); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Active); for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { @@ -712,7 +712,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); medtronicUtil.setCurrentCommand(null); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return basalProfile; } @@ -724,7 +724,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading profile in max retries."); medtronicUtil.setCurrentCommand(null); - medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); return null; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java index 50eebb6813..cb3aad5f94 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java @@ -21,14 +21,12 @@ import javax.inject.Inject; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; public class MedtronicHistoryActivity extends NoSplashAppCompatActivity { - @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicHistoryData medtronicHistoryData; Spinner historyTypeSpinner; 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 a6e154cf1f..02f08e93d7 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 @@ -11,13 +11,17 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; 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.defs.RileyLinkError; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -31,6 +35,8 @@ public class MedtronicPumpStatus extends PumpStatus { private final ResourceHelper resourceHelper; private final SP sp; + private final RileyLinkUtil rileyLinkUtil; + private final RxBusWrapper rxBus; public String errorDescription = null; public String serialNumber; @@ -39,8 +45,7 @@ public class MedtronicPumpStatus extends PumpStatus { public Double maxBasal; // statuses - public RileyLinkError rileyLinkError; - public PumpDeviceState pumpDeviceState = PumpDeviceState.NeverContacted; + private PumpDeviceState pumpDeviceState = PumpDeviceState.NeverContacted; public MedtronicDeviceType medtronicDeviceType = null; public Date tempBasalStart; public Double tempBasalAmount = 0.0d; @@ -57,11 +62,15 @@ public class MedtronicPumpStatus extends PumpStatus { @Inject public MedtronicPumpStatus( ResourceHelper resourceHelper, - SP sp + SP sp, + RxBusWrapper rxBus, + RileyLinkUtil rileyLinkUtil ) { super(); this.resourceHelper = resourceHelper; this.sp = sp; + this.rxBus = rxBus; + this.rileyLinkUtil = rileyLinkUtil; initSettings(); } @@ -155,4 +164,17 @@ public class MedtronicPumpStatus extends PumpStatus { public String getErrorInfo() { return (errorDescription == null) ? "-" : errorDescription; } + + public PumpDeviceState getPumpDeviceState() { + return pumpDeviceState; + } + + + public void setPumpDeviceState(PumpDeviceState pumpDeviceState) { + this.pumpDeviceState = pumpDeviceState; + + rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.MedtronicPump)); + + rxBus.send(new EventMedtronicDeviceStatusChange(pumpDeviceState)); + } } 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 d29bebb7b1..8a3702401e 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 @@ -162,7 +162,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { return; } - medtronicUtil.setPumpDeviceState(PumpDeviceState.InvalidConfiguration); + medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.InvalidConfiguration); // LOG.info("setPumpIDString: saved pumpID " + idString); } 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 dabf8ff0a8..e649ee1286 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 @@ -22,7 +22,6 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO; @@ -30,7 +29,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.PumpSettingDTO import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType; -import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -43,7 +42,6 @@ public class MedtronicUtil { private int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS] private static boolean lowLevelDebug = true; - private PumpDeviceState pumpDeviceState; private MedtronicDeviceType medtronicPumpModel; private MedtronicCommandType currentCommand; private Map settings; @@ -51,24 +49,23 @@ public class MedtronicUtil { private int doneBit = 1 << 7; private ClockDTO pumpTime; public Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); - public Gson gsonInstanceCore = new GsonBuilder().create(); private final AAPSLogger aapsLogger; private final RxBusWrapper rxBus; private final RileyLinkUtil rileyLinkUtil; - private final RileyLinkServiceData rileyLinkServiceData; + private final MedtronicPumpStatus medtronicPumpStatus; @Inject public MedtronicUtil( AAPSLogger aapsLogger, RxBusWrapper rxBus, RileyLinkUtil rileyLinkUtil, - RileyLinkServiceData rileyLinkServiceData + MedtronicPumpStatus medtronicPumpStatus ) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil; - this.rileyLinkServiceData = rileyLinkServiceData; + this.medtronicPumpStatus = medtronicPumpStatus; } public LocalTime getTimeFrom30MinInterval(int interval) { @@ -393,30 +390,14 @@ public class MedtronicUtil { return lowLevelDebug; } - public PumpDeviceState getPumpDeviceState() { - return pumpDeviceState; - } - - - public void setPumpDeviceState(PumpDeviceState pumpDeviceState) { - this.pumpDeviceState = pumpDeviceState; - - rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.MedtronicPump)); - - rxBus.send(new EventMedtronicDeviceStatusChange(pumpDeviceState)); - } - - public boolean isModelSet() { return medtronicPumpModel != null; } - public MedtronicDeviceType getMedtronicPumpModel() { return medtronicPumpModel; } - public void setMedtronicPumpModel(MedtronicDeviceType medtronicPumpModel) { this.medtronicPumpModel = medtronicPumpModel; } @@ -445,7 +426,7 @@ public class MedtronicUtil { setCurrentCommand(currentCommand); } - rxBus.send(new EventMedtronicDeviceStatusChange(pumpDeviceState)); + rxBus.send(new EventMedtronicDeviceStatusChange(medtronicPumpStatus.getPumpDeviceState())); } From dbb7570de700271346dbb4dd1df56fa444f3b56b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 20:22:00 +0200 Subject: [PATCH 14/23] MDT refactor pass 13 --- .../dependencyInjection/AppComponent.kt | 6 + .../dependencyInjection/AppModule.kt | 6 + .../dialog/RileyLinkBLEScanActivity.java | 6 +- .../RileyLinkCommunicationManager.java | 15 +-- .../common/hw/rileylink/RileyLinkUtil.java | 53 +-------- .../pump/common/hw/rileylink/ble/RFSpy.java | 112 +++++++----------- .../common/hw/rileylink/ble/RileyLinkBLE.java | 8 +- .../rileylink/ble/command/SendAndListen.java | 19 ++- .../hw/rileylink/ble/command/SetPreamble.java | 10 +- .../RileyLinkBluetoothStateReceiver.kt | 3 +- .../service/RileyLinkBroadcastReceiver.java | 8 +- .../service/RileyLinkServiceData.java | 4 + .../tasks/InitializePumpManagerTask.java | 14 ++- .../service/RileyLinkMedtronicService.java | 10 +- 14 files changed, 118 insertions(+), 156 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 64f08720e8..0cf7856ec0 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -30,7 +30,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager @@ -203,6 +206,9 @@ interface AppComponent : AndroidInjector { fun injectWakeAndTuneTask(wakeAndTuneTask: WakeAndTuneTask) fun injectRadioResponse(radioResponse: RadioResponse) fun injectRileyLinkBLE(rileyLinkBLE: RileyLinkBLE) + fun injectRFSpy(rfSpy: RFSpy) + fun injectSendAndListen(sendAndListen: SendAndListen) + fun injectSetPreamble(setPreamble: SetPreamble) @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 25d3d58668..ee351fd9ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -47,7 +47,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager @@ -296,6 +299,9 @@ open class AppModule { @ContributesAndroidInjector fun wakeAndTuneTaskProvider(): WakeAndTuneTask @ContributesAndroidInjector fun radioResponseProvider(): RadioResponse @ContributesAndroidInjector fun rileyLinkBLEProvider(): RileyLinkBLE + @ContributesAndroidInjector fun rfSpyProvider(): RFSpy + @ContributesAndroidInjector fun sendAndListenProvider(): SendAndListen + @ContributesAndroidInjector fun setPreambleProvider(): SetPreamble @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java index 7abf1db894..437edd2923 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java @@ -48,9 +48,7 @@ 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.utils.LocationHelper; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; -import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged; -import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -62,7 +60,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; @Inject RileyLinkUtil rileyLinkUtil; - @Inject MedtronicUtil medtronicUtil; + // TODO change this. Currently verifyConfiguration uses MDT data not only RL @Inject MedtronicPumpPlugin medtronicPumpPlugin; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 30241; // arbitrary. @@ -192,7 +190,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { } // disable currently selected RL, so that we can discover it - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnect); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnect, this); } 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 375ead3c4a..09e21c496c 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 @@ -16,6 +16,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Radi import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.WakeAndTuneTask; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; @@ -34,7 +35,7 @@ public abstract class RileyLinkCommunicationManager { @Inject protected SP sp; @Inject MedtronicPumpStatus medtronicPumpStatus; - @Inject RileyLinkUtil rileyLinkUtil; + @Inject RileyLinkServiceData rileyLinkServiceData; private final int SCAN_TIMEOUT = 1500; @@ -59,23 +60,23 @@ public abstract class RileyLinkCommunicationManager { // All pump communications go through this function. - public E sendAndListen(RLMessage msg, int timeout_ms, Class clazz) + protected E sendAndListen(RLMessage msg, int timeout_ms, Class clazz) throws RileyLinkCommunicationException { return sendAndListen(msg, timeout_ms, null, clazz); } - public E sendAndListen(RLMessage msg, int timeout_ms, Integer extendPreamble_ms, Class clazz) + private E sendAndListen(RLMessage msg, int timeout_ms, Integer extendPreamble_ms, Class clazz) throws RileyLinkCommunicationException { return sendAndListen(msg, timeout_ms, 0, extendPreamble_ms, clazz); } // For backward compatibility - public E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, Integer extendPreamble_ms, Class clazz) + private E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, Integer extendPreamble_ms, Class clazz) throws RileyLinkCommunicationException { return sendAndListen(msg, timeout_ms, repeatCount, 0, extendPreamble_ms, clazz); } - public E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class clazz) + private E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class clazz) throws RileyLinkCommunicationException { // internal flag @@ -189,7 +190,7 @@ public abstract class RileyLinkCommunicationManager { public double tuneForDevice() { - return scanForDevice(rileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies()); + return scanForDevice(rileyLinkServiceData.rileyLinkTargetFrequency.getScanFrequencies()); } @@ -203,7 +204,7 @@ public abstract class RileyLinkCommunicationManager { */ public boolean isValidFrequency(double frequency) { - double[] scanFrequencies = rileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies(); + double[] scanFrequencies = rileyLinkServiceData.rileyLinkTargetFrequency.getScanFrequencies(); if (scanFrequencies.length == 1) { return RileyLinkUtil.isSame(scanFrequencies[0], frequency); 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 960173a8bf..e2711496ee 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 @@ -5,8 +5,6 @@ import android.content.Intent; import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import org.jetbrains.annotations.NotNull; - import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; @@ -17,27 +15,15 @@ import java.util.UUID; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -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; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.BleAdvertisedData; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceNotification; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceResult; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTask; import info.nightscout.androidaps.plugins.pump.common.ui.RileyLinkSelectPreference; -import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange; /** * Created by andy on 17/05/2018. @@ -50,28 +36,13 @@ public class RileyLinkUtil { public RileyLinkCommunicationManager rileyLinkCommunicationManager; @Deprecated static ServiceTask currentTask; - private RileyLinkTargetFrequency rileyLinkTargetFrequency; private RileyLinkEncodingType encoding; private RileyLinkSelectPreference rileyLinkSelectPreference; private Encoding4b6b encoding4b6b; - private RileyLinkFirmwareVersion firmwareVersion; - - - @NotNull private final Context context; - @NotNull private final AAPSLogger aapsLogger; - @NotNull private final RxBusWrapper rxBus; @Inject - public RileyLinkUtil( - Context context, - AAPSLogger aapsLogger, - RxBusWrapper rxBus - - ) { - this.context = context; - this.aapsLogger = aapsLogger; - this.rxBus = rxBus; + public RileyLinkUtil() { instance = this; } @@ -98,7 +69,7 @@ public class RileyLinkUtil { } - public void sendBroadcastMessage(String message) { + public void sendBroadcastMessage(String message, Context context) { Intent intent = new Intent(message); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } @@ -129,7 +100,7 @@ public class RileyLinkUtil { } - public static void sendServiceTransportResponse(ServiceTransport transport, ServiceResult serviceResult) { + private static 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 @@ -140,16 +111,6 @@ public class RileyLinkUtil { } - public RileyLinkTargetFrequency getRileyLinkTargetFrequency() { - return rileyLinkTargetFrequency; - } - - - public void setRileyLinkTargetFrequency(RileyLinkTargetFrequency rileyLinkTargetFrequency) { - this.rileyLinkTargetFrequency = rileyLinkTargetFrequency; - } - - public static boolean isSame(Double d1, Double d2) { double diff = d1 - d2; @@ -218,12 +179,4 @@ public class RileyLinkUtil { public Encoding4b6b getEncoding4b6b() { return encoding4b6b; } - - public void setFirmwareVersion(RileyLinkFirmwareVersion firmwareVersion) { - this.firmwareVersion = firmwareVersion; - } - - public RileyLinkFirmwareVersion getFirmwareVersion() { - return firmwareVersion; - } } 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 e982311b5f..ace5db3987 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 @@ -2,15 +2,14 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble; import android.os.SystemClock; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.UUID; -import info.nightscout.androidaps.MainApp; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.Reset; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.RileyLinkCommand; @@ -28,45 +27,45 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; - import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by geoff on 5/26/16. */ public class RFSpy { + @Inject AAPSLogger aapsLogger; + @Inject ResourceHelper resourceHelper; + @Inject RileyLinkServiceData rileyLinkServiceData; + + private final HasAndroidInjector injector; + public static final long RILEYLINK_FREQ_XTAL = 24000000; public static final int EXPECTED_MAX_BLUETOOTH_LATENCY_MS = 7500; // 1500 - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); public int notConnectedCount = 0; private RileyLinkBLE rileyLinkBle; private RFSpyReader reader; - private RileyLinkTargetFrequency selectedTargetFrequency; private UUID radioServiceUUID = UUID.fromString(GattAttributes.SERVICE_RADIO); private UUID radioDataUUID = UUID.fromString(GattAttributes.CHARA_RADIO_DATA); private UUID radioVersionUUID = UUID.fromString(GattAttributes.CHARA_RADIO_VERSION); private UUID responseCountUUID = UUID.fromString(GattAttributes.CHARA_RADIO_RESPONSE_COUNT); - private RileyLinkFirmwareVersion firmwareVersion; private String bleVersion; // We don't use it so no need of sofisticated logic Double currentFrequencyMHz; - public RFSpy(RileyLinkBLE rileyLinkBle) { + public RFSpy(HasAndroidInjector injector, RileyLinkBLE rileyLinkBle) { + injector.androidInjector().inject(this); + this.injector = injector; this.rileyLinkBle = rileyLinkBle; reader = new RFSpyReader(rileyLinkBle); } - - public RileyLinkFirmwareVersion getRLVersionCached() { - return firmwareVersion; - } - - public String getBLEVersionCached() { return bleVersion; } @@ -75,13 +74,7 @@ public class RFSpy { // Call this after the RL services are discovered. // Starts an async task to read when data is available public void startReader() { - rileyLinkBle.registerRadioResponseCountNotification(new Runnable() { - - @Override - public void run() { - newDataIsAvailable(); - } - }); + rileyLinkBle.registerRadioResponseCountNotification(this::newDataIsAvailable); reader.start(); } @@ -90,13 +83,12 @@ public class RFSpy { // firmware version public void initializeRileyLink() { bleVersion = getVersion(); - firmwareVersion = getFirmwareVersion(); - RileyLinkUtil.getInstance().setFirmwareVersion(firmwareVersion); + rileyLinkServiceData.firmwareVersion = getFirmwareVersion(); } // Call this from the "response count" notification handler. - public void newDataIsAvailable() { + private void newDataIsAvailable() { // pass the message to the reader (which should be internal to RFSpy) reader.newDataIsAvailable(); } @@ -108,11 +100,10 @@ public class RFSpy { BLECommOperationResult result = rileyLinkBle.readCharacteristic_blocking(radioServiceUUID, radioVersionUUID); if (result.resultCode == BLECommOperationResult.RESULT_SUCCESS) { String version = StringUtil.fromBytes(result.value); - if (isLogEnabled()) - LOG.debug("BLE Version: " + version); + aapsLogger.debug(LTag.PUMPBTCOMM, "BLE Version: " + version); return version; } else { - LOG.error("getVersion failed with code: " + result.resultCode); + aapsLogger.error(LTag.PUMPBTCOMM, "getVersion failed with code: " + result.resultCode); return "(null)"; } } @@ -120,14 +111,13 @@ public class RFSpy { public boolean isRileyLinkStillAvailable() { RileyLinkFirmwareVersion firmwareVersion = getFirmwareVersion(); - return (firmwareVersion!= RileyLinkFirmwareVersion.UnknownVersion); + return (firmwareVersion != RileyLinkFirmwareVersion.UnknownVersion); } - public RileyLinkFirmwareVersion getFirmwareVersion() { + private RileyLinkFirmwareVersion getFirmwareVersion() { - if (isLogEnabled()) - LOG.debug("Firmware Version. Get Version - Start"); + aapsLogger.debug(LTag.PUMPBTCOMM, "Firmware Version. Get Version - Start"); for (int i = 0; i < 5; i++) { // We have to call raw version of communication to get firmware version @@ -136,8 +126,7 @@ public class RFSpy { byte[] getVersionRaw = getByteArray(RileyLinkCommandType.GetVersion.code); byte[] response = writeToDataRaw(getVersionRaw, 5000); - if (isLogEnabled()) - LOG.debug("Firmware Version. GetVersion [response={}]", ByteUtil.shortHexString(response)); + aapsLogger.debug(LTag.PUMPBTCOMM, "Firmware Version. GetVersion [response={}]", ByteUtil.shortHexString(response)); if (response != null) { // && response[0] == (byte) 0xDD) { @@ -146,8 +135,7 @@ public class RFSpy { RileyLinkFirmwareVersion version = RileyLinkFirmwareVersion.getByVersionString(StringUtil .fromBytes(response)); - if (isLogEnabled()) - LOG.trace("Firmware Version string: {}, resolved to {}.", versionString, version); + aapsLogger.debug(LTag.PUMPBTCOMM, "Firmware Version string: {}, resolved to {}.", versionString, version); if (version != RileyLinkFirmwareVersion.UnknownVersion) return version; @@ -156,7 +144,7 @@ public class RFSpy { } } - LOG.error("Firmware Version can't be determined. Checking with BLE Version [{}].", bleVersion); + aapsLogger.error(LTag.PUMPBTCOMM, "Firmware Version can't be determined. Checking with BLE Version [{}].", bleVersion); if (bleVersion.contains(" 2.")) { return RileyLinkFirmwareVersion.Version_2_0; @@ -172,7 +160,7 @@ public class RFSpy { byte[] junkInBuffer = reader.poll(0); while (junkInBuffer != null) { - LOG.warn(ThreadUtil.sig() + "writeToData: draining read queue, found this: " + aapsLogger.warn(LTag.PUMPBTCOMM, ThreadUtil.sig() + "writeToData: draining read queue, found this: " + ByteUtil.shortHexString(junkInBuffer)); junkInBuffer = reader.poll(0); } @@ -180,12 +168,12 @@ public class RFSpy { // prepend length, and send it. byte[] prepended = ByteUtil.concat(new byte[]{(byte) (bytes.length)}, bytes); - LOG.debug("writeToData (raw={})", ByteUtil.shortHexString(prepended)); + aapsLogger.debug(LTag.PUMPBTCOMM, "writeToData (raw={})", ByteUtil.shortHexString(prepended)); BLECommOperationResult writeCheck = rileyLinkBle.writeCharacteristic_blocking(radioServiceUUID, radioDataUUID, prepended); if (writeCheck.resultCode != BLECommOperationResult.RESULT_SUCCESS) { - LOG.error("BLE Write operation failed, code=" + writeCheck.resultCode); + aapsLogger.error(LTag.PUMPBTCOMM, "BLE Write operation failed, code=" + writeCheck.resultCode); return null; // will be a null (invalid) response } SystemClock.sleep(100); @@ -204,23 +192,22 @@ public class RFSpy { RFSpyResponse resp = new RFSpyResponse(command, rawResponse); if (rawResponse == null) { - LOG.error("writeToData: No response from RileyLink"); + aapsLogger.error(LTag.PUMPBTCOMM, "writeToData: No response from RileyLink"); notConnectedCount++; } else { if (resp.wasInterrupted()) { - LOG.error("writeToData: RileyLink was interrupted"); + aapsLogger.error(LTag.PUMPBTCOMM, "writeToData: RileyLink was interrupted"); } else if (resp.wasTimeout()) { - LOG.error("writeToData: RileyLink reports timeout"); + aapsLogger.error(LTag.PUMPBTCOMM, "writeToData: RileyLink reports timeout"); notConnectedCount++; } else if (resp.isOK()) { - LOG.warn("writeToData: RileyLink reports OK"); + aapsLogger.warn(LTag.PUMPBTCOMM, "writeToData: RileyLink reports OK"); resetNotConnectedCount(); } else { if (resp.looksLikeRadioPacket()) { // RadioResponse radioResp = resp.getRadioResponse(); // byte[] responsePayload = radioResp.getPayload(); - if (isLogEnabled()) - LOG.trace("writeToData: received radio response. Will decode at upper level"); + aapsLogger.debug(LTag.PUMPBTCOMM, "writeToData: received radio response. Will decode at upper level"); resetNotConnectedCount(); } // Log.i(TAG, "writeToData: raw response is " + ByteUtil.shortHexString(rawResponse)); @@ -274,14 +261,14 @@ public class RFSpy { int sendDelay = repeatCount * delay_ms; int receiveDelay = timeout_ms * (retryCount + 1); - SendAndListen command = new SendAndListen(sendChannel, repeatCount, delay_ms, listenChannel, timeout_ms, + SendAndListen command = new SendAndListen(injector, sendChannel, repeatCount, delay_ms, listenChannel, timeout_ms, retryCount, extendPreamble_ms, pkt); return writeToData(command, sendDelay + receiveDelay + EXPECTED_MAX_BLUETOOTH_LATENCY_MS); } - public RFSpyResponse updateRegister(CC111XRegister reg, int val) { + private RFSpyResponse updateRegister(CC111XRegister reg, int val) { RFSpyResponse resp = writeToData(new UpdateRegister(reg, (byte) val), EXPECTED_MAX_BLUETOOTH_LATENCY_MS); return resp; } @@ -292,11 +279,11 @@ 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 {} MHz", freqMHz); + aapsLogger.info(LTag.PUMPBTCOMM, "Set frequency to {} MHz", freqMHz); this.currentFrequencyMHz = freqMHz; - configureRadioForRegion(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency()); + configureRadioForRegion(rileyLinkServiceData.rileyLinkTargetFrequency); } @@ -362,35 +349,32 @@ public class RFSpy { } break; default: - LOG.warn("No region configuration for RfSpy and {}", frequency.name()); + aapsLogger.warn(LTag.PUMPBTCOMM, "No region configuration for RfSpy and {}", frequency.name()); break; } - - this.selectedTargetFrequency = frequency; } private void setMedtronicEncoding() { RileyLinkEncodingType encoding = RileyLinkEncodingType.FourByteSixByteLocal; - if (RileyLinkFirmwareVersion.isSameVersion(this.firmwareVersion, RileyLinkFirmwareVersion.Version2AndHigher)) { - if (SP.getString(MedtronicConst.Prefs.Encoding, "None").equals(MainApp.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { + if (RileyLinkFirmwareVersion.isSameVersion(rileyLinkServiceData.firmwareVersion, RileyLinkFirmwareVersion.Version2AndHigher)) { + if (SP.getString(MedtronicConst.Prefs.Encoding, "None").equals(resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { encoding = RileyLinkEncodingType.FourByteSixByteRileyLink; } } setRileyLinkEncoding(encoding); - if (isLogEnabled()) - LOG.debug("Set Encoding for Medtronic: " + encoding.name()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Set Encoding for Medtronic: " + encoding.name()); } private RFSpyResponse setPreamble(int preamble) { RFSpyResponse resp = null; try { - resp = writeToData(new SetPreamble(preamble), EXPECTED_MAX_BLUETOOTH_LATENCY_MS); + resp = writeToData(new SetPreamble(injector, preamble), EXPECTED_MAX_BLUETOOTH_LATENCY_MS); } catch (Exception e) { e.toString(); } @@ -431,16 +415,10 @@ public class RFSpy { RFSpyResponse resp = null; try { resp = writeToData(new Reset(), EXPECTED_MAX_BLUETOOTH_LATENCY_MS); - if (isLogEnabled()) - LOG.debug("Reset command send, response: {}", resp); + aapsLogger.debug(LTag.PUMPBTCOMM, "Reset command send, response: {}", resp); } catch (Exception e) { e.toString(); } return resp; } - - - 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 cb4bc6c615..531988fddf 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 @@ -145,7 +145,7 @@ public class RileyLinkBLE { if (newState == BluetoothProfile.STATE_CONNECTED) { if (status == BluetoothGatt.GATT_SUCCESS) { - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected, context); } else { aapsLogger.debug(LTag.PUMPBTCOMM, "BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); } @@ -155,7 +155,7 @@ public class RileyLinkBLE { // aapsLogger.debug(LTag.PUMPBTCOMM,"We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" : // "Disconnecting"); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected, context); if (manualDisconnect) close(); aapsLogger.warn(LTag.PUMPBTCOMM, "RileyLink Disconnected."); @@ -242,7 +242,7 @@ public class RileyLinkBLE { if (rileyLinkFound) { mIsConnected = true; - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady, context); // RileyLinkUtil.sendNotification(new // ServiceNotification(RileyLinkConst.Intents.RileyLinkReady), null); } else { @@ -253,7 +253,7 @@ public class RileyLinkBLE { } else { aapsLogger.debug(LTag.PUMPBTCOMM, "onServicesDiscovered " + getGattStatusMessage(status)); - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed, context); } } }; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java index cdefa2af29..6304567751 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SendAndListen.java @@ -3,14 +3,20 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command; import java.nio.ByteBuffer; import java.util.ArrayList; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkCommandType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; public class SendAndListen extends RileyLinkCommand { + @Inject RileyLinkServiceData rileyLinkServiceData; + private byte sendChannel; private byte repeatCount; private int delayBetweenPackets_ms; @@ -21,20 +27,21 @@ public class SendAndListen extends RileyLinkCommand { private RadioPacket packetToSend; - public SendAndListen(byte sendChannel, byte repeatCount, byte delayBetweenPackets_ms, byte listenChannel, + public SendAndListen(HasAndroidInjector injector, byte sendChannel, byte repeatCount, byte delayBetweenPackets_ms, byte listenChannel, int timeout_ms, byte retryCount, RadioPacket packetToSend ) { - this(sendChannel, repeatCount, delayBetweenPackets_ms, listenChannel, timeout_ms, retryCount, null, + this(injector, sendChannel, repeatCount, delayBetweenPackets_ms, listenChannel, timeout_ms, retryCount, null, packetToSend); } - public SendAndListen(byte sendChannel, byte repeatCount, int delayBetweenPackets_ms, byte listenChannel, - int timeout_ms, byte retryCount, Integer preambleExtension_ms, RadioPacket packetToSend + public SendAndListen(HasAndroidInjector injector, byte sendChannel, byte repeatCount, int delayBetweenPackets_ms, byte listenChannel, + int timeout_ms, byte retryCount, Integer preambleExtension_ms, RadioPacket packetToSend ) { super(); + injector.androidInjector().inject(this); this.sendChannel = sendChannel; this.repeatCount = repeatCount; this.delayBetweenPackets_ms = delayBetweenPackets_ms; @@ -57,8 +64,8 @@ public class SendAndListen extends RileyLinkCommand { // If firmware version is not set (error reading version from device, shouldn't happen), // we will default to version 2 - boolean isPacketV2 = RileyLinkUtil.getInstance().getFirmwareVersion() != null ? RileyLinkUtil.getInstance().getFirmwareVersion() - .isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher) : true; + boolean isPacketV2 = rileyLinkServiceData.firmwareVersion == null || rileyLinkServiceData.firmwareVersion + .isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher); ArrayList bytes = new ArrayList(); bytes.add(this.getCommandType().code); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java index 16ed2efc3b..d58525deb0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/command/SetPreamble.java @@ -4,20 +4,26 @@ import java.nio.ByteBuffer; import org.apache.commons.lang3.NotImplementedException; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkCommandType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; public class SetPreamble extends RileyLinkCommand { + @Inject RileyLinkServiceData rileyLinkServiceData; + private int preamble; - public SetPreamble(int preamble) throws Exception { + public SetPreamble(HasAndroidInjector injector, int preamble) throws Exception { super(); // this command was not supported before 2.0 - if (!RileyLinkUtil.getInstance().getFirmwareVersion().isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { + if (!rileyLinkServiceData.firmwareVersion.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { throw new NotImplementedException("Old firmware does not support SetPreamble command"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt index bca161e139..54e2f59cbd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBluetoothStateReceiver.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service import android.bluetooth.BluetoothAdapter -import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -28,7 +27,7 @@ class RileyLinkBluetoothStateReceiver : DaggerBroadcastReceiver() { BluetoothAdapter.STATE_ON -> { aapsLogger.debug("RileyLinkBluetoothStateReceiver: Bluetooth back on. Sending broadcast to RileyLink Framework") - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected) + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected, context) } } } 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 6dd29285f1..f3ee3bb2a8 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 @@ -106,7 +106,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { LOG.debug("Received Broadcast: " + action); if (!processBluetoothBroadcasts(action) && // - !processRileyLinkBroadcasts(action) && // + !processRileyLinkBroadcasts(action, context) && // !processTuneUpBroadcasts(action) && // !processDeviceSpecificBroadcasts(action, intent) && // !processApplicationSpecificBroadcasts(action, intent) // @@ -137,7 +137,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } - private boolean processRileyLinkBroadcasts(String action) { + private boolean processRileyLinkBroadcasts(String action, Context context) { if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnected)) { if (BluetoothAdapter.getDefaultAdapter().isEnabled()) { @@ -158,7 +158,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { serviceInstance.rfspy.initializeRileyLink(); String bleVersion = serviceInstance.rfspy.getBLEVersionCached(); - RileyLinkFirmwareVersion rlVersion = serviceInstance.rfspy.getRLVersionCached(); + RileyLinkFirmwareVersion rlVersion = rileyLinkServiceData.firmwareVersion; // if (isLoggingEnabled()) LOG.debug("RfSpy version (BLE113): " + bleVersion); @@ -168,7 +168,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; - ServiceTask task = new InitializePumpManagerTask(injector); + ServiceTask task = new InitializePumpManagerTask(injector, context); ServiceTaskExecutor.startTask(task); if (isLoggingEnabled()) LOG.info("Announcing RileyLink open For business"); 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 894bbe7706..b16c4971b9 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 @@ -8,6 +8,7 @@ import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; @@ -28,6 +29,9 @@ public class RileyLinkServiceData { boolean tuneUpDone = false; public RileyLinkError rileyLinkError; public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; + public RileyLinkFirmwareVersion firmwareVersion; + public RileyLinkTargetFrequency rileyLinkTargetFrequency; + public String rileylinkAddress; long lastTuneUpTime = 0L; public Double lastGoodFrequency; 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 4f79eb0561..ff683a665a 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 @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; +import android.content.Context; + import javax.inject.Inject; import dagger.android.HasAndroidInjector; @@ -29,12 +31,16 @@ public class InitializePumpManagerTask extends ServiceTask { @Inject RileyLinkServiceData rileyLinkServiceData; @Inject RileyLinkUtil rileyLinkUtil; - public InitializePumpManagerTask(HasAndroidInjector injector) { + private final Context context; + + public InitializePumpManagerTask(HasAndroidInjector injector, Context context) { super(injector); + this.context = context; } - public InitializePumpManagerTask(HasAndroidInjector injector, ServiceTransport transport) { + public InitializePumpManagerTask(HasAndroidInjector injector, Context context, ServiceTransport transport) { super(injector, transport); + this.context = context; } @Override @@ -74,11 +80,11 @@ public class InitializePumpManagerTask extends ServiceTask { } else { rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.NoContactWithDevice); - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump, context); } } else { - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump, context); } } } 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 8a3702401e..ac88f946aa 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 @@ -51,7 +51,6 @@ public class RileyLinkMedtronicService extends RileyLinkService { private boolean serialChanged = false; private String[] frequencies; - private RileyLinkTargetFrequency targetFrequency; private String rileyLinkAddress = null; private boolean rileyLinkAddressChanged = false; private RileyLinkEncodingType encodingType; @@ -100,7 +99,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { rileyLinkServiceData.rileylinkAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); rileyLinkBLE = new RileyLinkBLE(injector, this); // or this - rfspy = new RFSpy(rileyLinkBLE); + rfspy = new RFSpy(injector, rileyLinkBLE); rfspy.startReader(); // init rileyLinkCommunicationManager @@ -263,9 +262,8 @@ public class RileyLinkMedtronicService extends RileyLinkService { RileyLinkTargetFrequency.Medtronic_US : RileyLinkTargetFrequency.Medtronic_WorldWide; - if (targetFrequency != newTargetFrequency) { - rileyLinkUtil.setRileyLinkTargetFrequency(newTargetFrequency); - targetFrequency = newTargetFrequency; + if (rileyLinkServiceData.rileyLinkTargetFrequency != newTargetFrequency) { + rileyLinkServiceData.rileyLinkTargetFrequency = newTargetFrequency; } } @@ -359,7 +357,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { } if (rileyLinkAddressChanged) { - rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); + rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet, this); rileyLinkAddressChanged = false; } From 975f61563c7a8eeed01cf277018789ddfdac6050 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 21:14:45 +0200 Subject: [PATCH 15/23] MDT refactor pass 14 --- .../activities/MyPreferenceFragment.kt | 8 ++-- .../dialog/RileyLinkBLEScanActivity.java | 2 - .../common/hw/rileylink/RileyLinkUtil.java | 10 ----- .../common/ui/RileyLinkSelectPreference.java | 41 ------------------- .../pump/medtronic/MedtronicPumpPlugin.java | 12 ++++++ app/src/main/res/xml/pref_medtronic.xml | 4 +- 6 files changed, 18 insertions(+), 59 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 0a1c7c4267..2d139ce378 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -275,13 +275,13 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } else if (pref.text != null) { pref.dialogMessage = pref.dialogMessage pref.setSummary(pref.text) - } else { - for (plugin in pluginStore.plugins) { - plugin.updatePreferenceSummary(pref) - } } } + for (plugin in pluginStore.plugins) { + pref?.let { plugin.updatePreferenceSummary(it) } + } + val hmacPasswords = arrayOf( resourceHelper.gs(R.string.key_bolus_password), resourceHelper.gs(R.string.key_master_password), diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java index 437edd2923..50a617a94b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java @@ -110,8 +110,6 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { sp.putString(RileyLinkConst.Prefs.RileyLinkAddress, bleAddress); - rileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress); - medtronicPumpPlugin.getRileyLinkService().verifyConfiguration(); // force reloading of address rxBus.send(new EventMedtronicPumpConfigurationChanged()); 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 e2711496ee..0bc47754e7 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 @@ -23,7 +23,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistor import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceResult; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTask; -import info.nightscout.androidaps.plugins.pump.common.ui.RileyLinkSelectPreference; /** * Created by andy on 17/05/2018. @@ -38,7 +37,6 @@ public class RileyLinkUtil { static ServiceTask currentTask; private RileyLinkEncodingType encoding; - private RileyLinkSelectPreference rileyLinkSelectPreference; private Encoding4b6b encoding4b6b; @Inject @@ -168,14 +166,6 @@ public class RileyLinkUtil { return historyRileyLink; } - public void setRileyLinkSelectPreference(RileyLinkSelectPreference rileyLinkSelectPreference) { - this.rileyLinkSelectPreference = rileyLinkSelectPreference; - } - - public RileyLinkSelectPreference getRileyLinkSelectPreference() { - return rileyLinkSelectPreference; - } - public Encoding4b6b getEncoding4b6b() { return encoding4b6b; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java deleted file mode 100644 index 1bdb6a0a24..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/ui/RileyLinkSelectPreference.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.ui; - -import android.content.Context; -import android.util.AttributeSet; - -import androidx.preference.Preference; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by andy on 10/18/18. - */ - -public class RileyLinkSelectPreference extends Preference { - - public RileyLinkSelectPreference(Context context) { - super(context); - setInitialSummaryValue(); - - RileyLinkUtil.getInstance().setRileyLinkSelectPreference(this); - } - - - public RileyLinkSelectPreference(Context context, AttributeSet attrs) { - super(context, attrs); - setInitialSummaryValue(); - - RileyLinkUtil.getInstance().setRileyLinkSelectPreference(this); - } - - - private void setInitialSummaryValue() { - String value = SP.getString("pref_rileylink_mac_address", null); - - setSummary(value == null ? MainApp.gs(R.string.rileylink_error_address_not_set_short) : value); - } - -} 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 56c5c272d8..c914ae5b48 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 @@ -9,7 +9,9 @@ import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.preference.Preference; +import org.jetbrains.annotations.NotNull; import org.joda.time.LocalDateTime; import java.util.ArrayList; @@ -197,6 +199,16 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } + @Override + public void updatePreferenceSummary(@NotNull Preference pref) { + super.updatePreferenceSummary(pref); + + if (pref.getKey().equals(getResourceHelper().gs(R.string.key_rileylink_mac_address))) { + String value = sp.getStringOrNull(R.string.key_rileylink_mac_address, null); + pref.setSummary(value == null ? getResourceHelper().gs(R.string.rileylink_error_address_not_set_short) : value); + } + } + private String getLogPrefix() { return "MedtronicPumpPlugin::"; } diff --git a/app/src/main/res/xml/pref_medtronic.xml b/app/src/main/res/xml/pref_medtronic.xml index 0d6349489b..fd9a84ab64 100644 --- a/app/src/main/res/xml/pref_medtronic.xml +++ b/app/src/main/res/xml/pref_medtronic.xml @@ -90,13 +90,13 @@ android:selectable="true" android:title="@string/medtronic_bolus_debugging" /> - - + From a3278d53c3805945b5c52b64cbebe93e9ce51a63 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 21:41:24 +0200 Subject: [PATCH 16/23] MDT refactor pass 15 --- .../RileyLinkCommunicationManager.java | 5 ++- .../common/hw/rileylink/RileyLinkUtil.java | 9 ++-- .../service/RileyLinkBroadcastReceiver.java | 38 +++++++---------- .../service/tasks/ServiceTaskExecutor.java | 42 ++++++++----------- .../pump/medtronic/MedtronicPumpPlugin.java | 11 +++-- .../comm/MedtronicCommunicationManager.java | 3 +- 6 files changed, 48 insertions(+), 60 deletions(-) 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 09e21c496c..3963316f37 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 @@ -36,6 +36,7 @@ public abstract class RileyLinkCommunicationManager { @Inject MedtronicPumpStatus medtronicPumpStatus; @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject ServiceTaskExecutor serviceTaskExecutor; private final int SCAN_TIMEOUT = 1500; @@ -106,7 +107,7 @@ public abstract class RileyLinkCommunicationManager { if (diff > ALLOWED_PUMP_UNREACHABLE) { aapsLogger.warn(LTag.PUMPBTCOMM, "We reached max time that Pump can be unreachable. Starting Tuning."); - ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); + serviceTaskExecutor.startTask(new WakeAndTuneTask(injector)); timeoutCount = 0; } } @@ -222,7 +223,7 @@ public abstract class RileyLinkCommunicationManager { public abstract boolean tryToConnectToDevice(); - public double scanForDevice(double[] frequencies) { + private double scanForDevice(double[] frequencies) { aapsLogger.info(LTag.PUMPBTCOMM, "Scanning for receiver ({})", receiverDeviceID); wakeUp(receiverDeviceAwakeForMinutes, false); FrequencyScanResults results = new FrequencyScanResults(); 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 0bc47754e7..184094eb92 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 @@ -33,8 +33,7 @@ public class RileyLinkUtil { private List historyRileyLink = new ArrayList<>(); public RileyLinkCommunicationManager rileyLinkCommunicationManager; - @Deprecated - static ServiceTask currentTask; + private ServiceTask currentTask; private RileyLinkEncodingType encoding; private Encoding4b6b encoding4b6b; @@ -73,8 +72,7 @@ public class RileyLinkUtil { } // FIXME remove ? - @Deprecated - public static void setCurrentTask(ServiceTask task) { + public void setCurrentTask(ServiceTask task) { if (currentTask == null) { currentTask = task; } else { @@ -83,8 +81,7 @@ public class RileyLinkUtil { } - @Deprecated - public static void finishCurrentTask(ServiceTask task) { + public void finishCurrentTask(ServiceTask task) { if (task != currentTask) { //LOG.error("finishCurrentTask: task does not match"); } 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 f3ee3bb2a8..b04abb7195 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 @@ -22,10 +22,11 @@ import javax.inject.Inject; import dagger.android.DaggerBroadcastReceiver; import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; 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; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; @@ -44,9 +45,10 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { @Inject HasAndroidInjector injector; - @Inject RileyLinkUtil rileyLinkUtil; @Inject SP sp; + @Inject AAPSLogger aapsLogger; @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject ServiceTaskExecutor serviceTaskExecutor; private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); @@ -102,8 +104,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { if (action == null) { LOG.error("onReceive: null action"); } else { - if (isLoggingEnabled()) - LOG.debug("Received Broadcast: " + action); + aapsLogger.debug(LTag.PUMPBTCOMM, "Received Broadcast: " + action); if (!processBluetoothBroadcasts(action) && // !processRileyLinkBroadcasts(action, context) && // @@ -149,8 +150,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkReady)) { - if (isLoggingEnabled()) - LOG.warn("MedtronicConst.Intents.RileyLinkReady"); + aapsLogger.warn(LTag.PUMPBTCOMM, "MedtronicConst.Intents.RileyLinkReady"); // sendIPCNotification(RT2Const.IPC.MSG_note_WakingPump); serviceInstance.rileyLinkBLE.enableNotifications(); @@ -161,17 +161,16 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { RileyLinkFirmwareVersion rlVersion = rileyLinkServiceData.firmwareVersion; // if (isLoggingEnabled()) - LOG.debug("RfSpy version (BLE113): " + bleVersion); + aapsLogger.debug(LTag.PUMPBTCOMM, "RfSpy version (BLE113): " + bleVersion); serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion; // if (isLoggingEnabled()) - LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); + aapsLogger.debug(LTag.PUMPBTCOMM, "RfSpy Radio version (CC110): " + rlVersion.name()); serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; ServiceTask task = new InitializePumpManagerTask(injector, context); - ServiceTaskExecutor.startTask(task); - if (isLoggingEnabled()) - LOG.info("Announcing RileyLink open For business"); + serviceTaskExecutor.startTask(task); + aapsLogger.info(LTag.PUMPBTCOMM, "Announcing RileyLink open For business"); return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) { @@ -200,18 +199,16 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { public boolean processBluetoothBroadcasts(String action) { if (action.equals(RileyLinkConst.Intents.BluetoothConnected)) { - if (isLoggingEnabled()) - LOG.debug("Bluetooth - Connected"); - ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(injector)); + aapsLogger.debug(LTag.PUMPBTCOMM, "Bluetooth - Connected"); + serviceTaskExecutor.startTask(new DiscoverGattServicesTask(injector)); return true; } else if (action.equals(RileyLinkConst.Intents.BluetoothReconnected)) { - if (isLoggingEnabled()) - LOG.debug("Bluetooth - Reconnecting"); + aapsLogger.debug(LTag.PUMPBTCOMM, "Bluetooth - Reconnecting"); serviceInstance.bluetoothInit(); - ServiceTaskExecutor.startTask(new DiscoverGattServicesTask(injector, true)); + serviceTaskExecutor.startTask(new DiscoverGattServicesTask(injector, true)); return true; } else { @@ -226,7 +223,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { if (this.broadcastIdentifiers.get("TuneUp").contains(action)) { if (serviceInstance.getRileyLinkTargetDevice().isTuneUpEnabled()) { - ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); + serviceTaskExecutor.startTask(new WakeAndTuneTask(injector)); } return true; } else { @@ -252,11 +249,6 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { return false; } - - public boolean isLoggingEnabled() { - return (L.isEnabled(L.PUMPCOMM)); - } - public void unregisterBroadcasts(Context context) { LocalBroadcastManager.getInstance(context).unregisterReceiver(this); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTaskExecutor.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTaskExecutor.java index 1c6f33b071..5f430be89f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTaskExecutor.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ServiceTaskExecutor.java @@ -4,46 +4,40 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import android.util.Log; +import javax.inject.Inject; +import javax.inject.Singleton; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; /** * Created by geoff on 7/9/16. */ +@Singleton public class ServiceTaskExecutor extends ThreadPoolExecutor { - private static final String TAG = "ServiceTaskExecutor"; - private static ServiceTaskExecutor instance; + @Inject RileyLinkUtil rileyLinkUtil; + @Inject AAPSLogger aapsLogger; + private static LinkedBlockingQueue taskQueue = new LinkedBlockingQueue<>(); - static { - instance = new ServiceTaskExecutor(); - } - - - private ServiceTaskExecutor() { + @Inject + public ServiceTaskExecutor() { super(1, 1, 10000, TimeUnit.MILLISECONDS, taskQueue); } - - public static ServiceTaskExecutor getInstance() { - return instance; - } - - - public static ServiceTask startTask(ServiceTask task) { - instance.execute(task); // task will be run on async thread from pool. + public ServiceTask startTask(ServiceTask task) { + execute(task); // task will be run on async thread from pool. return task; } - // FIXME protected void beforeExecute(Thread t, Runnable r) { // This is run on either caller UI thread or Service UI thread. - ServiceTask task = (ServiceTask)r; - Log.v(TAG, "About to run task " + task.getClass().getSimpleName()); - RileyLinkUtil.setCurrentTask(task); + ServiceTask task = (ServiceTask) r; + aapsLogger.debug(LTag.PUMPBTCOMM, "About to run task " + task.getClass().getSimpleName()); + rileyLinkUtil.setCurrentTask(task); task.preOp(); } @@ -51,9 +45,9 @@ public class ServiceTaskExecutor extends ThreadPoolExecutor { // FIXME protected void afterExecute(Runnable r, Throwable t) { // This is run on either caller UI thread or Service UI thread. - ServiceTask task = (ServiceTask)r; + ServiceTask task = (ServiceTask) r; task.postOp(); - Log.v(TAG, "Finishing task " + task.getClass().getSimpleName()); - RileyLinkUtil.finishCurrentTask(task); + aapsLogger.debug(LTag.PUMPBTCOMM, "Finishing task " + task.getClass().getSimpleName()); + rileyLinkUtil.finishCurrentTask(task); } } 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 c914ae5b48..45ed524fdf 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 @@ -103,6 +103,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final MedtronicPumpStatus medtronicPumpStatus; private final MedtronicHistoryData medtronicHistoryData; private final RileyLinkServiceData rileyLinkServiceData; + private final ServiceTaskExecutor serviceTaskExecutor; protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService rileyLinkMedtronicService; @@ -134,7 +135,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter MedtronicUtil medtronicUtil, MedtronicPumpStatus medtronicPumpStatus, MedtronicHistoryData medtronicHistoryData, - RileyLinkServiceData rileyLinkServiceData + RileyLinkServiceData rileyLinkServiceData, + ServiceTaskExecutor serviceTaskExecutor ) { super(new PluginDescription() // @@ -155,6 +157,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter this.medtronicPumpStatus = medtronicPumpStatus; this.medtronicHistoryData = medtronicHistoryData; this.rileyLinkServiceData = rileyLinkServiceData; + this.serviceTaskExecutor = serviceTaskExecutor; displayConnectionMessages = false; @@ -596,7 +599,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (errorCount >= 5) { aapsLogger.error("Number of error counts was 5 or more. Starting tunning."); setRefreshButtonEnabled(true); - ServiceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); + serviceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); return; } @@ -1527,7 +1530,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter case WakeUpAndTune: { if (rileyLinkMedtronicService.verifyConfiguration()) { - ServiceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); + serviceTaskExecutor.startTask(new WakeAndTuneTask(getInjector())); } else { Intent i = new Intent(context, ErrorHelperActivity.class); i.putExtra("soundid", R.raw.boluserror); @@ -1547,7 +1550,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter break; case ResetRileyLinkConfiguration: { - ServiceTaskExecutor.startTask(new ResetRileyLinkConfigurationTask(getInjector())); + serviceTaskExecutor.startTask(new ResetRileyLinkConfigurationTask(getInjector())); } break; 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 fb33bc5fa9..0fb88af515 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 @@ -68,6 +68,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager @Inject MedtronicUtil medtronicUtil; @Inject MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder; @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject ServiceTaskExecutor serviceTaskExecutor; private final int MAX_COMMAND_TRIES = 3; private final int DEFAULT_TIMEOUT = 2000; @@ -136,7 +137,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager long diff = System.currentTimeMillis() - medtronicPumpStatus.lastConnection; if (diff > RILEYLINK_TIMEOUT) { - ServiceTaskExecutor.startTask(new WakeAndTuneTask(injector)); + serviceTaskExecutor.startTask(new WakeAndTuneTask(injector)); } } From 52e0e3ec5141219b873477c306051cbd580b1a5d Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 22:19:50 +0200 Subject: [PATCH 17/23] MDT refactor pass 16 --- .../dependencyInjection/AppComponent.kt | 2 ++ .../dependencyInjection/AppModule.kt | 2 ++ .../RileyLinkCommunicationManager.java | 8 +++---- .../common/hw/rileylink/RileyLinkUtil.java | 12 ----------- .../pump/common/hw/rileylink/ble/RFSpy.java | 14 +++++++------ .../hw/rileylink/ble/data/RadioPacket.java | 21 ++++++++++++------- .../hw/rileylink/ble/data/RadioResponse.java | 7 ++++--- .../comm/MedtronicCommunicationManager.java | 2 +- 8 files changed, 34 insertions(+), 34 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 0cf7856ec0..7d9dcac987 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -34,6 +34,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager @@ -209,6 +210,7 @@ interface AppComponent : AndroidInjector { fun injectRFSpy(rfSpy: RFSpy) fun injectSendAndListen(sendAndListen: SendAndListen) fun injectSetPreamble(setPreamble: SetPreamble) + fun injectRadioPacket(radioPacket: RadioPacket) @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index ee351fd9ef..6d334aa3d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -51,6 +51,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager @@ -302,6 +303,7 @@ open class AppModule { @ContributesAndroidInjector fun rfSpyProvider(): RFSpy @ContributesAndroidInjector fun sendAndListenProvider(): SendAndListen @ContributesAndroidInjector fun setPreambleProvider(): SetPreamble + @ContributesAndroidInjector fun radioPacketProvider(): RadioPacket @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider 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 3963316f37..f89e820671 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 @@ -86,7 +86,7 @@ public abstract class RileyLinkCommunicationManager { aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); } - RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(msg.getTxData()), + RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(injector, msg.getTxData()), (byte) 0, (byte) repeatCount, (byte) 0, (byte) 0, timeout_ms, (byte) retryCount, extendPreamble_ms); RadioResponse radioResponse = rfSpyResponse.getRadioResponse(injector); @@ -159,7 +159,7 @@ public abstract class RileyLinkCommunicationManager { aapsLogger.info(LTag.PUMPBTCOMM, "Waking pump..."); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple - RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, + RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 200, (byte) 0, (byte) 0, 25000, (byte) 0); aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); @@ -238,7 +238,7 @@ public abstract class RileyLinkCommunicationManager { for (int j = 0; j < tries; j++) { byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); - RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 0, + RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 0, (byte) 0, (byte) 0, 1250, (byte) 0); if (resp.wasTimeout()) { aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: Failed to find pump at frequency {}", frequencies[i]); @@ -326,7 +326,7 @@ public abstract class RileyLinkCommunicationManager { rfspy.setBaseFrequency(freqMHz); // RLMessage msg = makeRLMessage(RLMessageType.ReadSimpleData); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); - RadioPacket pkt = new RadioPacket(pumpMsgContent); + RadioPacket pkt = new RadioPacket(injector, pumpMsgContent); RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, SCAN_TIMEOUT, (byte) 0); if (resp.wasTimeout()) { aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: no pump response at frequency {}", freqMHz); 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 184094eb92..8fc900aa90 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 @@ -32,7 +32,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks public class RileyLinkUtil { private List historyRileyLink = new ArrayList<>(); - public RileyLinkCommunicationManager rileyLinkCommunicationManager; private ServiceTask currentTask; private RileyLinkEncodingType encoding; @@ -40,16 +39,6 @@ public class RileyLinkUtil { @Inject public RileyLinkUtil() { - instance = this; - } - - private static RileyLinkUtil instance; - - // TODO: replace by injection - @Deprecated - public static RileyLinkUtil getInstance() { - if (instance == null) throw new IllegalStateException("RileyLinkUtil not initialized"); - return instance; } public RileyLinkEncodingType getEncoding() { @@ -113,7 +102,6 @@ public class RileyLinkUtil { } - @Deprecated public static BleAdvertisedData parseAdertisedData(byte[] advertisedData) { List uuids = new ArrayList(); String name = null; 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 ace5db3987..7f933c1082 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 @@ -32,7 +32,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper; /** @@ -42,12 +42,14 @@ public class RFSpy { @Inject AAPSLogger aapsLogger; @Inject ResourceHelper resourceHelper; + @Inject SP sp; @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject RileyLinkUtil rileyLinkUtil; private final HasAndroidInjector injector; - public static final long RILEYLINK_FREQ_XTAL = 24000000; - public static final int EXPECTED_MAX_BLUETOOTH_LATENCY_MS = 7500; // 1500 + private static final long RILEYLINK_FREQ_XTAL = 24000000; + private static final int EXPECTED_MAX_BLUETOOTH_LATENCY_MS = 7500; // 1500 public int notConnectedCount = 0; private RileyLinkBLE rileyLinkBle; private RFSpyReader reader; @@ -56,7 +58,7 @@ public class RFSpy { private UUID radioVersionUUID = UUID.fromString(GattAttributes.CHARA_RADIO_VERSION); private UUID responseCountUUID = UUID.fromString(GattAttributes.CHARA_RADIO_RESPONSE_COUNT); private String bleVersion; // We don't use it so no need of sofisticated logic - Double currentFrequencyMHz; + private Double currentFrequencyMHz; public RFSpy(HasAndroidInjector injector, RileyLinkBLE rileyLinkBle) { @@ -360,7 +362,7 @@ public class RFSpy { RileyLinkEncodingType encoding = RileyLinkEncodingType.FourByteSixByteLocal; if (RileyLinkFirmwareVersion.isSameVersion(rileyLinkServiceData.firmwareVersion, RileyLinkFirmwareVersion.Version2AndHigher)) { - if (SP.getString(MedtronicConst.Prefs.Encoding, "None").equals(resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { + if (sp.getString(MedtronicConst.Prefs.Encoding, "None").equals(resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { encoding = RileyLinkEncodingType.FourByteSixByteRileyLink; } } @@ -387,7 +389,7 @@ public class RFSpy { if (resp.isOK()) { reader.setRileyLinkEncodingType(encoding); - RileyLinkUtil.getInstance().setEncoding(encoding); + rileyLinkUtil.setEncoding(encoding); } return resp; 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 35fc0d54ff..cff7c1b9d1 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 @@ -2,6 +2,9 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data; import org.apache.commons.lang3.NotImplementedException; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.CRC; @@ -12,10 +15,13 @@ import info.nightscout.androidaps.plugins.pump.common.utils.CRC; public class RadioPacket { - protected byte[] pkt; + @Inject RileyLinkUtil rileyLinkUtil; + + private byte[] pkt; - public RadioPacket(byte[] pkt) { + public RadioPacket(HasAndroidInjector injector, byte[] pkt) { + injector.androidInjector().inject(this); this.pkt = pkt; } @@ -25,7 +31,7 @@ public class RadioPacket { } - public byte[] getWithCRC() { + private byte[] getWithCRC() { byte[] withCRC = ByteUtil.concat(pkt, CRC.crc8(pkt)); return withCRC; } @@ -33,7 +39,7 @@ public class RadioPacket { public byte[] getEncoded() { - switch (RileyLinkUtil.getInstance().getEncoding()) { + switch (rileyLinkUtil.getEncoding()) { case Manchester: { // We have this encoding in RL firmware return pkt; } @@ -41,8 +47,8 @@ public class RadioPacket { case FourByteSixByteLocal: { byte[] withCRC = getWithCRC(); - byte[] encoded = RileyLinkUtil.getInstance().getEncoding4b6b().encode4b6b(withCRC); - return ByteUtil.concat(encoded, (byte)0); + byte[] encoded = rileyLinkUtil.getEncoding4b6b().encode4b6b(withCRC); + return ByteUtil.concat(encoded, (byte) 0); } case FourByteSixByteRileyLink: { @@ -50,8 +56,7 @@ public class RadioPacket { } default: - throw new NotImplementedException(("Encoding not supported: " + RileyLinkUtil.getInstance().getEncoding().toString())); + throw new NotImplementedException(("Encoding not supported: " + rileyLinkUtil.getEncoding().toString())); } } - } 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 343e32da67..785691e4c2 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 @@ -25,6 +25,7 @@ public class RadioResponse { @Inject AAPSLogger aapsLogger; @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject RileyLinkUtil rileyLinkUtil; private boolean decodedOK = false; public int rssi; @@ -98,7 +99,7 @@ public class RadioResponse { return; } - switch (RileyLinkUtil.getInstance().getEncoding()) { + switch (rileyLinkUtil.getEncoding()) { case Manchester: case FourByteSixByteRileyLink: { @@ -108,7 +109,7 @@ public class RadioResponse { break; case FourByteSixByteLocal: { - byte[] decodeThis = RileyLinkUtil.getInstance().getEncoding4b6b().decode4b6b(encodedPayload); + byte[] decodeThis = rileyLinkUtil.getEncoding4b6b().decode4b6b(encodedPayload); if (decodeThis != null && decodeThis.length > 2) { decodedOK = true; @@ -127,7 +128,7 @@ public class RadioResponse { break; default: - throw new NotImplementedException("this {" + RileyLinkUtil.getInstance().getEncoding().toString() + throw new NotImplementedException("this {" + rileyLinkUtil.getEncoding().toString() + "} encoding is not supported"); } } catch (NumberFormatException e) { 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 0fb88af515..37de1fa7f6 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 @@ -150,7 +150,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpDeviceState state = medtronicPumpStatus.getPumpDeviceState(); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple - RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, + RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 200, (byte) 0, (byte) 0, 25000, (byte) 0); aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); From 1b21b74878c3382790490b639d5682a40d1af254 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 23:02:12 +0200 Subject: [PATCH 18/23] MDT refactor pass 17 --- .../dependencyInjection/FragmentsModule.kt | 2 + .../pump/common/PumpPluginAbstract.java | 6 +- .../pump/common/hw/rileylink/ble/RFSpy.java | 4 +- .../common/hw/rileylink/ble/RFSpyReader.java | 64 +++++++------------ .../common/hw/rileylink/ble/RileyLinkBLE.java | 10 +-- .../CharacteristicReadOperation.java | 36 ++++------- .../CharacteristicWriteOperation.java | 36 ++++------- .../operations/DescriptorWriteOperation.java | 23 ++++--- .../hw/rileylink/data/RLHistoryItem.java | 12 ++-- .../RileyLinkStatusHistoryFragment.java | 37 ++++++----- .../service/RileyLinkBroadcastReceiver.java | 14 ++-- .../service/tasks/WakeAndTuneTask.java | 2 - .../pump/common/utils/DateTimeUtil.java | 10 ++- .../pump/common/utils/LocationHelper.java | 3 +- .../RileyLinkStatusDeviceMedtronic.java | 11 +++- 15 files changed, 116 insertions(+), 154 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index 4e6161473d..87129bbb37 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -37,6 +37,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyL import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment +import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpFragment import info.nightscout.androidaps.plugins.source.BGSourceFragment import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment @@ -118,4 +119,5 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesRileyLinkStatusGeneral(): RileyLinkStatusGeneralFragment @ContributesAndroidInjector abstract fun contributesRileyLinkStatusHistoryFragment(): RileyLinkStatusHistoryFragment + @ContributesAndroidInjector abstract fun contributesRileyLinkStatusDeviceMedtronic(): RileyLinkStatusDeviceMedtronic } \ No newline at end of file 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 669adeff31..efca466951 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 @@ -37,7 +37,6 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.treatments.Treatment; @@ -109,8 +108,11 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public abstract void initPumpStatusData(); + public abstract void resetRileyLinkConfiguration(); + public abstract void doTuneUpDevice(); + public abstract RileyLinkService getRileyLinkService(); @Override @@ -446,7 +448,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public ManufacturerType manufacturer() { - return pumpType.getManufacturer() ; + return pumpType.getManufacturer(); } @NotNull 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 7f933c1082..ef3641fa02 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 @@ -32,8 +32,8 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; -import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by geoff on 5/26/16. @@ -65,7 +65,7 @@ public class RFSpy { injector.androidInjector().inject(this); this.injector = injector; this.rileyLinkBle = rileyLinkBle; - reader = new RFSpyReader(rileyLinkBle); + reader = new RFSpyReader(aapsLogger, rileyLinkBle); } public String getBLEVersionCached() { 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 595da51847..5a3d459154 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 @@ -1,19 +1,15 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble; +import android.os.AsyncTask; +import android.os.SystemClock; + import java.util.UUID; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import android.os.AsyncTask; -import android.os.SystemClock; - -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations.BLECommOperationResult; @@ -25,7 +21,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; */ public class RFSpyReader { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + private final AAPSLogger aapsLogger; private static AsyncTask readerTask; private RileyLinkBLE rileyLinkBle; private Semaphore waitForRadioData = new Semaphore(0, true); @@ -35,13 +31,9 @@ public class RFSpyReader { private boolean stopAtNull = true; - public RFSpyReader(RileyLinkBLE rileyLinkBle) { + RFSpyReader(AAPSLogger aapsLogger, RileyLinkBLE rileyLinkBle) { this.rileyLinkBle = rileyLinkBle; - } - - - public void init(RileyLinkBLE rileyLinkBLE) { - this.rileyLinkBle = rileyLinkBLE; + this.aapsLogger = aapsLogger; } @@ -52,16 +44,15 @@ public class RFSpyReader { this.rileyLinkBle = rileyLinkBle; } - public void setRileyLinkEncodingType(RileyLinkEncodingType encodingType) { + void setRileyLinkEncodingType(RileyLinkEncodingType encodingType) { stopAtNull = !(encodingType == RileyLinkEncodingType.Manchester || // encodingType == RileyLinkEncodingType.FourByteSixByteRileyLink); } // This timeout must be coordinated with the length of the RFSpy radio operation or Bad Things Happen. - public byte[] poll(int timeout_ms) { - if (isLogEnabled()) - LOG.trace(ThreadUtil.sig() + "Entering poll at t==" + SystemClock.uptimeMillis() + ", timeout is " + timeout_ms + byte[] poll(int timeout_ms) { + aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "Entering poll at t==" + SystemClock.uptimeMillis() + ", timeout is " + timeout_ms + " mDataQueue size is " + mDataQueue.size()); if (mDataQueue.isEmpty()) { @@ -70,16 +61,14 @@ public class RFSpyReader { // returns null if timeout. byte[] dataFromQueue = mDataQueue.poll(timeout_ms, TimeUnit.MILLISECONDS); if (dataFromQueue != null) { - if (isLogEnabled()) - LOG.debug("Got data [" + ByteUtil.shortHexString(dataFromQueue) + "] at t==" - + SystemClock.uptimeMillis()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Got data [" + ByteUtil.shortHexString(dataFromQueue) + "] at t==" + + SystemClock.uptimeMillis()); } else { - if (isLogEnabled()) - LOG.debug("Got data [null] at t==" + SystemClock.uptimeMillis()); + aapsLogger.debug(LTag.PUMPBTCOMM, "Got data [null] at t==" + SystemClock.uptimeMillis()); } return dataFromQueue; } catch (InterruptedException e) { - LOG.error("poll: Interrupted waiting for data"); + aapsLogger.error(LTag.PUMPBTCOMM, "poll: Interrupted waiting for data"); } } @@ -88,11 +77,10 @@ public class RFSpyReader { // Call this from the "response count" notification handler. - public void newDataIsAvailable() { + void newDataIsAvailable() { releaseCount++; - if (isLogEnabled()) - LOG.trace(ThreadUtil.sig() + "waitForRadioData released(count=" + releaseCount + ") at t=" + aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "waitForRadioData released(count=" + releaseCount + ") at t=" + SystemClock.uptimeMillis()); waitForRadioData.release(); } @@ -110,8 +98,7 @@ public class RFSpyReader { try { acquireCount++; waitForRadioData.acquire(); - if (isLogEnabled()) - LOG.trace(ThreadUtil.sig() + "waitForRadioData acquired (count=" + acquireCount + ") at t=" + aapsLogger.debug(LTag.PUMPBTCOMM, ThreadUtil.sig() + "waitForRadioData acquired (count=" + acquireCount + ") at t=" + SystemClock.uptimeMillis()); SystemClock.sleep(100); SystemClock.sleep(1); @@ -130,24 +117,19 @@ public class RFSpyReader { } mDataQueue.add(result.value); } else if (result.resultCode == BLECommOperationResult.RESULT_INTERRUPTED) { - LOG.error("Read operation was interrupted"); + aapsLogger.error(LTag.PUMPBTCOMM, "Read operation was interrupted"); } else if (result.resultCode == BLECommOperationResult.RESULT_TIMEOUT) { - LOG.error("Read operation on Radio Data timed out"); + aapsLogger.error(LTag.PUMPBTCOMM, "Read operation on Radio Data timed out"); } else if (result.resultCode == BLECommOperationResult.RESULT_BUSY) { - LOG.error("FAIL: RileyLinkBLE reports operation already in progress"); + aapsLogger.error(LTag.PUMPBTCOMM, "FAIL: RileyLinkBLE reports operation already in progress"); } else if (result.resultCode == BLECommOperationResult.RESULT_NONE) { - LOG.error("FAIL: got invalid result code: " + result.resultCode); + aapsLogger.error(LTag.PUMPBTCOMM, "FAIL: got invalid result code: " + result.resultCode); } } catch (InterruptedException e) { - LOG.error("Interrupted while waiting for data"); + aapsLogger.error(LTag.PUMPBTCOMM, "Interrupted while waiting for data"); } } } }.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 531988fddf..bf71a19fe5 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 @@ -47,8 +47,8 @@ public class RileyLinkBLE { @Inject RileyLinkUtil rileyLinkUtil; private final Context context; - public boolean gattDebugEnabled = true; - boolean manualDisconnect = false; + private boolean gattDebugEnabled = true; + private boolean manualDisconnect = false; private BluetoothAdapter bluetoothAdapter; private BluetoothGattCallback bluetoothGattCallback; private BluetoothDevice rileyLinkDevice; @@ -447,7 +447,7 @@ public class RileyLinkBLE { } BluetoothGattDescriptor descr = list.get(0); // Tell the remote device to send the notifications - mCurrentOperation = new DescriptorWriteOperation(bluetoothConnectionGatt, descr, + mCurrentOperation = new DescriptorWriteOperation(aapsLogger, bluetoothConnectionGatt, descr, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mCurrentOperation.execute(this); if (mCurrentOperation.timedOut) { @@ -496,7 +496,7 @@ public class RileyLinkBLE { } else { BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID) .getCharacteristic(charaUUID); - mCurrentOperation = new CharacteristicWriteOperation(bluetoothConnectionGatt, chara, value); + mCurrentOperation = new CharacteristicWriteOperation(aapsLogger, bluetoothConnectionGatt, chara, value); mCurrentOperation.execute(this); if (mCurrentOperation.timedOut) { rval.resultCode = BLECommOperationResult.RESULT_TIMEOUT; @@ -538,7 +538,7 @@ public class RileyLinkBLE { } else { BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID).getCharacteristic( charaUUID); - mCurrentOperation = new CharacteristicReadOperation(bluetoothConnectionGatt, chara); + mCurrentOperation = new CharacteristicReadOperation(aapsLogger, bluetoothConnectionGatt, chara); mCurrentOperation.execute(this); if (mCurrentOperation.timedOut) { rval.resultCode = BLECommOperationResult.RESULT_TIMEOUT; 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 a891fce501..09a3c58469 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 @@ -1,17 +1,14 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.os.SystemClock; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes; @@ -20,12 +17,13 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Gatt */ public class CharacteristicReadOperation extends BLECommOperation { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + private final AAPSLogger aapsLogger; private BluetoothGattCharacteristic characteristic; - public CharacteristicReadOperation(BluetoothGatt gatt, BluetoothGattCharacteristic chara) { + public CharacteristicReadOperation(AAPSLogger aapsLogger, BluetoothGatt gatt, BluetoothGattCharacteristic chara) { + this.aapsLogger = aapsLogger; this.gatt = gatt; this.characteristic = chara; } @@ -39,15 +37,14 @@ public class CharacteristicReadOperation extends BLECommOperation { boolean didAcquire = operationComplete.tryAcquire(getGattOperationTimeout_ms(), TimeUnit.MILLISECONDS); if (didAcquire) { SystemClock.sleep(1); // This is to allow the IBinder thread to exit before we continue, allowing easier - // understanding of the sequence of events. + // understanding of the sequence of events. // success } else { - LOG.error("Timeout waiting for gatt write operation to complete"); + aapsLogger.error(LTag.PUMPBTCOMM, "Timeout waiting for gatt write operation to complete"); timedOut = true; } } catch (InterruptedException e) { - if (isLogEnabled()) - LOG.error("Interrupted while waiting for gatt write operation to complete"); + aapsLogger.error(LTag.PUMPBTCOMM, "Interrupted while waiting for gatt write operation to complete"); interrupted = true; } value = characteristic.getValue(); @@ -58,15 +55,10 @@ public class CharacteristicReadOperation extends BLECommOperation { public void gattOperationCompletionCallback(UUID uuid, byte[] value) { super.gattOperationCompletionCallback(uuid, value); if (!characteristic.getUuid().equals(uuid)) { - LOG.error(String.format( - "Completion callback: UUID does not match! out of sequence? Found: %s, should be %s", - GattAttributes.lookup(characteristic.getUuid()), GattAttributes.lookup(uuid))); + aapsLogger.error(LTag.PUMPCOMM, String.format( + "Completion callback: UUID does not match! out of sequence? Found: %s, should be %s", + GattAttributes.lookup(characteristic.getUuid()), GattAttributes.lookup(uuid))); } 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 54f20d517d..011135e7ac 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 @@ -1,17 +1,14 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.os.SystemClock; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes; @@ -20,12 +17,13 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Gatt */ public class CharacteristicWriteOperation extends BLECommOperation { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + private final AAPSLogger aapsLogger; private BluetoothGattCharacteristic characteristic; - public CharacteristicWriteOperation(BluetoothGatt gatt, BluetoothGattCharacteristic chara, byte[] value) { + public CharacteristicWriteOperation(AAPSLogger aapsLogger, BluetoothGatt gatt, BluetoothGattCharacteristic chara, byte[] value) { + this.aapsLogger = aapsLogger; this.gatt = gatt; this.characteristic = chara; this.value = value; @@ -42,14 +40,14 @@ public class CharacteristicWriteOperation extends BLECommOperation { boolean didAcquire = operationComplete.tryAcquire(getGattOperationTimeout_ms(), TimeUnit.MILLISECONDS); if (didAcquire) { SystemClock.sleep(1); // This is to allow the IBinder thread to exit before we continue, allowing easier - // understanding of the sequence of events. + // understanding of the sequence of events. // success } else { - LOG.error("Timeout waiting for gatt write operation to complete"); + aapsLogger.error(LTag.PUMPBTCOMM, "Timeout waiting for gatt write operation to complete"); timedOut = true; } } catch (InterruptedException e) { - LOG.error("Interrupted while waiting for gatt write operation to complete"); + aapsLogger.error(LTag.PUMPBTCOMM, "Interrupted while waiting for gatt write operation to complete"); interrupted = true; } @@ -60,16 +58,10 @@ public class CharacteristicWriteOperation extends BLECommOperation { @Override public void gattOperationCompletionCallback(UUID uuid, byte[] value) { if (!characteristic.getUuid().equals(uuid)) { - LOG.error(String.format( - "Completion callback: UUID does not match! out of sequence? Found: %s, should be %s", - GattAttributes.lookup(characteristic.getUuid()), GattAttributes.lookup(uuid))); + aapsLogger.error(LTag.PUMPCOMM, String.format( + "Completion callback: UUID does not match! out of sequence? Found: %s, should be %s", + GattAttributes.lookup(characteristic.getUuid()), GattAttributes.lookup(uuid))); } 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/DescriptorWriteOperation.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/DescriptorWriteOperation.java index 82f3359198..49c912e997 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/DescriptorWriteOperation.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/operations/DescriptorWriteOperation.java @@ -1,16 +1,14 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.operations; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattDescriptor; import android.os.SystemClock; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE; /** @@ -18,12 +16,13 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLink */ public class DescriptorWriteOperation extends BLECommOperation { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(DescriptorWriteOperation.class); + private final AAPSLogger aapsLogger; private BluetoothGattDescriptor descr; - public DescriptorWriteOperation(BluetoothGatt gatt, BluetoothGattDescriptor descr, byte[] value) { + public DescriptorWriteOperation(AAPSLogger aapsLogger, BluetoothGatt gatt, BluetoothGattDescriptor descr, byte[] value) { + this.aapsLogger = aapsLogger; this.gatt = gatt; this.descr = descr; this.value = value; @@ -46,14 +45,14 @@ public class DescriptorWriteOperation extends BLECommOperation { boolean didAcquire = operationComplete.tryAcquire(getGattOperationTimeout_ms(), TimeUnit.MILLISECONDS); if (didAcquire) { SystemClock.sleep(1); // This is to allow the IBinder thread to exit before we continue, allowing easier - // understanding of the sequence of events. + // understanding of the sequence of events. // success } else { - LOG.error("Timeout waiting for descriptor write operation to complete"); + aapsLogger.error(LTag.PUMPBTCOMM, "Timeout waiting for descriptor write operation to complete"); timedOut = true; } } catch (InterruptedException e) { - LOG.error("Interrupted while waiting for descriptor write operation to complete"); + aapsLogger.error(LTag.PUMPBTCOMM, "Interrupted while waiting for descriptor write operation to complete"); interrupted = true; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java index be6cfb3e2d..f8d1909bad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java @@ -2,12 +2,12 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data; import org.joda.time.LocalDateTime; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by andy on 5/19/18. @@ -26,7 +26,7 @@ public class RLHistoryItem { public RLHistoryItem(RileyLinkServiceState serviceState, RileyLinkError errorCode, - RileyLinkTargetDevice targetDevice) { + RileyLinkTargetDevice targetDevice) { this.targetDevice = targetDevice; this.dateTime = new LocalDateTime(); this.serviceState = serviceState; @@ -65,16 +65,16 @@ public class RLHistoryItem { } - public String getDescription() { + public String getDescription(ResourceHelper resourceHelper) { // TODO extend when we have Omnipod switch (this.source) { case RileyLink: - return "State: " + MainApp.gs(serviceState.getResourceId(targetDevice)) - + (this.errorCode == null ? "" : ", Error Code: " + errorCode); + return "State: " + resourceHelper.gs(serviceState.getResourceId(targetDevice)) + + (this.errorCode == null ? "" : ", Error Code: " + errorCode); case MedtronicPump: - return MainApp.gs(pumpDeviceState.getResourceId()); + return resourceHelper.gs(pumpDeviceState.getResourceId()); case MedtronicCommand: return medtronicCommandType.name(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java index e91ad59a30..f8f79c821a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java @@ -1,22 +1,20 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import android.os.Bundle; - -import androidx.fragment.app.Fragment; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import javax.inject.Inject; import dagger.android.support.DaggerFragment; @@ -24,9 +22,9 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; -import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by andy on 5/19/18. @@ -35,6 +33,7 @@ import info.nightscout.androidaps.utils.DateUtil; public class RileyLinkStatusHistoryFragment extends DaggerFragment implements RefreshableInterface { @Inject RileyLinkUtil rileyLinkUtil; + @Inject ResourceHelper resourceHelper; RecyclerView recyclerView; RecyclerViewAdapter recyclerViewAdapter; @@ -50,7 +49,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re recyclerView = (RecyclerView) rootView.findViewById(R.id.rileylink_history_list); recyclerView.setHasFixedSize(true); - llm = new LinearLayoutManager(getActivity().getApplicationContext()); + llm = new LinearLayoutManager(rootView.getContext()); recyclerView.setLayoutManager(llm); recyclerViewAdapter = new RecyclerViewAdapter(filteredHistoryList); @@ -76,7 +75,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re } - public static class RecyclerViewAdapter extends RecyclerView.Adapter { + public class RecyclerViewAdapter extends RecyclerView.Adapter { List historyList; @@ -111,11 +110,11 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re PumpDeviceState pumpState = item.getPumpDeviceState(); - if ((pumpState != null) && // - (pumpState == PumpDeviceState.Sleeping || // - pumpState == PumpDeviceState.Active || // - pumpState == PumpDeviceState.WakingUp // - )) + // + if ((pumpState == PumpDeviceState.Sleeping || // + pumpState == PumpDeviceState.Active || // + pumpState == PumpDeviceState.WakingUp // + )) return false; return true; @@ -139,7 +138,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re if (item != null) { holder.timeView.setText(DateUtil.dateAndTimeAndSecondsString(item.getDateTime().toDateTime().getMillis())); holder.typeView.setText(item.getSource().getDesc()); - holder.valueView.setText(item.getDescription()); + holder.valueView.setText(item.getDescription(resourceHelper)); } } @@ -155,7 +154,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re super.onAttachedToRecyclerView(recyclerView); } - static class HistoryViewHolder extends RecyclerView.ViewHolder { + class HistoryViewHolder extends RecyclerView.ViewHolder { TextView timeView; TextView typeView; 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 b04abb7195..12add79f7a 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 @@ -11,8 +11,6 @@ import android.content.IntentFilter; import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import org.slf4j.Logger; - import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -23,9 +21,7 @@ import javax.inject.Inject; import dagger.android.DaggerBroadcastReceiver; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; @@ -50,8 +46,6 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { @Inject RileyLinkServiceData rileyLinkServiceData; @Inject ServiceTaskExecutor serviceTaskExecutor; - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - RileyLinkService serviceInstance; protected Map> broadcastIdentifiers = null; String deviceSpecificPrefix; @@ -98,11 +92,11 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { super.onReceive(context, intent); if (intent == null) { - LOG.error("onReceive: received null intent"); + aapsLogger.error("onReceive: received null intent"); } else { String action = intent.getAction(); if (action == null) { - LOG.error("onReceive: null action"); + aapsLogger.error("onReceive: null action"); } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Received Broadcast: " + action); @@ -112,7 +106,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { !processDeviceSpecificBroadcasts(action, intent) && // !processApplicationSpecificBroadcasts(action, intent) // ) { - LOG.error("Unhandled broadcast: action=" + action); + aapsLogger.error("Unhandled broadcast: action=" + action); } } } @@ -176,7 +170,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) { String RileylinkBLEAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); if (RileylinkBLEAddress.equals("")) { - LOG.error("No Rileylink BLE Address saved in app"); + aapsLogger.error("No Rileylink BLE Address saved in app"); } else { // showBusy("Configuring Service", 50); // rileyLinkBLE.findRileyLink(RileylinkBLEAddress); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java index 11a6de7a3d..d7eed28ef4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/WakeAndTuneTask.java @@ -4,13 +4,11 @@ import javax.inject.Inject; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState; -import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService; /** * Created by geoff on 7/16/16. 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 7db9fcfb5a..20c19c644c 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 @@ -20,14 +20,13 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; */ public class DateTimeUtil { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); - /** * DateTime is packed as long: yyyymmddHHMMss * * @param atechDateTime * @return */ + @Deprecated // use joda instead public static LocalDateTime toLocalDateTime(long atechDateTime) { int year = (int) (atechDateTime / 10000000000L); atechDateTime -= year * 10000000000L; @@ -49,8 +48,7 @@ public class DateTimeUtil { try { return new LocalDateTime(year, month, dayOfMonth, hourOfDay, minute, second); } catch (Exception ex) { - if (L.isEnabled(L.PUMPCOMM)) - LOG.error("Error creating LocalDateTime from values [atechDateTime={}, year={}, month={}, day={}, hour={}, minute={}, second={}]. Exception: {}", atechDateTime, year, month, dayOfMonth, hourOfDay, minute, second, ex.getMessage()); + //LOG.error("Error creating LocalDateTime from values [atechDateTime={}, year={}, month={}, day={}, hour={}, minute={}, second={}]. Exception: {}", atechDateTime, year, month, dayOfMonth, hourOfDay, minute, second, ex.getMessage()); //return null; throw ex; } @@ -63,6 +61,7 @@ public class DateTimeUtil { * @param atechDateTime * @return */ + @Deprecated // use joda instead public static GregorianCalendar toGregorianCalendar(long atechDateTime) { int year = (int) (atechDateTime / 10000000000L); atechDateTime -= year * 10000000000L; @@ -84,8 +83,7 @@ public class DateTimeUtil { try { return new GregorianCalendar(year, month - 1, dayOfMonth, hourOfDay, minute, second); } catch (Exception ex) { - if (L.isEnabled(L.PUMPCOMM)) - LOG.error("DateTimeUtil", String.format("Error creating GregorianCalendar from values [atechDateTime=%d, year=%d, month=%d, day=%d, hour=%d, minute=%d, second=%d]", atechDateTime, year, month, dayOfMonth, hourOfDay, minute, second)); + //LOG.error("DateTimeUtil", String.format("Error creating GregorianCalendar 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; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java index 21f496fcdc..03b42b730f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java @@ -5,7 +5,6 @@ import android.content.Context; import android.content.Intent; import android.location.LocationManager; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.utils.alertDialogs.OKDialog; @@ -44,7 +43,7 @@ public class LocationHelper { } // Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533 - OKDialog.showConfirmation(parent, MainApp.gs(R.string.location_not_found_title), MainApp.gs(R.string.location_not_found_message), () -> { + OKDialog.showConfirmation(parent, parent.getString(R.string.location_not_found_title), parent.getString(R.string.location_not_found_message), () -> { parent.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); }); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java index 2d7252cb7c..2a7ffa2ce4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.medtronic.dialog; import android.os.Bundle; -import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -12,10 +11,14 @@ import android.widget.TextView; import java.util.ArrayList; import java.util.List; +import javax.inject.Inject; + +import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by andy on 5/19/18. @@ -26,7 +29,9 @@ import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; */ // TODO needs to be implemented -public class RileyLinkStatusDeviceMedtronic extends Fragment implements RefreshableInterface { +public class RileyLinkStatusDeviceMedtronic extends DaggerFragment implements RefreshableInterface { + + @Inject ResourceHelper resourceHelper; // @BindView(R.id.rileylink_history_list) ListView listView; @@ -150,7 +155,7 @@ public class RileyLinkStatusDeviceMedtronic extends Fragment implements Refresha RLHistoryItem item = historyItemList.get(i); viewHolder.itemTime.setText(StringUtil.toDateTimeString(item.getDateTime())); viewHolder.itemSource.setText("Riley Link"); // for now - viewHolder.itemDescription.setText(item.getDescription()); + viewHolder.itemDescription.setText(item.getDescription(resourceHelper)); return view; } From 7b773ae80074e006663ad145c5589f0aad7b8e37 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 23:32:54 +0200 Subject: [PATCH 19/23] remove unused test --- .../comm/history/pump/MedtronicPumpHistoryDecoderUTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java index 3233d4e1e4..0420dba922 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; */ @Ignore public class MedtronicPumpHistoryDecoderUTest { - +/* MedtronicPumpHistoryDecoder decoder = new MedtronicPumpHistoryDecoder(); @@ -152,5 +152,5 @@ public class MedtronicPumpHistoryDecoderUTest { System.out.println("Record: " + phe); } - +*/ } From a2ebcb5ff070a677a343e31ab7176c2e8f347bde Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 27 Apr 2020 23:55:06 +0200 Subject: [PATCH 20/23] remove some static dependencies --- .../info/nightscout/androidaps/MainApp.java | 10 --- .../androidaps/db/CareportalEvent.java | 3 +- .../info/nightscout/androidaps/db/TDD.java | 25 ++++--- .../androidaps/dialogs/CareDialog.kt | 3 +- .../Dialogs/NewNSTreatmentDialog.java | 5 +- .../fragments/TreatmentsCareportalFragment.kt | 5 +- .../androidaps/utils/NumberPicker.java | 17 ++--- .../androidaps/utils/ToastUtils.java | 15 ++--- .../androidaps/utils/Translator.java | 65 ------------------- .../nightscout/androidaps/utils/Translator.kt | 44 +++++++++++++ .../androidaps/utils/stats/TddCalculator.kt | 4 +- 11 files changed, 78 insertions(+), 118 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/utils/Translator.java create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/Translator.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index d3701c94b0..e39516934f 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -217,16 +217,6 @@ public class MainApp extends DaggerApplication { return sResources.getString(id, args); } - @Deprecated - public static int gc(@ColorRes int id) { - return ContextCompat.getColor(instance(), id); - } - - @Deprecated - public static Resources resources() { - return sResources; - } - @Deprecated public static MainApp instance() { return sInstance; diff --git a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java index db05730aea..bfe24a008b 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java +++ b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java @@ -42,6 +42,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval { @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; @Inject AAPSLogger aapsLogger; + @Inject Translator translator; @DatabaseField(id = true) public long date; @@ -227,7 +228,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval { } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } - return Translator.translate(eventType); + return translator.translate(eventType); } public String getNotes() { diff --git a/app/src/main/java/info/nightscout/androidaps/db/TDD.java b/app/src/main/java/info/nightscout/androidaps/db/TDD.java index 3b4727a100..8d6a2e2576 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TDD.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TDD.java @@ -3,15 +3,12 @@ package info.nightscout.androidaps.db; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.Locale; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** * Created by mike on 20.09.2017. @@ -20,7 +17,6 @@ import info.nightscout.androidaps.utils.DateUtil; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS) public class TDD { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; @@ -35,14 +31,15 @@ public class TDD { public double total; - public double getTotal(){ - return (total > 0d) ? total:(bolus+basal); + public double getTotal() { + return (total > 0d) ? total : (bolus + basal); } - public TDD() { } + public TDD() { + } - public TDD(long date, double bolus, double basal, double total){ + public TDD(long date, double bolus, double basal, double total) { this.date = date; this.bolus = bolus; this.basal = basal; @@ -61,11 +58,11 @@ public class TDD { ']'; } - public String toText() { - return MainApp.gs(R.string.tddformat, DateUtil.dateStringShort(date), total, bolus, basal); + public String toText(ResourceHelper resourceHelper) { + return resourceHelper.gs(R.string.tddformat, DateUtil.dateStringShort(date), total, bolus, basal); } - public String toText(int days) { - return MainApp.gs(R.string.tddformat, String.format("%d ", days) + MainApp.gs(R.string.days), total, bolus, basal); + public String toText(ResourceHelper resourceHelper, int days) { + return resourceHelper.gs(R.string.tddformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolus, basal); } } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index 3ca03ead97..e561cb0890 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -36,6 +36,7 @@ class CareDialog : DialogFragmentWithDate() { @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var translator: Translator enum class EventType { BGCHECK, @@ -149,7 +150,7 @@ class CareDialog : DialogFragmentWithDate() { actions_care_sensor.isChecked -> "Sensor" else -> "Manual" } - actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + translator.translate(type)) actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, actions_care_bg.value) + " " + resourceHelper.gs(unitResId)) json.put("glucose", actions_care_bg.value) json.put("glucoseType", type) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java index f155d3e3f2..0c7dd11e83 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java @@ -78,6 +78,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O @Inject ActivePluginProvider activePlugin; @Inject TreatmentsPlugin treatmentsPlugin; @Inject HardLimits hardLimits; + @Inject Translator translator; private static OptionsToShow options; private static @StringRes int event; @@ -623,7 +624,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O if (data.has("glucoseType")) { ret += resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype); ret += ": "; - ret += Translator.translate(JsonHelper.safeGetString(data, "glucoseType", "")); + ret += translator.translate(JsonHelper.safeGetString(data, "glucoseType", "")); ret += "\n"; } if (data.has("carbs")) { @@ -712,7 +713,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O private void confirmNSTreatmentCreation() { final JSONObject data = gatherData(); - OKDialog.showConfirmation(getContext(), Translator.translate(JsonHelper.safeGetString(data, "eventType", resourceHelper.gs(R.string.overview_treatment_label))), buildConfirmText(data), () -> NSUpload.createNSTreatment(data, profileStore, profileFunction, eventTime.getTime())); + OKDialog.showConfirmation(getContext(), translator.translate(JsonHelper.safeGetString(data, "eventType", resourceHelper.gs(R.string.overview_treatment_label))), buildConfirmText(data), () -> NSUpload.createNSTreatment(data, profileStore, profileFunction, eventTime.getTime())); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt index 956da1c30c..d7a5e99496 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt @@ -37,6 +37,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var translator: Translator override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -108,7 +109,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { holder.date.text = DateUtil.dateAndTimeString(careportalEvent.date) holder.duration.text = if (careportalEvent.durationInMsec() == 0L) "" else DateUtil.niceTimeScalar(careportalEvent.durationInMsec(), resourceHelper) holder.note.text = careportalEvent.notes - holder.type.text = Translator.translate(careportalEvent.eventType) + holder.type.text = translator.translate(careportalEvent.eventType) holder.remove.tag = careportalEvent } @@ -129,7 +130,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { remove.setOnClickListener { v: View -> val careportalEvent = v.tag as CareportalEvent activity?.let { activity -> - val text = resourceHelper.gs(R.string.careportal_newnstreatment_eventtype) + ": " + Translator.translate(careportalEvent.eventType) + "\n" + + val text = resourceHelper.gs(R.string.careportal_newnstreatment_eventtype) + ": " + translator.translate(careportalEvent.eventType) + "\n" + resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + careportalEvent.notes + "\n" + resourceHelper.gs(R.string.date) + ": " + DateUtil.dateAndTimeString(careportalEvent.date) OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/NumberPicker.java b/app/src/main/java/info/nightscout/androidaps/utils/NumberPicker.java index 7ffabaec82..775582473e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/NumberPicker.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/NumberPicker.java @@ -5,7 +5,6 @@ import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; -import android.text.method.DigitsKeyListener; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; @@ -15,24 +14,18 @@ import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.text.NumberFormat; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; /** * Created by mike on 28.06.2016. */ public class NumberPicker extends LinearLayout implements View.OnKeyListener, View.OnTouchListener, View.OnClickListener { - private static Logger log = StacktraceLoggerWrapper.getLogger(NumberPicker.class); public interface OnValueChangedListener { void onValueChanged(double value); @@ -172,14 +165,14 @@ public class NumberPicker extends LinearLayout implements View.OnKeyListener, value = SafeParse.stringToDouble(editText.getText().toString()); if (value > maxValue) { value = maxValue; - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.youareonallowedlimit)); + ToastUtils.showToastInUiThread(getContext(), getContext().getString(R.string.youareonallowedlimit)); updateEditText(); if (okButton != null) okButton.setVisibility(VISIBLE); } if (value < minValue) { value = minValue; - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.youareonallowedlimit)); + ToastUtils.showToastInUiThread(getContext(), getContext().getString(R.string.youareonallowedlimit)); updateEditText(); if (okButton != null) okButton.setVisibility(VISIBLE); @@ -244,7 +237,7 @@ public class NumberPicker extends LinearLayout implements View.OnKeyListener, if (value > maxValue) { value = maxValue; callValueChangedListener(); - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.youareonallowedlimit)); + ToastUtils.showToastInUiThread(getContext(), getContext().getString(R.string.youareonallowedlimit)); stopUpdating(); } updateEditText(); @@ -255,7 +248,7 @@ public class NumberPicker extends LinearLayout implements View.OnKeyListener, if (value < minValue) { value = minValue; callValueChangedListener(); - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.youareonallowedlimit)); + ToastUtils.showToastInUiThread(getContext(), getContext().getString(R.string.youareonallowedlimit)); stopUpdating(); } updateEditText(); @@ -275,7 +268,7 @@ public class NumberPicker extends LinearLayout implements View.OnKeyListener, private void startUpdating(boolean inc) { if (mUpdater != null) { - log.debug("Another executor is still active"); + //log.debug("Another executor is still active"); return; } mUpdater = Executors.newSingleThreadScheduledExecutor(); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java b/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java index 26062011f6..ec165e4ba5 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java @@ -14,7 +14,6 @@ import android.widget.Toast; import androidx.annotation.DrawableRes; import androidx.appcompat.view.ContextThemeWrapper; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -30,20 +29,20 @@ public class ToastUtils { } public static void infoToast(final Context ctx, final String string) { - graphicalToast(ctx, string, R.drawable.ic_toast_info,false); + graphicalToast(ctx, string, R.drawable.ic_toast_info, false); } public static void okToast(final Context ctx, final String string) { - graphicalToast(ctx, string, R.drawable.ic_toast_check,false); + graphicalToast(ctx, string, R.drawable.ic_toast_check, false); } public static void errorToast(final Context ctx, final String string) { - graphicalToast(ctx, string, R.drawable.ic_toast_error,false); + graphicalToast(ctx, string, R.drawable.ic_toast_error, false); } } public static void showToastInUiThread(final Context ctx, final int stringId) { - showToastInUiThread(ctx, MainApp.gs(stringId)); + showToastInUiThread(ctx, ctx.getString(stringId)); } public static void warnToast(final Context ctx, final String string) { @@ -70,7 +69,7 @@ public class ToastUtils { public static void graphicalToast(final Context ctx, final String string, @DrawableRes int iconId, boolean isShort) { Handler mainThread = new Handler(Looper.getMainLooper()); mainThread.post(() -> { - View toastRoot =LayoutInflater.from(new ContextThemeWrapper(ctx, R.style.AppTheme)).inflate(R.layout.toast, null); + View toastRoot = LayoutInflater.from(new ContextThemeWrapper(ctx, R.style.AppTheme)).inflate(R.layout.toast, null); TextView toastMessage = toastRoot.findViewById(android.R.id.message); toastMessage.setText(string); @@ -86,9 +85,7 @@ public class ToastUtils { public static void showToastInUiThread(final Context ctx, final String string) { Handler mainThread = new Handler(Looper.getMainLooper()); - mainThread.post(() -> { - Toast.makeText(ctx, string, Toast.LENGTH_SHORT).show(); - }); + mainThread.post(() -> Toast.makeText(ctx, string, Toast.LENGTH_SHORT).show()); } public static void showToastInUiThread(final Context ctx, final RxBusWrapper rxBus, diff --git a/app/src/main/java/info/nightscout/androidaps/utils/Translator.java b/app/src/main/java/info/nightscout/androidaps/utils/Translator.java deleted file mode 100644 index e25c083a7b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/Translator.java +++ /dev/null @@ -1,65 +0,0 @@ -package info.nightscout.androidaps.utils; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; - -/** - * Created by mike on 15.07.2016. - */ -public class Translator { - - public static String translate(String text) { - switch (text) { - - case "BG Check": - return MainApp.gs(R.string.careportal_bgcheck); - case "Snack Bolus": - return MainApp.gs(R.string.careportal_snackbolus); - case "Meal Bolus": - return MainApp.gs(R.string.careportal_mealbolus); - case "Correction Bolus": - return MainApp.gs(R.string.careportal_correctionbolus); - case "Carb Correction": - return MainApp.gs(R.string.careportal_carbscorrection); - case "Combo Bolus": - return MainApp.gs(R.string.careportal_combobolus); - case "Announcement": - return MainApp.gs(R.string.careportal_announcement); - case "Note": - return MainApp.gs(R.string.careportal_note); - case "Question": - return MainApp.gs(R.string.careportal_question); - case "Exercise": - return MainApp.gs(R.string.careportal_exercise); - case "Site Change": - return MainApp.gs(R.string.careportal_pumpsitechange); - case "Pump Battery Change": - return MainApp.gs(R.string.careportal_pumpbatterychange); - case "Sensor Start": - return MainApp.gs(R.string.careportal_cgmsensorstart); - case "Sensor Change": - return MainApp.gs(R.string.careportal_cgmsensorinsert); - case "Insulin Change": - return MainApp.gs(R.string.careportal_insulincartridgechange); - case "Temp Basal Start": - return MainApp.gs(R.string.careportal_tempbasalstart); - case "Temp Basal End": - return MainApp.gs(R.string.careportal_tempbasalend); - case "Profile Switch": - return MainApp.gs(R.string.careportal_profileswitch); - case "Temporary Target": - return MainApp.gs(R.string.careportal_temporarytarget); - case "Temporary Target Cancel": - return MainApp.gs(R.string.careportal_temporarytargetcancel); - case "OpenAPS Offline": - return MainApp.gs(R.string.careportal_openapsoffline); - case "Finger": - return MainApp.gs(R.string.glucosetype_finger); - case "Sensor": - return MainApp.gs(R.string.glucosetype_sensor); - case "Manual": - return MainApp.gs(R.string.manual); - } - return text; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/Translator.kt b/app/src/main/java/info/nightscout/androidaps/utils/Translator.kt new file mode 100644 index 0000000000..b68fb74194 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/Translator.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.utils + +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by mike on 15.07.2016. + */ +@Singleton +class Translator @Inject internal constructor( + private val resourceHelper: ResourceHelper +) { + + fun translate(text: String): String = + when (text) { + "BG Check" -> resourceHelper.gs(R.string.careportal_bgcheck) + "Snack Bolus" -> resourceHelper.gs(R.string.careportal_snackbolus) + "Meal Bolus" -> resourceHelper.gs(R.string.careportal_mealbolus) + "Correction Bolus" -> resourceHelper.gs(R.string.careportal_correctionbolus) + "Carb Correction" -> resourceHelper.gs(R.string.careportal_carbscorrection) + "Combo Bolus" -> resourceHelper.gs(R.string.careportal_combobolus) + "Announcement" -> resourceHelper.gs(R.string.careportal_announcement) + "Note" -> resourceHelper.gs(R.string.careportal_note) + "Question" -> resourceHelper.gs(R.string.careportal_question) + "Exercise" -> resourceHelper.gs(R.string.careportal_exercise) + "Site Change" -> resourceHelper.gs(R.string.careportal_pumpsitechange) + "Pump Battery Change" -> resourceHelper.gs(R.string.careportal_pumpbatterychange) + "Sensor Start" -> resourceHelper.gs(R.string.careportal_cgmsensorstart) + "Sensor Change" -> resourceHelper.gs(R.string.careportal_cgmsensorinsert) + "Insulin Change" -> resourceHelper.gs(R.string.careportal_insulincartridgechange) + "Temp Basal Start" -> resourceHelper.gs(R.string.careportal_tempbasalstart) + "Temp Basal End" -> resourceHelper.gs(R.string.careportal_tempbasalend) + "Profile Switch" -> resourceHelper.gs(R.string.careportal_profileswitch) + "Temporary Target" -> resourceHelper.gs(R.string.careportal_temporarytarget) + "Temporary Target Cancel" -> resourceHelper.gs(R.string.careportal_temporarytargetcancel) + "OpenAPS Offline" -> resourceHelper.gs(R.string.careportal_openapsoffline) + "Finger" -> resourceHelper.gs(R.string.glucosetype_finger) + "Sensor" -> resourceHelper.gs(R.string.glucosetype_sensor) + "Manual" -> resourceHelper.gs(R.string.manual) + else -> resourceHelper.gs(R.string.unknown) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 247d4c22d4..0dc0cab7f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -92,14 +92,14 @@ class TddCalculator @Inject constructor( "" + resourceHelper.gs(R.string.tdd) + ":
" + toText(tdds) + "" + resourceHelper.gs(R.string.average) + ":
" + - averageTdd.toText(tdds.size()) + averageTdd.toText(resourceHelper, tdds.size()) ) } private fun toText(tdds: LongSparseArray): String { var t = "" for (i in 0 until tdds.size()) { - t += "${tdds.valueAt(i).toText()}
" + t += "${tdds.valueAt(i).toText(resourceHelper)}
" } return t } From bb39dd994a772efaeb017e4ce790c03588ee4d6d Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 28 Apr 2020 00:48:43 +0200 Subject: [PATCH 21/23] fix logging --- .../logging/AAPSLoggerProduction.kt | 10 +- .../pump/common/data/TempBasalPair.java | 2 - .../RileyLinkCommunicationManager.java | 46 +++---- .../service/RileyLinkBroadcastReceiver.java | 18 +-- .../tasks/InitializePumpManagerTask.java | 2 +- .../comm/MedtronicCommunicationManager.java | 130 +++++++++--------- .../medtronic/comm/MedtronicConverter.java | 12 +- .../comm/history/MedtronicHistoryDecoder.java | 10 +- .../comm/history/pump/PumpHistoryResult.java | 26 ++-- .../medtronic/comm/message/PumpMessage.java | 2 +- .../pump/medtronic/data/dto/BasalProfile.java | 32 ++--- .../medtronic/data/dto/BasalProfileEntry.java | 2 +- .../pump/medtronic/util/MedtronicUtil.java | 2 +- 13 files changed, 146 insertions(+), 148 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt index 6b3c9832a6..3b71419cab 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt @@ -26,7 +26,7 @@ class AAPSLoggerProduction : AAPSLogger { override fun debug(tag: LTag, format: String, vararg arguments: Any?) { if (L.isEnabled(tag.tag)) - LoggerFactory.getLogger(tag.tag).debug(stackLogMarker() + String.format(format, arguments)) + LoggerFactory.getLogger(tag.tag).debug(stackLogMarker() + format, arguments) } override fun warn(tag: LTag, message: String) { @@ -36,7 +36,7 @@ class AAPSLoggerProduction : AAPSLogger { } override fun warn(tag: LTag, format: String, vararg arguments: Any?) { - LoggerFactory.getLogger(tag.tag).warn(stackLogMarker() + String.format(format, arguments)) + LoggerFactory.getLogger(tag.tag).warn(stackLogMarker() + format, arguments) } override fun info(tag: LTag, message: String) { @@ -47,7 +47,7 @@ class AAPSLoggerProduction : AAPSLogger { } override fun info(tag: LTag, format: String, vararg arguments: Any?) { - LoggerFactory.getLogger(tag.tag).info(stackLogMarker() + String.format(format, arguments)) + LoggerFactory.getLogger(tag.tag).info(stackLogMarker() + format, arguments) } override fun error(tag: LTag, message: String) { @@ -65,7 +65,7 @@ class AAPSLoggerProduction : AAPSLogger { } override fun error(format: String, vararg arguments: Any?) { - LoggerFactory.getLogger(LTag.CORE.tag).error(stackLogMarker() + String.format(format, arguments)) + LoggerFactory.getLogger(LTag.CORE.tag).error(stackLogMarker() + format, arguments) } override fun error(tag: LTag, message: String, throwable: Throwable) { @@ -76,7 +76,7 @@ class AAPSLoggerProduction : AAPSLogger { override fun error(tag: LTag, format: String, vararg arguments: Any?) { if (L.isEnabled(tag.tag)) { - LoggerFactory.getLogger(tag.tag).error(stackLogMarker() + String.format(format, arguments)) + LoggerFactory.getLogger(tag.tag).error(stackLogMarker() + format, arguments) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java index 1e53734b5f..08ff0c3b49 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java @@ -9,8 +9,6 @@ import info.nightscout.androidaps.logging.L; public class TempBasalPair { - private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM); - @Expose protected double insulinRate = 0.0d; @Expose 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 f89e820671..4887d3d4a3 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 @@ -83,7 +83,7 @@ public abstract class RileyLinkCommunicationManager { // internal flag boolean showPumpMessages = true; if (showPumpMessages) { - aapsLogger.info(LTag.PUMPBTCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); + aapsLogger.info(LTag.PUMPCOMM, "Sent:" + ByteUtil.shortHexString(msg.getTxData())); } RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(injector, msg.getTxData()), @@ -96,7 +96,7 @@ public abstract class RileyLinkCommunicationManager { // Mark this as the last time we heard from the pump. rememberLastGoodDeviceCommunicationTime(); } else { - aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Response is invalid ! [interrupted={}, timeout={}, unknownCommand={}, invalidParam={}]", rfSpyResponse.wasInterrupted(), + aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Response is invalid ! [interrupted={}, timeout={}, unknownCommand={}, invalidParam={}]", rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout(), rfSpyResponse.isUnknownCommand(), rfSpyResponse.isInvalidParam()); if (rfSpyResponse.wasTimeout()) { @@ -106,7 +106,7 @@ public abstract class RileyLinkCommunicationManager { long diff = System.currentTimeMillis() - getPumpStatus().lastConnection; if (diff > ALLOWED_PUMP_UNREACHABLE) { - aapsLogger.warn(LTag.PUMPBTCOMM, "We reached max time that Pump can be unreachable. Starting Tuning."); + aapsLogger.warn(LTag.PUMPCOMM, "We reached max time that Pump can be unreachable. Starting Tuning."); serviceTaskExecutor.startTask(new WakeAndTuneTask(injector)); timeoutCount = 0; } @@ -119,7 +119,7 @@ public abstract class RileyLinkCommunicationManager { } if (showPumpMessages) { - aapsLogger.info(LTag.PUMPBTCOMM, "Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse(injector).getPayload())); + aapsLogger.info(LTag.PUMPCOMM, "Received:" + ByteUtil.shortHexString(rfSpyResponse.getRadioResponse(injector).getPayload())); } return response; @@ -156,18 +156,18 @@ public abstract class RileyLinkCommunicationManager { nextWakeUpRequired = 0L; if (System.currentTimeMillis() > nextWakeUpRequired) { - aapsLogger.info(LTag.PUMPBTCOMM, "Waking pump..."); + aapsLogger.info(LTag.PUMPCOMM, "Waking pump..."); byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 200, (byte) 0, (byte) 0, 25000, (byte) 0); - aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.info(LTag.PUMPCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(resp.getRaw())); // FIXME wakeUp successful !!!!!!!!!!!!!!!!!! nextWakeUpRequired = System.currentTimeMillis() + (receiverDeviceAwakeForMinutes * 60 * 1000); } else { - aapsLogger.debug(LTag.PUMPBTCOMM, "Last pump communication was recent, not waking pump."); + aapsLogger.debug(LTag.PUMPCOMM, "Last pump communication was recent, not waking pump."); } // long lastGoodPlus = getLastGoodReceiverCommunicationTime() + (receiverDeviceAwakeForMinutes * 60 * 1000); @@ -224,7 +224,7 @@ public abstract class RileyLinkCommunicationManager { private double scanForDevice(double[] frequencies) { - aapsLogger.info(LTag.PUMPBTCOMM, "Scanning for receiver ({})", receiverDeviceID); + aapsLogger.info(LTag.PUMPCOMM, "Scanning for receiver ({})", receiverDeviceID); wakeUp(receiverDeviceAwakeForMinutes, false); FrequencyScanResults results = new FrequencyScanResults(); @@ -241,7 +241,7 @@ public abstract class RileyLinkCommunicationManager { RFSpyResponse resp = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 0, (byte) 0, (byte) 0, 1250, (byte) 0); if (resp.wasTimeout()) { - aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: Failed to find pump at frequency {}", frequencies[i]); + aapsLogger.error(LTag.PUMPCOMM, "scanForPump: Failed to find pump at frequency {}", frequencies[i]); } else if (resp.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(injector); @@ -255,17 +255,17 @@ public abstract class RileyLinkCommunicationManager { trial.rssiList.add(rssi); trial.successes++; } else { - aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to parse radio response: " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.warn(LTag.PUMPCOMM, "Failed to parse radio response: " + ByteUtil.shortHexString(resp.getRaw())); trial.rssiList.add(-99); } } catch (RileyLinkCommunicationException rle) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.warn(LTag.PUMPCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); trial.rssiList.add(-99); } } else { - aapsLogger.error(LTag.PUMPBTCOMM, "scanForPump: raw response is " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.error(LTag.PUMPCOMM, "scanForPump: raw response is " + ByteUtil.shortHexString(resp.getRaw())); trial.rssiList.add(-99); } trial.tries++; @@ -297,10 +297,10 @@ public abstract class RileyLinkCommunicationManager { results.bestFrequencyMHz = bestTrial.frequencyMHz; if (bestTrial.successes > 0) { rfspy.setBaseFrequency(results.bestFrequencyMHz); - aapsLogger.debug(LTag.PUMPBTCOMM, "Best frequency found: " + results.bestFrequencyMHz); + aapsLogger.debug(LTag.PUMPCOMM, "Best frequency found: " + results.bestFrequencyMHz); return results.bestFrequencyMHz; } else { - aapsLogger.error(LTag.PUMPBTCOMM, "No pump response during scan."); + aapsLogger.error(LTag.PUMPCOMM, "No pump response during scan."); return 0.0; } } @@ -329,22 +329,22 @@ public abstract class RileyLinkCommunicationManager { RadioPacket pkt = new RadioPacket(injector, pumpMsgContent); RFSpyResponse resp = rfspy.transmitThenReceive(pkt, (byte) 0, (byte) 0, (byte) 0, (byte) 0, SCAN_TIMEOUT, (byte) 0); if (resp.wasTimeout()) { - aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: no pump response at frequency {}", freqMHz); + aapsLogger.warn(LTag.PUMPCOMM, "tune_tryFrequency: no pump response at frequency {}", freqMHz); } else if (resp.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(injector); try { radioResponse.init(resp.getRaw()); if (radioResponse.isValid()) { - aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz); + aapsLogger.warn(LTag.PUMPCOMM, "tune_tryFrequency: saw response level {} at frequency {}", radioResponse.rssi, freqMHz); return calculateRssi(radioResponse.rssi); } else { - aapsLogger.warn(LTag.PUMPBTCOMM, "tune_tryFrequency: invalid radio response:" + aapsLogger.warn(LTag.PUMPCOMM, "tune_tryFrequency: invalid radio response:" + ByteUtil.shortHexString(radioResponse.getPayload())); } } catch (RileyLinkCommunicationException e) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); + aapsLogger.warn(LTag.PUMPCOMM, "Failed to decode radio response: " + ByteUtil.shortHexString(resp.getRaw())); } } @@ -371,13 +371,13 @@ public abstract class RileyLinkCommunicationManager { } if (betterFrequency == 0.0) { // we've failed... caller should try a full scan for pump - aapsLogger.error(LTag.PUMPBTCOMM, "quickTuneForPump: failed to find pump"); + aapsLogger.error(LTag.PUMPCOMM, "quickTuneForPump: failed to find pump"); } else { rfspy.setBaseFrequency(betterFrequency); if (betterFrequency != startFrequencyMHz) { - aapsLogger.info(LTag.PUMPBTCOMM, "quickTuneForPump: new frequency is {}MHz", betterFrequency); + aapsLogger.info(LTag.PUMPCOMM, "quickTuneForPump: new frequency is {}MHz", betterFrequency); } else { - aapsLogger.info(LTag.PUMPBTCOMM, "quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); + aapsLogger.info(LTag.PUMPCOMM, "quickTuneForPump: pump frequency is the same: {}MHz", startFrequencyMHz); } } return betterFrequency; @@ -385,7 +385,7 @@ public abstract class RileyLinkCommunicationManager { private double quickTunePumpStep(double startFrequencyMHz, double stepSizeMHz) { - aapsLogger.info(LTag.PUMPBTCOMM, "Doing quick radio tune for receiver ({})", receiverDeviceID); + aapsLogger.info(LTag.PUMPCOMM, "Doing quick radio tune for receiver ({})", receiverDeviceID); wakeUp(false); int startRssi = tune_tryFrequency(startFrequencyMHz); double lowerFrequency = startFrequencyMHz - stepSizeMHz; @@ -423,7 +423,7 @@ public abstract class RileyLinkCommunicationManager { // Might still be zero, but that's fine. } double minutesAgo = (System.currentTimeMillis() - lastGoodReceiverCommunicationTime) / (1000.0 * 60.0); - aapsLogger.debug(LTag.PUMPBTCOMM, "Last good pump communication was " + minutesAgo + " minutes ago."); + aapsLogger.debug(LTag.PUMPCOMM, "Last good pump communication was " + minutesAgo + " minutes ago."); return lastGoodReceiverCommunicationTime; } 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 12add79f7a..f7d3b686e0 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 @@ -92,13 +92,13 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { super.onReceive(context, intent); if (intent == null) { - aapsLogger.error("onReceive: received null intent"); + aapsLogger.error(LTag.PUMPCOMM, "onReceive: received null intent"); } else { String action = intent.getAction(); if (action == null) { aapsLogger.error("onReceive: null action"); } else { - aapsLogger.debug(LTag.PUMPBTCOMM, "Received Broadcast: " + action); + aapsLogger.debug(LTag.PUMPCOMM, "Received Broadcast: " + action); if (!processBluetoothBroadcasts(action) && // !processRileyLinkBroadcasts(action, context) && // @@ -106,7 +106,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { !processDeviceSpecificBroadcasts(action, intent) && // !processApplicationSpecificBroadcasts(action, intent) // ) { - aapsLogger.error("Unhandled broadcast: action=" + action); + aapsLogger.error(LTag.PUMPCOMM, "Unhandled broadcast: action=" + action); } } } @@ -144,7 +144,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkReady)) { - aapsLogger.warn(LTag.PUMPBTCOMM, "MedtronicConst.Intents.RileyLinkReady"); + aapsLogger.warn(LTag.PUMPCOMM, "MedtronicConst.Intents.RileyLinkReady"); // sendIPCNotification(RT2Const.IPC.MSG_note_WakingPump); serviceInstance.rileyLinkBLE.enableNotifications(); @@ -155,16 +155,16 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { RileyLinkFirmwareVersion rlVersion = rileyLinkServiceData.firmwareVersion; // if (isLoggingEnabled()) - aapsLogger.debug(LTag.PUMPBTCOMM, "RfSpy version (BLE113): " + bleVersion); + aapsLogger.debug(LTag.PUMPCOMM, "RfSpy version (BLE113): " + bleVersion); serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion; // if (isLoggingEnabled()) - aapsLogger.debug(LTag.PUMPBTCOMM, "RfSpy Radio version (CC110): " + rlVersion.name()); + aapsLogger.debug(LTag.PUMPCOMM, "RfSpy Radio version (CC110): " + rlVersion.name()); serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; ServiceTask task = new InitializePumpManagerTask(injector, context); serviceTaskExecutor.startTask(task); - aapsLogger.info(LTag.PUMPBTCOMM, "Announcing RileyLink open For business"); + aapsLogger.info(LTag.PUMPCOMM, "Announcing RileyLink open For business"); return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) { @@ -193,13 +193,13 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { public boolean processBluetoothBroadcasts(String action) { if (action.equals(RileyLinkConst.Intents.BluetoothConnected)) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Bluetooth - Connected"); + aapsLogger.debug(LTag.PUMPCOMM, "Bluetooth - Connected"); serviceTaskExecutor.startTask(new DiscoverGattServicesTask(injector)); return true; } else if (action.equals(RileyLinkConst.Intents.BluetoothReconnected)) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Bluetooth - Reconnecting"); + aapsLogger.debug(LTag.PUMPCOMM, "Bluetooth - Reconnecting"); serviceInstance.bluetoothInit(); serviceTaskExecutor.startTask(new DiscoverGattServicesTask(injector, true)); 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 ff683a665a..d97399e6a1 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 @@ -69,7 +69,7 @@ public class InitializePumpManagerTask extends ServiceTask { rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady); - aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to {} MHz", lastGoodFrequency); + aapsLogger.info(LTag.PUMPCOMM, "Setting radio frequency to {} MHz", lastGoodFrequency); rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency); 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 37de1fa7f6..348110c671 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 @@ -118,7 +118,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager for (int retry = 0; retry < 5; retry++) { - aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : "")); + aapsLogger.debug(LTag.PUMPCOMM, "isDeviceReachable. Waking pump... " + (retry != 0 ? " (retry " + retry + ")" : "")); boolean connected = connectToDevice(); @@ -152,10 +152,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(injector, pumpMsgContent), (byte) 0, (byte) 200, (byte) 0, (byte) 0, 25000, (byte) 0); - aapsLogger.info(LTag.PUMPBTCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + aapsLogger.info(LTag.PUMPCOMM, "wakeup: raw response is " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); if (rfSpyResponse.wasTimeout()) { - aapsLogger.error(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to find pump (timeout)."); + aapsLogger.error(LTag.PUMPCOMM, "isDeviceReachable. Failed to find pump (timeout)."); } else if (rfSpyResponse.looksLikeRadioPacket()) { RadioResponse radioResponse = new RadioResponse(injector); @@ -168,7 +168,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload(), PumpMessage.class); if (!pumpResponse.isValid()) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), + aapsLogger.warn(LTag.PUMPCOMM, "Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), rfSpyResponse.wasTimeout()); } else { @@ -183,7 +183,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager medtronicUtil.setMedtronicPumpModel(pumpModel); } - aapsLogger.debug(LTag.PUMPBTCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, + aapsLogger.debug(LTag.PUMPCOMM, "isDeviceReachable. PumpModel is {} - Valid: {} (rssi={})", pumpModel.name(), valid, radioResponse.rssi); if (valid) { @@ -204,17 +204,17 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } else { - aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to parse radio response: " + aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Failed to parse radio response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } } catch (RileyLinkCommunicationException e) { - aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Failed to decode radio response: " + aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Failed to decode radio response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } } else { - aapsLogger.warn(LTag.PUMPBTCOMM, "isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); + aapsLogger.warn(LTag.PUMPCOMM, "isDeviceReachable. Unknown response: " + ByteUtil.shortHexString(rfSpyResponse.getRaw())); } return false; @@ -230,7 +230,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private PumpMessage runCommandWithArgs(PumpMessage msg) throws RileyLinkCommunicationException { if (debugSetCommands) - aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Args: "); + aapsLogger.debug(LTag.PUMPCOMM, "Run command with Args: "); PumpMessage rval; PumpMessage shortMessage = makePumpMessage(msg.commandType, new CarelinkShortMessageBody(new byte[]{0})); @@ -238,15 +238,15 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage shortResponse = sendAndListen(shortMessage); if (shortResponse.commandType == MedtronicCommandType.CommandACK) { if (debugSetCommands) - aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Args: Got ACK response"); + aapsLogger.debug(LTag.PUMPCOMM, "Run command with Args: Got ACK response"); rval = sendAndListen(msg); if (debugSetCommands) - aapsLogger.debug(LTag.PUMPBTCOMM, "2nd Response: {}", rval); + aapsLogger.debug(LTag.PUMPCOMM, "2nd Response: {}", rval); return rval; } else { - aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithArgs: Pump did not ack Attention packet"); + aapsLogger.error(LTag.PUMPCOMM, "runCommandWithArgs: Pump did not ack Attention packet"); return new PumpMessage(aapsLogger, "No ACK after Attention packet."); } } @@ -255,7 +255,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private PumpMessage runCommandWithFrames(MedtronicCommandType commandType, List> frames) throws RileyLinkCommunicationException { - aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: {}", commandType.name()); + aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: {}", commandType.name()); PumpMessage rval = null; PumpMessage shortMessage = makePumpMessage(commandType, new CarelinkShortMessageBody(new byte[]{0})); @@ -263,11 +263,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage shortResponse = sendAndListen(shortMessage); if (shortResponse.commandType != MedtronicCommandType.CommandACK) { - aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithFrames: Pump did not ack Attention packet"); + aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ack Attention packet"); return new PumpMessage(aapsLogger, "No ACK after start message."); } else { - aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: Got ACK response for Attention packet"); + aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for Attention packet"); } int frameNr = 1; @@ -276,23 +276,23 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager byte[] frameData = medtronicUtil.createByteArray(frame); - // aapsLogger.debug(LTag.PUMPBTCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); + // aapsLogger.debug(LTag.PUMPCOMM,"Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(frameData)); rval = sendAndListen(msg); - // aapsLogger.debug(LTag.PUMPBTCOMM,"PumpResponse: " + rval); + // aapsLogger.debug(LTag.PUMPCOMM,"PumpResponse: " + rval); if (rval.commandType != MedtronicCommandType.CommandACK) { - aapsLogger.error(LTag.PUMPBTCOMM, "runCommandWithFrames: Pump did not ACK frame #{}", frameNr); + aapsLogger.error(LTag.PUMPCOMM, "runCommandWithFrames: Pump did not ACK frame #{}", frameNr); - aapsLogger.error(LTag.PUMPBTCOMM, "Run command with Frames FAILED (command={}, response={})", commandType.name(), + aapsLogger.error(LTag.PUMPCOMM, "Run command with Frames FAILED (command={}, response={})", commandType.name(), rval.toString()); return new PumpMessage(aapsLogger, "No ACK after frame #" + frameNr); } else { - aapsLogger.debug(LTag.PUMPBTCOMM, "Run command with Frames: Got ACK response for frame #{}", (frameNr)); + aapsLogger.debug(LTag.PUMPCOMM, "Run command with Frames: Got ACK response for frame #{}", (frameNr)); } frameNr++; @@ -311,7 +311,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (doWakeUpBeforeCommand) wakeUp(receiverDeviceAwakeForMinutes, false); - aapsLogger.debug(LTag.PUMPBTCOMM, "Current command: " + medtronicUtil.getCurrentCommand()); + aapsLogger.debug(LTag.PUMPCOMM, "Current command: " + medtronicUtil.getCurrentCommand()); medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Active); boolean doneWithError = false; @@ -323,8 +323,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage getHistoryMsg = makePumpMessage(MedtronicCommandType.GetHistoryData, new GetHistoryPageCarelinkMessageBody(pageNumber)); - aapsLogger.info(LTag.PUMPBTCOMM, "getPumpHistory: Page {}", pageNumber); - // aapsLogger.info(LTag.PUMPBTCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); + aapsLogger.info(LTag.PUMPCOMM, "getPumpHistory: Page {}", pageNumber); + // aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): "+ByteUtil.shortHexString(getHistoryMsg.getTxData())); // Ask the pump to transfer history (we get first frame?) PumpMessage firstResponse = null; @@ -339,7 +339,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager failed = false; break; } catch (RileyLinkCommunicationException e) { - aapsLogger.error(LTag.PUMPBTCOMM, "First call for PumpHistory failed (retry={})", retries); + aapsLogger.error(LTag.PUMPCOMM, "First call for PumpHistory failed (retry={})", retries); failed = true; } } @@ -349,7 +349,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return pumpTotalResult; } - // aapsLogger.info(LTag.PUMPBTCOMM,"getPumpHistoryPage("+pageNumber+"): " + ByteUtil.shortHexString(firstResponse.getContents())); + // aapsLogger.info(LTag.PUMPCOMM,"getPumpHistoryPage("+pageNumber+"): " + ByteUtil.shortHexString(firstResponse.getContents())); PumpMessage ackMsg = makePumpMessage(MedtronicCommandType.CommandACK, new PumpAckMessageBody()); GetHistoryPageCarelinkMessageBody currentResponse = new GetHistoryPageCarelinkMessageBody(firstResponse @@ -366,7 +366,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager && currentResponse.getFrameNumber() == expectedFrameNum) { // success! got a frame. if (frameData.length != 64) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Expected frame of length 64, got frame of length " + frameData.length); + aapsLogger.warn(LTag.PUMPCOMM, "Expected frame of length 64, got frame of length " + frameData.length); // but append it anyway? } // handle successful frame data @@ -376,7 +376,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager medtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, currentResponse.getFrameNumber()); - aapsLogger.info(LTag.PUMPBTCOMM, "getPumpHistory: Got frame {} of Page {}", currentResponse.getFrameNumber(), pageNumber); + aapsLogger.info(LTag.PUMPCOMM, "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++; @@ -385,16 +385,16 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } else { if (frameData == null) { - aapsLogger.error(LTag.PUMPBTCOMM, "null frame data, retrying"); + aapsLogger.error(LTag.PUMPCOMM, "null frame data, retrying"); } else if (currentResponse.getFrameNumber() != expectedFrameNum) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Expected frame number {}, received {} (retrying)", expectedFrameNum, + aapsLogger.warn(LTag.PUMPCOMM, "Expected frame number {}, received {} (retrying)", expectedFrameNum, currentResponse.getFrameNumber()); } else if (frameData.length == 0) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Frame has zero length, retrying"); + aapsLogger.warn(LTag.PUMPCOMM, "Frame has zero length, retrying"); } failures++; if (failures == 6) { - aapsLogger.error(LTag.PUMPBTCOMM, + aapsLogger.error(LTag.PUMPCOMM, "getPumpHistory: 6 failures in attempting to download frame {} of page {}, giving up.", expectedFrameNum, pageNumber); done = true; // failure completion. @@ -412,26 +412,26 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager nextMsg = sendAndListen(ackMsg); break; } catch (RileyLinkCommunicationException e) { - aapsLogger.error(LTag.PUMPBTCOMM, "Problem acknowledging frame response. (retry={})", retries); + aapsLogger.error(LTag.PUMPCOMM, "Problem acknowledging frame response. (retry={})", retries); } } if (nextMsg != null) currentResponse = new GetHistoryPageCarelinkMessageBody(nextMsg.getMessageBody().getTxData()); else { - aapsLogger.error(LTag.PUMPBTCOMM, "We couldn't acknowledge frame from pump, aborting operation."); + aapsLogger.error(LTag.PUMPCOMM, "We couldn't acknowledge frame from pump, aborting operation."); } } } if (rawHistoryPage.getLength() != 1024) { - aapsLogger.warn(LTag.PUMPBTCOMM, "getPumpHistory: short page. Expected length of 1024, found length of " + aapsLogger.warn(LTag.PUMPCOMM, "getPumpHistory: short page. Expected length of 1024, found length of " + rawHistoryPage.getLength()); doneWithError = true; } if (!rawHistoryPage.isChecksumOK()) { - aapsLogger.error(LTag.PUMPBTCOMM, "getPumpHistory: checksum is wrong"); + aapsLogger.error(LTag.PUMPCOMM, "getPumpHistory: checksum is wrong"); doneWithError = true; } @@ -444,11 +444,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager List medtronicHistoryEntries = medtronicPumpHistoryDecoder.processPageAndCreateRecords(rawHistoryPage); - aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); + aapsLogger.debug(LTag.PUMPCOMM, "getPumpHistory: Found {} history entries.", medtronicHistoryEntries.size()); pumpTotalResult.addHistoryEntries(medtronicHistoryEntries, pageNumber); - aapsLogger.debug(LTag.PUMPBTCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); + aapsLogger.debug(LTag.PUMPCOMM, "getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); if (pumpTotalResult.isSearchFinished()) { medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); @@ -559,7 +559,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager private Object sendAndGetResponseWithCheck(MedtronicCommandType commandType, byte[] bodyData) { - aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType); + aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: {}", commandType); for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { @@ -574,7 +574,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (dataResponse != null) { this.errorMessage = null; - aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), dataResponse); + aapsLogger.debug(LTag.PUMPCOMM, "Converted response for {} is {}.", commandType.name(), dataResponse); return dataResponse; } else { @@ -586,7 +586,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } catch (RileyLinkCommunicationException e) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.warn(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } @@ -599,7 +599,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (!response.isValid()) { String responseData = String.format("%s: Invalid response.", method); - aapsLogger.warn(LTag.PUMPBTCOMM, responseData); + aapsLogger.warn(LTag.PUMPCOMM, responseData); return responseData; } @@ -607,7 +607,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (contents != null) { if (contents.length >= expectedLength) { - aapsLogger.debug(LTag.PUMPBTCOMM, "{}: Content: {}", method, ByteUtil.shortHexString(contents)); + aapsLogger.debug(LTag.PUMPCOMM, "{}: Content: {}", method, ByteUtil.shortHexString(contents)); return null; } else { @@ -615,12 +615,12 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager "%s: Cannot return data. Data is too short [expected=%s, received=%s].", method, "" + expectedLength, "" + contents.length); - aapsLogger.warn(LTag.PUMPBTCOMM, responseData); + aapsLogger.warn(LTag.PUMPCOMM, responseData); return responseData; } } else { String responseData = String.format("%s: Cannot return data. Null response.", method); - aapsLogger.warn(LTag.PUMPBTCOMM, responseData); + aapsLogger.warn(LTag.PUMPCOMM, responseData); return responseData; } } @@ -652,7 +652,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager MedtronicCommandType commandType = MedtronicCommandType.GetBasalProfileSTD; - aapsLogger.debug(LTag.PUMPBTCOMM, "getDataFromPump: {}", commandType); + aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: {}", commandType); medtronicUtil.setCurrentCommand(commandType); @@ -670,8 +670,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage response = sendAndListen(msg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); -// aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent())); -// aapsLogger.debug(LTag.PUMPBTCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData())); +// aapsLogger.debug(LTag.PUMPCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getRawContent())); +// aapsLogger.debug(LTag.PUMPCOMM,"1st Response: " + HexDump.toHexStringDisplayable(response.getMessageBody().getTxData())); String check = checkResponseContent(response, commandType.commandDescription, 1); @@ -687,8 +687,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager response = sendAndListen(ackMsg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries)); -// aapsLogger.debug(LTag.PUMPBTCOMM,"{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent())); -// aapsLogger.debug(LTag.PUMPBTCOMM,"{} Response: {}", runs, +// aapsLogger.debug(LTag.PUMPCOMM,"{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent())); +// aapsLogger.debug(LTag.PUMPCOMM,"{} Response: {}", runs, // HexDump.toHexStringDisplayable(response2.getMessageBody().getTxData())); String check2 = checkResponseContent(response, commandType.commandDescription, 1); @@ -699,7 +699,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } else { this.errorMessage = check2; - aapsLogger.error(LTag.PUMPBTCOMM, "Error with response got GetProfile: " + check2); + aapsLogger.error(LTag.PUMPCOMM, "Error with response got GetProfile: " + check2); } } @@ -710,7 +710,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager BasalProfile basalProfile = (BasalProfile) medtronicConverter.convertResponse(medtronicPumpPlugin.getPumpDescription().pumpType, commandType, data); if (basalProfile != null) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); + aapsLogger.debug(LTag.PUMPCOMM, "Converted response for {} is {}.", commandType.name(), basalProfile); medtronicUtil.setCurrentCommand(null); medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); @@ -719,11 +719,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } } catch (RileyLinkCommunicationException e) { - aapsLogger.error(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.error(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } - aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading profile in max retries."); + aapsLogger.warn(LTag.PUMPCOMM, "Error reading profile in max retries."); medtronicUtil.setCurrentCommand(null); medtronicPumpStatus.setPumpDeviceState(PumpDeviceState.Sleeping); @@ -741,7 +741,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager int last = responseRaw.length - 1; - aapsLogger.debug(LTag.PUMPBTCOMM, "Length: " + data.length); + aapsLogger.debug(LTag.PUMPCOMM, "Length: " + data.length); if (data.length >= BasalProfile.MAX_RAW_DATA_SIZE) { return false; @@ -793,7 +793,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public Boolean setBolus(double units) { - aapsLogger.info(LTag.PUMPBTCOMM, "setBolus: " + units); + aapsLogger.info(LTag.PUMPCOMM, "setBolus: " + units); return setCommand(MedtronicCommandType.SetBolus, medtronicUtil.getBolusStrokes(units)); @@ -802,7 +802,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager public boolean setTBR(TempBasalPair tbr) { - aapsLogger.info(LTag.PUMPBTCOMM, "setTBR: " + tbr.getDescription()); + aapsLogger.info(LTag.PUMPCOMM, "setTBR: " + tbr.getDescription()); return setCommand(MedtronicCommandType.SetTemporaryBasal, tbr.getAsRawData()); } @@ -813,7 +813,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager GregorianCalendar gc = new GregorianCalendar(); gc.add(Calendar.SECOND, 5); - aapsLogger.info(LTag.PUMPBTCOMM, "setPumpTime: " + DateTimeUtil.toString(gc)); + aapsLogger.info(LTag.PUMPCOMM, "setPumpTime: " + DateTimeUtil.toString(gc)); int i = 1; byte[] data = new byte[8]; @@ -830,7 +830,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager data[i + 5] = (byte) (gc.get(Calendar.MONTH) + 1); data[i + 6] = (byte) gc.get(Calendar.DAY_OF_MONTH); - //aapsLogger.info(LTag.PUMPBTCOMM,"setPumpTime: Body: " + ByteUtil.getHex(data)); + //aapsLogger.info(LTag.PUMPCOMM,"setPumpTime: Body: " + ByteUtil.getHex(data)); return setCommand(MedtronicCommandType.SetRealTimeClock, data); @@ -846,7 +846,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager wakeUp(false); if (debugSetCommands) - aapsLogger.debug(LTag.PUMPBTCOMM, "{}: Body - {}", commandType.getCommandDescription(), + aapsLogger.debug(LTag.PUMPCOMM, "{}: Body - {}", commandType.getCommandDescription(), ByteUtil.getHex(body)); PumpMessage msg = makePumpMessage(commandType, new CarelinkLongMessageBody(body)); @@ -854,16 +854,16 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager PumpMessage pumpMessage = runCommandWithArgs(msg); if (debugSetCommands) - aapsLogger.debug(LTag.PUMPBTCOMM, "{}: {}", commandType.getCommandDescription(), pumpMessage.getResponseContent()); + aapsLogger.debug(LTag.PUMPCOMM, "{}: {}", commandType.getCommandDescription(), pumpMessage.getResponseContent()); if (pumpMessage.commandType == MedtronicCommandType.CommandACK) { return true; } else { - aapsLogger.warn(LTag.PUMPBTCOMM, "We received non-ACK response from pump: {}", pumpMessage.getResponseContent()); + aapsLogger.warn(LTag.PUMPCOMM, "We received non-ACK response from pump: {}", pumpMessage.getResponseContent()); } } catch (RileyLinkCommunicationException e) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.warn(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } } @@ -899,13 +899,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager return true; } catch (RileyLinkCommunicationException e) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); + aapsLogger.warn(LTag.PUMPCOMM, "Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1); } if (responseMessage != null) - aapsLogger.warn(LTag.PUMPBTCOMM, "Set Basal Profile: Invalid response: commandType={},rawData={}", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent())); + aapsLogger.warn(LTag.PUMPCOMM, "Set Basal Profile: Invalid response: commandType={},rawData={}", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent())); else - aapsLogger.warn(LTag.PUMPBTCOMM, "Set Basal Profile: Null response."); + aapsLogger.warn(LTag.PUMPCOMM, "Set Basal Profile: Null response."); } return false; 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 b1377a38af..5ad6c51ceb 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 @@ -46,12 +46,12 @@ public class MedtronicConverter { Object convertResponse(PumpType pumpType, MedtronicCommandType commandType, byte[] rawContent) { if ((rawContent == null || rawContent.length < 1) && commandType != MedtronicCommandType.PumpModel) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Content is empty or too short, no data to convert (type={},isNull={},length={})", + aapsLogger.warn(LTag.PUMPCOMM, "Content is empty or too short, no data to convert (type={},isNull={},length={})", commandType.name(), rawContent == null, rawContent == null ? "-" : rawContent.length); return null; } - aapsLogger.debug(LTag.PUMPBTCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent)); + aapsLogger.debug(LTag.PUMPCOMM, "Raw response before convert: " + ByteUtil.shortHexString(rawContent)); switch (commandType) { @@ -114,13 +114,13 @@ public class MedtronicConverter { private MedtronicDeviceType decodeModel(byte[] rawContent) { if ((rawContent == null || rawContent.length < 4)) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading PumpModel, returning Unknown_Device"); + aapsLogger.warn(LTag.PUMPCOMM, "Error reading PumpModel, returning Unknown_Device"); return MedtronicDeviceType.Unknown_Device; } String rawModel = StringUtil.fromBytes(ByteUtil.substring(rawContent, 1, 3)); MedtronicDeviceType pumpModel = MedtronicDeviceType.getByDescription(rawModel); - aapsLogger.debug(LTag.PUMPBTCOMM, "PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); + aapsLogger.debug(LTag.PUMPCOMM, "PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); if (pumpModel != MedtronicDeviceType.Unknown_Device) { if (!medtronicUtil.isModelSet()) { @@ -173,7 +173,7 @@ public class MedtronicConverter { float value = ByteUtil.toInt(rawData[startIdx], rawData[startIdx + 1]) / (1.0f * strokes); - aapsLogger.debug(LTag.PUMPBTCOMM, "Remaining insulin: " + value); + aapsLogger.debug(LTag.PUMPCOMM, "Remaining insulin: " + value); return value; } @@ -190,7 +190,7 @@ public class MedtronicConverter { LocalDateTime pumpTime = new LocalDateTime(year, month, day, hours, minutes, seconds); return pumpTime; } catch (IllegalFieldValueException e) { - aapsLogger.error(LTag.PUMPBTCOMM, + aapsLogger.error(LTag.PUMPCOMM, "decodeTime: Failed to parse pump time value: year=%d, month=%d, hours=%d, minutes=%d, seconds=%d", year, month, day, hours, minutes, seconds); return null; 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 ef810a2efc..450425b26c 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 @@ -62,7 +62,7 @@ public abstract class MedtronicHistoryDecoder i // } if (medtronicUtil.getMedtronicPumpModel() == null) { - aapsLogger.error(LTag.PUMPBTCOMM, "Device Type is not defined."); + aapsLogger.error(LTag.PUMPCOMM, "Device Type is not defined."); return byteList; } @@ -118,10 +118,10 @@ public abstract class MedtronicHistoryDecoder i StringUtil.appendToStringBuilder(sb, "" + unknownEntry.getKey(), ", "); } - aapsLogger.error(LTag.PUMPBTCOMM, "STATISTICS OF PUMP DECODE"); + aapsLogger.error(LTag.PUMPCOMM, "STATISTICS OF PUMP DECODE"); if (unknownOpCodes.size() > 0) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Unknown Op Codes: {}", sb.toString()); + aapsLogger.warn(LTag.PUMPCOMM, "Unknown Op Codes: {}", sb.toString()); } for (Map.Entry> entry : mapStatistics.entrySet()) { @@ -137,9 +137,9 @@ public abstract class MedtronicHistoryDecoder i String spaces = StringUtils.repeat(" ", 14 - entry.getKey().name().length()); - aapsLogger.error(LTag.PUMPBTCOMM, " {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(), sb.toString()); + aapsLogger.error(LTag.PUMPCOMM, " {}{} - {}. Elements: {}", entry.getKey().name(), spaces, entry.getValue().size(), sb.toString()); } else { - aapsLogger.error(LTag.PUMPBTCOMM, " {} - {}", entry.getKey().name(), entry.getValue().size()); + aapsLogger.error(LTag.PUMPCOMM, " {} - {}", entry.getKey().name(), entry.getValue().size()); } } } 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 4ddf73eafe..349ac1bf2a 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 @@ -31,16 +31,16 @@ public class PumpHistoryResult { /* * this.searchEntry = searchEntry; * this.searchType = SearchType.LastEntry; - * aapsLogger.debug(LTag.PUMPBTCOMM,"PumpHistoryResult. Search parameters: Last Entry: " + searchEntry.atechDateTime + " type=" + * aapsLogger.debug(LTag.PUMPCOMM,"PumpHistoryResult. Search parameters: Last Entry: " + searchEntry.atechDateTime + " type=" * + searchEntry.getEntryType().name()); */ this.searchDate = searchEntry.atechDateTime; this.searchType = SearchType.Date; - aapsLogger.debug(LTag.PUMPBTCOMM, "PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate); + aapsLogger.debug(LTag.PUMPCOMM, "PumpHistoryResult. Search parameters: Date(with searchEntry): " + targetDate); } else if (targetDate != null) { this.searchDate = targetDate; this.searchType = SearchType.Date; - aapsLogger.debug(LTag.PUMPBTCOMM, "PumpHistoryResult. Search parameters: Date: " + targetDate); + aapsLogger.debug(LTag.PUMPCOMM, "PumpHistoryResult. Search parameters: Date: " + targetDate); } // this.unprocessedEntries = new ArrayList<>(); @@ -50,7 +50,7 @@ public class PumpHistoryResult { public void addHistoryEntries(List entries, int page) { this.unprocessedEntries = entries; - //aapsLogger.debug(LTag.PUMPBTCOMM,"PumpHistoryResult. Unprocessed entries: {}", MedtronicUtil.getGsonInstance().toJson(entries)); + //aapsLogger.debug(LTag.PUMPCOMM,"PumpHistoryResult. Unprocessed entries: {}", MedtronicUtil.getGsonInstance().toJson(entries)); processEntries(); } @@ -62,47 +62,47 @@ public class PumpHistoryResult { switch (searchType) { case None: - //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. None search"); + //aapsLogger.debug(LTag.PUMPCOMM,"PE. None search"); this.validEntries.addAll(this.unprocessedEntries); break; case LastEntry: { - aapsLogger.debug(LTag.PUMPBTCOMM, "PE. Last entry search"); + aapsLogger.debug(LTag.PUMPCOMM, "PE. Last entry search"); //Collections.sort(this.unprocessedEntries, new PumpHistoryEntry.Comparator()); - aapsLogger.debug(LTag.PUMPBTCOMM, "PE. PumpHistoryResult. Search entry date: " + searchEntry.atechDateTime); + aapsLogger.debug(LTag.PUMPCOMM, "PE. PumpHistoryResult. Search entry date: " + searchEntry.atechDateTime); Long date = searchEntry.atechDateTime; for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) { if (unprocessedEntry.equals(searchEntry)) { - //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. Item found {}.", unprocessedEntry); + //aapsLogger.debug(LTag.PUMPCOMM,"PE. Item found {}.", unprocessedEntry); searchFinished = true; break; } - //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. Entry {} added.", unprocessedEntry); + //aapsLogger.debug(LTag.PUMPCOMM,"PE. Entry {} added.", unprocessedEntry); this.validEntries.add(unprocessedEntry); } } break; case Date: { - aapsLogger.debug(LTag.PUMPBTCOMM, "PE. Date search: Search date: {}", this.searchDate); + aapsLogger.debug(LTag.PUMPCOMM, "PE. Date search: Search date: {}", this.searchDate); for (PumpHistoryEntry unprocessedEntry : unprocessedEntries) { if (unprocessedEntry.atechDateTime == null || unprocessedEntry.atechDateTime == 0) { - aapsLogger.debug(LTag.PUMPBTCOMM, "PE. PumpHistoryResult. Search entry date: Entry with no date: {}", unprocessedEntry); + aapsLogger.debug(LTag.PUMPCOMM, "PE. PumpHistoryResult. Search entry date: Entry with no date: {}", unprocessedEntry); continue; } if (unprocessedEntry.isAfter(this.searchDate)) { this.validEntries.add(unprocessedEntry); } else { -// aapsLogger.debug(LTag.PUMPBTCOMM,"PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]", +// aapsLogger.debug(LTag.PUMPCOMM,"PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]", // DateTimeUtil.getYear(unprocessedEntry.atechDateTime), unprocessedEntry); if (DateTimeUtil.getYear(unprocessedEntry.atechDateTime) > 2015) olderEntries++; @@ -119,7 +119,7 @@ public class PumpHistoryResult { } // switch - //aapsLogger.debug(LTag.PUMPBTCOMM,"PE. Valid Entries: {}", validEntries); + //aapsLogger.debug(LTag.PUMPCOMM,"PE. Valid Entries: {}", validEntries); } 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 99712eb9bd..8c7eb0bcee 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 @@ -66,7 +66,7 @@ public class PumpMessage implements RLMessage { if (rxData.length > 4) { this.commandType = MedtronicCommandType.getByCode(rxData[4]); if (this.commandType == MedtronicCommandType.InvalidCommand) { - aapsLogger.error(LTag.PUMPBTCOMM, "PumpMessage - Unknown commandType " + rxData[4]); + aapsLogger.error(LTag.PUMPCOMM, "PumpMessage - Unknown commandType " + rxData[4]); } } if (rxData.length > 5) { 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 359663b22c..475066cb6c 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 @@ -68,7 +68,7 @@ public class BasalProfile { private boolean setRawData(byte[] data) { if (data == null) { - aapsLogger.error(LTag.PUMPBTCOMM,"setRawData: buffer is null!"); + aapsLogger.error(LTag.PUMPCOMM,"setRawData: buffer is null!"); return false; } @@ -91,7 +91,7 @@ public class BasalProfile { public boolean setRawDataFromHistory(byte[] data) { if (data == null) { - aapsLogger.error(LTag.PUMPBTCOMM,"setRawData: buffer is null!"); + aapsLogger.error(LTag.PUMPCOMM,"setRawData: buffer is null!"); return false; } @@ -116,13 +116,13 @@ public class BasalProfile { public void dumpBasalProfile() { - aapsLogger.debug(LTag.PUMPBTCOMM,"Basal Profile entries:"); + aapsLogger.debug(LTag.PUMPCOMM,"Basal Profile entries:"); List entries = getEntries(); for (int i = 0; i < entries.size(); i++) { BasalProfileEntry entry = entries.get(i); String startString = entry.startTime.toString("HH:mm"); // this doesn't work - aapsLogger.debug(LTag.PUMPBTCOMM,String.format("Entry %d, rate=%.3f (0x%02X), start=%s (0x%02X)", i + 1, entry.rate, + aapsLogger.debug(LTag.PUMPCOMM,String.format("Entry %d, rate=%.3f (0x%02X), start=%s (0x%02X)", i + 1, entry.rate, entry.rate_raw, startString, entry.startTime_raw)); } @@ -169,14 +169,14 @@ public class BasalProfile { BasalProfileEntry rval = new BasalProfileEntry(); List entries = getEntries(); if (entries.size() == 0) { - aapsLogger.warn(LTag.PUMPBTCOMM,String.format("getEntryForTime(%s): table is empty", + aapsLogger.warn(LTag.PUMPCOMM,String.format("getEntryForTime(%s): table is empty", when.toDateTime().toLocalTime().toString("HH:mm"))); return rval; } // Log.w(TAG,"Assuming first entry"); rval = entries.get(0); if (entries.size() == 1) { - aapsLogger.debug(LTag.PUMPBTCOMM,"getEntryForTime: Only one entry in profile"); + aapsLogger.debug(LTag.PUMPCOMM,"getEntryForTime: Only one entry in profile"); return rval; } @@ -186,17 +186,17 @@ public class BasalProfile { while (!done) { BasalProfileEntry entry = entries.get(i); if (DEBUG_BASALPROFILE) { - aapsLogger.debug(LTag.PUMPBTCOMM,String.format("Comparing 'now'=%s to entry 'start time'=%s", when.toDateTime().toLocalTime() + aapsLogger.debug(LTag.PUMPCOMM,String.format("Comparing 'now'=%s to entry 'start time'=%s", when.toDateTime().toLocalTime() .toString("HH:mm"), entry.startTime.toString("HH:mm"))); } if (localMillis >= entry.startTime.getMillisOfDay()) { rval = entry; if (DEBUG_BASALPROFILE) - aapsLogger.debug(LTag.PUMPBTCOMM,"Accepted Entry"); + aapsLogger.debug(LTag.PUMPCOMM,"Accepted Entry"); } else { // entry at i has later start time, keep older entry if (DEBUG_BASALPROFILE) - aapsLogger.debug(LTag.PUMPBTCOMM,"Rejected Entry"); + aapsLogger.debug(LTag.PUMPCOMM,"Rejected Entry"); done = true; } i++; @@ -205,7 +205,7 @@ public class BasalProfile { } } if (DEBUG_BASALPROFILE) { - aapsLogger.debug(LTag.PUMPBTCOMM,String.format("getEntryForTime(%s): Returning entry: rate=%.3f (%d), start=%s (%d)", when + aapsLogger.debug(LTag.PUMPCOMM,String.format("getEntryForTime(%s): Returning entry: rate=%.3f (%d), start=%s (%d)", when .toDateTime().toLocalTime().toString("HH:mm"), rval.rate, rval.rate_raw, rval.startTime.toString("HH:mm"), rval.startTime_raw)); } @@ -217,7 +217,7 @@ public class BasalProfile { List entries = new ArrayList<>(); if (mRawData == null || mRawData[2] == 0x3f) { - aapsLogger.warn(LTag.PUMPBTCOMM,"Raw Data is empty."); + aapsLogger.warn(LTag.PUMPCOMM,"Raw Data is empty."); return entries; // an empty list } boolean done = false; @@ -237,7 +237,7 @@ public class BasalProfile { try { entries.add(new BasalProfileEntry(aapsLogger, r, st)); } catch (Exception ex) { - aapsLogger.error(LTag.PUMPBTCOMM,"Error decoding basal profile from bytes: {}", ByteUtil.shortHexString(mRawData)); + aapsLogger.error(LTag.PUMPCOMM,"Error decoding basal profile from bytes: {}", ByteUtil.shortHexString(mRawData)); throw ex; } @@ -286,10 +286,10 @@ public class BasalProfile { try { entries = getEntries(); } catch (Exception ex) { - aapsLogger.error(LTag.PUMPBTCOMM,"============================================================================="); - aapsLogger.error(LTag.PUMPBTCOMM," Error generating entries. Ex.: " + ex, ex); - aapsLogger.error(LTag.PUMPBTCOMM," rawBasalValues: " + ByteUtil.shortHexString(this.getRawData())); - aapsLogger.error(LTag.PUMPBTCOMM,"============================================================================="); + aapsLogger.error(LTag.PUMPCOMM,"============================================================================="); + aapsLogger.error(LTag.PUMPCOMM," Error generating entries. Ex.: " + ex, ex); + aapsLogger.error(LTag.PUMPCOMM," rawBasalValues: " + ByteUtil.shortHexString(this.getRawData())); + aapsLogger.error(LTag.PUMPCOMM,"============================================================================="); //FabricUtil.createEvent("MedtronicBasalProfileGetByHourError", null); } 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 8622b0f00b..05d8eaaa16 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 @@ -52,7 +52,7 @@ public class BasalProfileEntry { try { startTime = new LocalTime(startTimeInterval / 2, (startTimeInterval % 2) * 30); } catch (Exception ex) { - aapsLogger.error(LTag.PUMPBTCOMM, + aapsLogger.error(LTag.PUMPCOMM, "Error creating BasalProfileEntry: startTimeInterval={}, startTime_raw={}, hours={}, rateStrokes={}", startTimeInterval, startTime_raw, startTimeInterval / 2, rateStrokes); throw ex; 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 e649ee1286..a4e7a51ec2 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 @@ -275,7 +275,7 @@ public class MedtronicUtil { byte[] payload = sendPayloadBuffer.array(); - aapsLogger.debug(LTag.PUMPBTCOMM, "buildCommandPayload [{}]", ByteUtil.shortHexString(payload)); + aapsLogger.debug(LTag.PUMPCOMM, "buildCommandPayload [{}]", ByteUtil.shortHexString(payload)); // int crc = computeCRC8WithPolynomial(payload, 0, payload.length - 1); From 789d520606abbd91819c6908da5b0927eb70f8a7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 28 Apr 2020 09:08:03 +0200 Subject: [PATCH 22/23] fix preference processing --- .../nightscout/androidaps/activities/MyPreferenceFragment.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 2d139ce378..b06276114d 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -279,7 +279,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } for (plugin in pluginStore.plugins) { - pref?.let { plugin.updatePreferenceSummary(it) } + pref?.let { pref-> pref.getKey()?.let { plugin.updatePreferenceSummary(pref) }} } val hmacPasswords = arrayOf( From 0aa8a4b270876b931adf2bd7c3cb0e07fd25b7b7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 28 Apr 2020 09:43:12 +0200 Subject: [PATCH 23/23] New Crowdin translations (#2584) * New translations protection.xml (Czech) * New translations protection.xml (German) * New translations validator.xml (German) * New translations strings.xml (German) * New translations strings.xml (German) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (German) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese) * New translations protection.xml (Portuguese) * New translations validator.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations protection.xml (Portuguese, Brazilian) * New translations validator.xml (Portuguese, Brazilian) * New translations validator.xml (Portuguese, Brazilian) * New translations validator.xml (Portuguese) * New translations strings.xml (Spanish) * New translations strings.xml (Spanish) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Bulgarian) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Portuguese) * New translations protection.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations protection.xml (Portuguese, Brazilian) * New translations strings.xml (German) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Slovak) * New translations protection.xml (Slovak) * New translations strings.xml (Slovak) * New translations validator.xml (Slovak) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations strings.xml (Russian) * New translations protection.xml (Russian) * New translations validator.xml (Russian) * New translations objectives.xml (Portuguese) * New translations objectives.xml (Portuguese, Brazilian) * New translations objectives.xml (German) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Russian) * New translations objectives.xml (Russian) * New translations strings.xml (Portuguese) * New translations strings.xml (Portuguese, Brazilian) * New translations objectives.xml (Portuguese) * New translations objectives.xml (Portuguese, Brazilian) * New translations objectives.xml (Russian) * New translations objectives.xml (German) * New translations strings.xml (German) * New translations objectives.xml (German) * New translations objectives.xml (Czech) * New translations objectives.xml (Russian) * New translations objectives.xml (Lithuanian) * New translations strings.xml (Lithuanian) * New translations strings.xml (Romanian) * New translations exam.xml (Lithuanian) * New translations strings.xml (Portuguese, Brazilian) * New translations strings.xml (Chinese Simplified) * New translations strings.xml (Turkish) * New translations validator.xml (Swedish) * New translations protection.xml (Swedish) * New translations objectives.xml (Swedish) * New translations strings.xml (Swedish) * New translations strings.xml (Slovak) * New translations strings.xml (Russian) * New translations strings.xml (Portuguese) * New translations strings.xml (Polish) * New translations strings.xml (Dutch) * New translations strings.xml (Lithuanian) * New translations strings.xml (French) * New translations strings.xml (Korean) * New translations strings.xml (Italian) * New translations strings.xml (Greek) * New translations strings.xml (German) * New translations strings.xml (Czech) * New translations strings.xml (Bulgarian) * New translations strings.xml (Afrikaans) * New translations strings.xml (Spanish) * New translations strings.xml (Slovak) * New translations strings.xml (Czech) * New translations objectives.xml (Portuguese) * New translations validator.xml (Italian) * New translations objectives.xml (Italian) * New translations objectives.xml (Bulgarian) * New translations strings.xml (Slovak) * New translations strings.xml (Czech) * New translations strings.xml (Italian) * New translations objectives.xml (Italian) * New translations protection.xml (Italian) * New translations validator.xml (Italian) * New translations strings.xml (Italian) * New translations strings.xml (German) * New translations strings.xml (Czech) * New translations strings.xml (German) * New translations strings.xml (Italian) * New translations strings.xml (Polish) * New translations strings.xml (Slovak) * New translations objectives.xml (Slovak) * New translations objectives.xml (Polish) * New translations protection.xml (Polish) * New translations strings.xml (Russian) * New translations strings.xml (Czech) * New translations strings.xml (Czech) * New translations strings.xml (German) * New translations strings.xml (Italian) * New translations strings.xml (Slovak) * New translations strings.xml (French) * New translations strings.xml (Portuguese) * New translations strings.xml (Russian) * New translations protection.xml (French) * New translations objectives.xml (French) * New translations validator.xml (French) --- app/src/main/res/values-af-rZA/strings.xml | 1 - app/src/main/res/values-bg-rBG/objectives.xml | 3 + app/src/main/res/values-bg-rBG/strings.xml | 5 +- app/src/main/res/values-cs-rCZ/objectives.xml | 2 + app/src/main/res/values-cs-rCZ/protection.xml | 16 ++ app/src/main/res/values-cs-rCZ/strings.xml | 19 ++- app/src/main/res/values-de-rDE/objectives.xml | 2 + app/src/main/res/values-de-rDE/protection.xml | 23 ++- app/src/main/res/values-de-rDE/strings.xml | 99 +++++++++++- app/src/main/res/values-de-rDE/validator.xml | 21 ++- app/src/main/res/values-el-rGR/strings.xml | 3 - app/src/main/res/values-es-rES/strings.xml | 56 ++++++- app/src/main/res/values-fr-rFR/objectives.xml | 2 + app/src/main/res/values-fr-rFR/protection.xml | 23 ++- app/src/main/res/values-fr-rFR/strings.xml | 104 ++++++++++++- app/src/main/res/values-fr-rFR/validator.xml | 21 ++- app/src/main/res/values-it-rIT/objectives.xml | 3 + app/src/main/res/values-it-rIT/protection.xml | 23 ++- app/src/main/res/values-it-rIT/strings.xml | 98 +++++++++++- app/src/main/res/values-it-rIT/validator.xml | 21 ++- app/src/main/res/values-ko-rKR/strings.xml | 3 - app/src/main/res/values-lt-rLT/exam.xml | 2 +- app/src/main/res/values-lt-rLT/objectives.xml | 25 +-- app/src/main/res/values-lt-rLT/strings.xml | 144 ++++++++++++------ app/src/main/res/values-nl-rNL/strings.xml | 3 - app/src/main/res/values-pl-rPL/objectives.xml | 3 + app/src/main/res/values-pl-rPL/protection.xml | 23 ++- app/src/main/res/values-pl-rPL/strings.xml | 13 +- app/src/main/res/values-pt-rBR/objectives.xml | 1 + app/src/main/res/values-pt-rBR/protection.xml | 23 ++- app/src/main/res/values-pt-rBR/strings.xml | 70 ++++++++- app/src/main/res/values-pt-rBR/validator.xml | 21 ++- app/src/main/res/values-pt-rPT/objectives.xml | 2 + app/src/main/res/values-pt-rPT/protection.xml | 23 ++- app/src/main/res/values-pt-rPT/strings.xml | 78 +++++++++- app/src/main/res/values-pt-rPT/validator.xml | 21 ++- app/src/main/res/values-ro-rRO/strings.xml | 3 - app/src/main/res/values-ru-rRU/objectives.xml | 2 + app/src/main/res/values-ru-rRU/protection.xml | 23 ++- app/src/main/res/values-ru-rRU/strings.xml | 100 +++++++++++- app/src/main/res/values-ru-rRU/validator.xml | 21 ++- app/src/main/res/values-sk-rSK/objectives.xml | 2 + app/src/main/res/values-sk-rSK/protection.xml | 23 ++- app/src/main/res/values-sk-rSK/strings.xml | 100 +++++++++++- app/src/main/res/values-sk-rSK/validator.xml | 21 ++- app/src/main/res/values-sv-rSE/objectives.xml | 2 + app/src/main/res/values-sv-rSE/protection.xml | 23 ++- app/src/main/res/values-sv-rSE/strings.xml | 87 ++++++++++- app/src/main/res/values-sv-rSE/validator.xml | 21 ++- app/src/main/res/values-tr-rTR/strings.xml | 1 - app/src/main/res/values-zh-rCN/strings.xml | 1 - 51 files changed, 1303 insertions(+), 127 deletions(-) diff --git a/app/src/main/res/values-af-rZA/strings.xml b/app/src/main/res/values-af-rZA/strings.xml index 506d2d824f..b05923bba0 100644 --- a/app/src/main/res/values-af-rZA/strings.xml +++ b/app/src/main/res/values-af-rZA/strings.xml @@ -103,7 +103,6 @@ Delta: Konfigurasie bouer Doelstellings - OpenAPS MA Oorsig Ns Profiel Maklike profiel diff --git a/app/src/main/res/values-bg-rBG/objectives.xml b/app/src/main/res/values-bg-rBG/objectives.xml index 633ff84c99..16339650fd 100644 --- a/app/src/main/res/values-bg-rBG/objectives.xml +++ b/app/src/main/res/values-bg-rBG/objectives.xml @@ -46,6 +46,9 @@ Код (request code): %1$s (отбележете всички правилни отговори) https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen Няма връзка с Интернет! Не може да се вземе времето Задачите не са изпълнени diff --git a/app/src/main/res/values-bg-rBG/strings.xml b/app/src/main/res/values-bg-rBG/strings.xml index d508c88e48..2811beea92 100644 --- a/app/src/main/res/values-bg-rBG/strings.xml +++ b/app/src/main/res/values-bg-rBG/strings.xml @@ -43,6 +43,7 @@ Писалки - За хората, които правят множество ежедневни инжекции ( интензифицирано лечение с писалки) За помпи, който все още не работят с AndroidAPS(Open Loop) Чувствителността се изчислява по същия начин като в Oref0, но можете да зададете времева рамка. Минимална въглехидрати абсорбция се изчислява от Макс време за усвояване на въглехидратите в опциите. + Чувствителността се изчислява за 8 или 24 назад в миналото, а въглехидрати (ако не са се абсорбирали) изчезват след изтичане на срока от настройките. Това е необходимо за изчисление на необявени хранения (UAM). Чувствителността се изчислява като среднопретеглена стойност от отклоненията. По-новите отклонения имат по-високо тегло. Минималната абсорбция на въглехидрати се изчислява от Време за макс усвояване на въглехидрати от опциите. Този алгоритъм е най-бързият при проследяването на промени в чувствителността. Получава данни за КЗ от модифицираното приложение на Eversense. Получава данни за КЗ от Glimp. @@ -105,7 +106,6 @@ Изменение (делта): Конфигурация Цели - OpenAPS МА Общ NS Профил Обикновен профил @@ -543,8 +543,6 @@ Разреши използването на Суперболус Разреши функцията суперболус в съветника. Не я разрешавайте докато не научите какво наистина прави. ТОВА МОЖЕ ДА СЪЗДАДЕ ОПАСНОСТ ОТ ПРЕДОЗИРАНЕ С ИНСУЛИН. Покажи статус светлини на началния екран - Покажи статус светлини с подробности на началния екран - Показвай подробни статус светлини за канула, инсулин, сензор, резервоар и батерията на началния екран. Ниво за аларма за останал инсулин в резервоара [Е] Критично ниво на останал инсулин в резервоар [Е] Аларма при заряд на батерия под [%] @@ -979,6 +977,7 @@ Внимание: Ако активирате и свържете с хардуерна помпа, AndroidAPS ще копира основните настройки от профила в помпата, като презапише съществуващата базова скорост, съхранявана на помпата. Уверете се, че имате правилните основни настройки в AndroidAPS. Ако не сте сигурни или не искате да презапишете основните настройки на помпата, натиснете Cancel и повторете превключването към помпата по-късно. Данните за лечението не са пълни Настройки за поддръжка + Имейл Брой логове за изпращане Поддръжка ПОДДР diff --git a/app/src/main/res/values-cs-rCZ/objectives.xml b/app/src/main/res/values-cs-rCZ/objectives.xml index b47865c3ef..bbebc9fc02 100644 --- a/app/src/main/res/values-cs-rCZ/objectives.xml +++ b/app/src/main/res/values-cs-rCZ/objectives.xml @@ -20,7 +20,9 @@ Jeden týden úspěšného používání s běžným příjmem sacharidů Povolení doplňkový funkcí pro každodenní použití, jako např. pokročilý jídelní asistent (AMA) Povolit další funkce pro běžné používání jako SMB + Povolení automatizace Přečíst si dokumentaci a zvýšit maximální IOB, aby mohlo SMB fungovat. Pro začátek se dá použít velikost běžného bolusu + 3x maximální denní bazál + Přečtěte si na wiki, jak automatizace funguje. Nejdříve nastavte pouze jednoduchá pravidla. Namísto provádění akcí nechte AAPS zobrazovat pouze oznámení. Pokud jste si jistí, že je automatizace je spuštěna v pravý čas, můžete oznámení nahradit prováděním akce. (https://androidaps.readdocs.io/en/latest/CROWDIN/cs/Usage/Automation.html) Glykémie dostupná v NS Stav pumpy dostupný v NS Ručně spuštěno diff --git a/app/src/main/res/values-cs-rCZ/protection.xml b/app/src/main/res/values-cs-rCZ/protection.xml index 07c76f4ff9..01ec1022d6 100644 --- a/app/src/main/res/values-cs-rCZ/protection.xml +++ b/app/src/main/res/values-cs-rCZ/protection.xml @@ -4,4 +4,20 @@ Položte prst na čtečku otisků prstů pro ověření vaší totožnosti Ochrana nastavení Ochrana aplikace + Ochrana bolusu + Hlavní heslo + Heslo pro nastavení + Heslo aplikace + Heslo pro bolus + Odemknout nastavení + Biometrie + Vlastní heslo + Bez ochrany + Ochrana + Hlavní heslo není nastaveno!\n\nProsím nastavte své hlavní heslo v Preferencích (%1$s → %2$s) + Heslo nastaveno! + Heslo není nastavené + Heslo nezměněno + Heslo vymazáno! + Zadejte heslo diff --git a/app/src/main/res/values-cs-rCZ/strings.xml b/app/src/main/res/values-cs-rCZ/strings.xml index 281a97be63..52cdbe4638 100644 --- a/app/src/main/res/values-cs-rCZ/strings.xml +++ b/app/src/main/res/values-cs-rCZ/strings.xml @@ -106,7 +106,6 @@ Rozdíl: Konfigurace Cíle - OpenAPS MA Přehled NS profil Jednoduchý profil @@ -585,8 +584,14 @@ Povolit superbolus Povolení superbolusu v kalkulátoru. Nepovolujte, dokud se nenaučíte, co to opravdu dělá. MŮŽE ZPŮSOBIT PŘEDÁVKOVÁNÍ INZULÍNEM PŘI NESPRÁVNÉM POUŽITÍ! Zobrazit stavové indikátory na domovské obrazovce - Zobrazit rozšířené stavové indikátory na domovské obrazovce - Povolí rozšířené stavové indikátory pro stáří kanyly, inzulínu, senzoru, zásobníku a baterie na domovské obrazovce. + Úroveň varování stáří kanyly [h] + Úroveň kritického stáří kanyly [h] + Úroveň varování stáří inzulínu [h] + Úroveň kritického stáří inzulínu [h] + Úroveň varování stáří senzoru [h] + Úroveň kritického stáří senzoru [h] + Úroveň varování stáří baterie [h] + Úroveň kritického varování stáří baterie [h] Úroveň varování stavu zásobníku [U] Úroveň kritického varování stavu zásobníku [U] Úroveň varování stavu baterie [%] @@ -1523,4 +1528,12 @@ Při odpojení Predikce Odchylka sklonu + Autorizace selhala + Absolutní inzulin + Hlavní heslo se používá pro šifrování zálohy a pro \"přebití\" zabezpečení v aplikaci. Dobře si ho zapamatujte nebo uložte na bezpečném místě. + Hesla se neshodují + Aktuální hlavní heslo + Stavové indikátory + Zkopírovat nastavení z NS + Zkopírovat nastavení NS (existuje-li)? diff --git a/app/src/main/res/values-de-rDE/objectives.xml b/app/src/main/res/values-de-rDE/objectives.xml index e094670b18..b9ea574d3e 100644 --- a/app/src/main/res/values-de-rDE/objectives.xml +++ b/app/src/main/res/values-de-rDE/objectives.xml @@ -20,8 +20,10 @@ Loope eine Woche tagsüber mit regelmäßiger Kohlenhydrat-Eingabe Aktiviere zusätzliche Funktionen für die Nutzung tagsüber wie z. B. den erweiterten Mahlzeitenassistenten (AMA) Aktiviere zusätzliche Funktionen für die Nutzung tagsüber wie z. B. SMB + Automatisierung aktivieren Lies das Wiki und erhöhe maxIOB, damit der SMB gut funktioniert. Ein guter Anfang ist die Formel maxIOB = durchschnittlicher Essensbolus + 3 x höchste Basalrate + Lies in den Docs wie Automatisierung funktioniert und erstelle dann eine erste einfache Regel. Verwende eine Benachrichtigung statt der tatsächlichen Aktion. Wenn die Automatisierung zum richtigen Zeitpunkt auslöst, ersetze die Benachrichtigung durch die gewünschte Aktion. (https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/Automation.html) BZ in Nightscout verfügbar Pumpen-Status in Nightscout verfügbar Manuelle Aktionen diff --git a/app/src/main/res/values-de-rDE/protection.xml b/app/src/main/res/values-de-rDE/protection.xml index 3ea04e700d..0c6f2dd337 100644 --- a/app/src/main/res/values-de-rDE/protection.xml +++ b/app/src/main/res/values-de-rDE/protection.xml @@ -1,2 +1,23 @@ - + + Authentifizierung erforderlich + Legen Deinen Finger auf den Fingerabdrucksensors, um Deine Identität zu bestätigen. + Schutz der Einstellungen + Schutz der App + Bolus-Schutz + Master-Passwort + Passwort für Einstellungen + Anwendungspasswort + Passwort für Boli + Einstellungen freischalten + Biometrisch + Benutzerdefiniertes Passwort + Kein Schutz + Schutz + Das Master-Passwort ist nicht festgelegt!\n\nLege Dein Master-Passwort bitte in en Einstellungen fest (%1$s → %2$s) + Passwort festgelegt! + Passwort nicht festgelegt + Passwort nicht geändert + Passwort gelöscht! + Passwort hier eingeben + diff --git a/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/values-de-rDE/strings.xml index 0418722968..db4a75a29c 100644 --- a/app/src/main/res/values-de-rDE/strings.xml +++ b/app/src/main/res/values-de-rDE/strings.xml @@ -43,6 +43,7 @@ Pumpen-Integration für Personen, die täglich mehrere Injektionen für ihre Diabetestherapie vornehmen Pumpen-Integration für Pumpen, die noch nicht über einen Treiber verfügen (Open Loop) Die Sensitivität wird genauso wie bei Oref0 berechnet, aber Du kannst dafür ein Zeitfenster bestimmen. Die minimale Kohlenhydrat-Absorptionsrate wird aus der maximalen Absorptionsdauer aus den Einstellungen abgeleitet. + Die Sensitivität wird aus den Daten der letzten 8 Stunden berechnet und Kohlenhydrate (falls nicht bereits absorbiert) werden nach der in den Einstellungen angegebenen Zeit als absorbiert betrachtet. Das Plugin bezieht Zeiträume, in denen UAM annimmt, dass Kohlenhydrate aktiv waren, nicht mit in die Berechnung ein. Die Sensitivität wird aus den Abweichungen errechnet. Dabei werden neuere Abweichungen stärker gewichtet als ältere. Die minimale Kohlenhydrat-Aufnahme wird aus der in den Präferenzen angegebenen maximalen Kohlenhydrat-Resorptionszeit abgeleitet. Dieser Algorithmus reagiert am schnellsten auf Änderungen der Empfindlichkeit. Empfange BZ-Werte von der gepatchten Eversense App. Empfange Blutzucker-Werte von Glimp. @@ -105,7 +106,6 @@ Delta: Konfiguration Zielsetzungen - OpenAPS MA Übersicht Nightscout-Profil Einfaches Profil @@ -218,6 +218,44 @@ Maximales Basal-IOB, das OpenAPS abgeben darf [IE] Maximale Menge von nicht Bolus-IOB, die OpenAPs abgeben kann. VERWERFEN + Du wirst nach dem Master-Passwort gefragt. Mit diesem werden die exportierten Einstellungen verschlüsselt. + Du wirst nach dem Master-Passwort gefragt. Mit diesem werden die importierten Einstellungen entschlüsselt. + Export abgebrochen! Einstellungen wurden NICHT exportiert! + Import abgebrochen! Einstellungen wurden NICHT importiert! + Überprüfe die Einstellungen vor dem Import: + Einstellungen können nicht importiert werden! + Einstellungen sollten nicht importiert werden! + Beschreibe die Import-Probleme... + Details zu den Import-Problemen + Importieren + Trotzdem importieren (GEFÄHRLICH!) + Einstellungen wurden mit einer anderen Variante von AAPS erstellt (%1$s). Du nutzt: %2$s.\n\nEinige Einstellungen können fehlen oder ungültig sein - überprüfe und aktualisiere Deine Einstellungen nach dem Import . + Einstellungen wurden auf einem anderen Gerät erstellt. Das ist OK, wenn Du von einem älteren/anderen Handy importierst. Stelle aber sicher, dass die importierten Einstellungen korrekt sind! + Du verwendest das veraltete Format einer alten AAPS-Version das nicht sicher ist! Verwende dieses nur als letzte Möglichkeit, wenn Du keinen Export im aktuellen JSON-Format hast. + Die importierten Einstellungen sind bereits %1$s Tage alt! Hast Du aktuellere Einstellungen oder evtl. die falsche Datei gewählt? Denke daran, die Einstellungen regelmäßig zu exportieren. + Ungültiges Datums-/Zeitformat! + Dateiformat + Erstellt am + AAPS-Version + Build-Variante + Patientenname des exportierenden Geräts + Modell des exportierenden Geräts + Dateiverschlüsselung + Altes Exportformat + Neues verschlüsseltes Format + Neues Debugformat (unverschlüsselt) + Unbekanntes Export-Format + Einstellungen-Datei wurde manipuliert. + Einstellungsdatei ist sicher. + Nicht sicheres, unverschlüsseltes Einstellungsformat verwenden + Fehler im JSON-Format, fehlendes erforderliches Feld (Format, Inhalt, Metadaten oder Sicherheit) + Entschlüsselungsfehler. Das angegebene Passwort kann die Datei nicht entschlüsseln. + Datei-Prüfsumme (hash) fehlt. Einstellungen können nicht auf Echtheit überprüft werden! + Datei wurde nach dem Export verändert! + Entschlüsselungsfehler, Analyse der Einstellungen fehlgeschlagen! + Entschlüsselungsfehler. Das angegebene Passwort ist ungültig oder die Einstellungsdatei wurde verändert! Evtl. wurde die importierte Datei mit einem anderen Master-Passwort exportiert. + Fehlende Verschlüsselungskonfiguration, Einstellungsformat ist ungültig! + Nicht unterstützter oder nicht angegebener Verschlüsselungsalgorithmus! DanaR Verbinden Verbunden @@ -507,6 +545,9 @@ Erwachsener Insulinresistenter Erwachsener Bitte wähle das Patientenalter, um die Sicherheits-Limits festzulegen + Name des Patienten + Gib den Namen des Patienten oder einen Spitznamen für die Unterscheidung zwischen mehreren Setups an. + Nutzer Glimp %1$s benötigt eine deaktivierte Akku-Leistungsoptimierung, um korrekt arbeiten zu können. Loop pausiert @@ -543,8 +584,14 @@ Aktiviere Superbolus im Wizard Aktiviere die SuperBolus-Funktion im Wizard. Nicht aktivieren, wenn Du nicht weißt, welche Auswirkungen dieser Bolus hat! ES KANN ZU EINER ÜBERDOSIERUNG AN INSULIN KOMMEN! Statusanzeige auf Homescreen - Erweiterte Statusanzeige auf Homescreen - Erweiterte Statusanzeige für CAGE, IAGE, SAGE, Reservoir- und Batteriestand auf dem Homescreen. + Warnschwelle Kanülenalter [h] + Warnschwelle kritisches Kanülenalter [h] + Warnschwelle Insulinalter [h] + Warnschwelle kritisches Insulinalter [h] + Warnschwelle Sensoralter [h] + Warnschwelle kritisches Sensoralter [h] + Warnschwelle Batteriealter [h] + Warnschwelle kritisches Batteriealter [h] Warnschwelle Reservoirstand [IE] Warnschwelle kritischer Reservoirstand [IE] Warnschwelle Batteriestand [%] @@ -704,8 +751,12 @@ BZ Upload Einstellungen Zeige detailliertes Delta Delta wird mit Dezimalstelle angezeigt. + Wie häufig SMBs angegeben werden (in Min.) SMB max. Minuten SMB Basal-Limit in Minuten + UAM SMB max minutes + SMB Basal-Limit in Minuten für UAM + Schwellenwert für KH-Empfehlung Nicht unterstützte Pumpen-Firmware Sende BZ-Werte zu xDrip+ Wähle in xDrip+ 640g/Eversense als Daten-Quelle. @@ -772,6 +823,7 @@ her %1$.2f h %1$d mins + %1$dm SMB immer aktivieren Aktiviere SMB immer, unabhängig von Boli. Dies ist nur möglich, wenn eine BZ-Quelle genutzt wird, die die Daten besonders gut filtert wie z. B. G5. Aktiviere SMB nach Mahlzeiten. @@ -970,6 +1022,10 @@ = 100.]]> Niedrige temporäre Ziele senken die Sensitivität + Resistenz senkt Zielwert + Wenn Resistenz festgestellt wird, senke den Glukose-Zielwert + Empfindlichkeit erhöht den Zielwert + Wenn eine höhere Empfindlichkeit festgestellt wird, wird der Glukose-Zielwert erhöht. Ungültige Pumpen-Einstellungen. Lies das Wiki und stelle mit der 360° Konfigurations-Software sicher, dass das Quick-Info-Menü \"QUICK INFO\" heißt. Benutzerdefiniert Große Zeitdifferenz @@ -979,6 +1035,8 @@ WARNUNG: Wenn Du eine echte Pumpe aktivierst und anschließt, kopiert AndroidAPS die Basaleinstellungen vom aktiven Profil zur Pumpe (und behält sie bei). Die Einstellungen in der Pumpe werden hierbei überschrieben. Wenn Du Dir nicht sicher bist oder die Basaleinstellungen in der Pumpe nicht überschreiben möchten, drücke \"Abbrechen\" und vollziehe den Wechsel zur Pumpe später. Behandlungsdaten unvollständig Wartungseinstellungen + E-Mail + Exportierte Einstellungen verschlüsseln Anzahl der zu sendenden Logs Wartung WRTNG @@ -1187,6 +1245,8 @@ Unerwartetes Verhalten. existiert existiert nicht Temporäres Ziel %1$s + Bluetooth-Verbindung mit Gerät %1$s %2$s + Mit Bluetooth-Gerät verbinden WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1241,6 +1301,7 @@ Unerwartetes Verhalten. Alkaline Batterie (erweiterte Ansicht) Lithium Batterie (erweiterte Ansicht) Nickel-Zink-Akku (erweiterte Ansicht) + Nickel-Zink-Akku (erweiterte Ansicht) Fehlersuche Bolus/Behandlungen SCANNEN @@ -1256,6 +1317,7 @@ Unerwartetes Verhalten. Scannt Scannen abgeschlossen Scanfehler: %1$d + Nie Einstellungen Verlauf @@ -1389,6 +1451,7 @@ Unerwartetes Verhalten. Ziel neu starten Zeiterkennung Möchtest Du den Start der Ziele zurücksetzen? Du verlierst Deine Fortschritte. + Zeit- und/oder Zeitzonenänderung an der Pumpe Keine Pumpe ausgewählt Wähle die Einheit, in der die Werte angezeigt werden sollen. Lade die Änderungen des lokalen Profils zu NS hoch. @@ -1445,4 +1508,34 @@ Unerwartetes Verhalten. Temp. BR Ausführungszeit Insight Pumpenalarme + von der Authentifizierungs-App für: %1$s + Authentifizierung einschalten + Authentifiziere Befehle mit Einmal-Passwörtern, die von Google Authenticator oder ähnlichen Apps zur 2-Faktor-Authentifizierung generiert wurden. + Zusätzliche PIN am Ende des Tokens + Zusätzliche Ziffern, die auswendig gelernt und am Ende jedes generierten Einmal-Passworts angehängt werden sollten. + Konfiguration des Authentifikators + Zu überprüfendes OTP: + Authentifikators zurücksetzen + Authentifikatorschlüssel zurücksetzen + Willst Du wirklich den Authentifikatorschlüssel zurücksetzen? Dies wird alle momentan genutzten Authentifikatoren ungültig machen und Du musst sie neu einrichten. + Neuer Authentifizierungsschlüssel generiert! Bitte verwende den aktualisierten QR-Code für die Bereitstellung von Authentifikatoren. + 1. Authentifikator installieren + 2. Scanne den Code zum Einrichten von AndroidAPS OTP-Codes + 3. Teste das Einmal-Passwort + Authentifikators zurücksetzen + Installiere auf jedem Folloer-Phone eine Authenticator-App, die RFC 6238 TOTP-Token unterstützt. Beliebte kostenlose Apps sind:\n Authy\n Google Authenticator\n LastPass Authenticator\n FreeOTP Authenticator + Diesen Code NICHT ONLINE TEILEN!\nVerwende ihn nur zur Einrichtung der Authenticator App auf den Follower-Phones. + Wenn Du den Authentifikator zurücksetzt werden alle bestehenden Authentifikatoren ungültig. Du musst sie dann neu einrichten! + Beim Verbinden + Beim Trennen + Predictions (Vorhersagen) + Steigung der Abweichung + Autorisierung fehlgeschlagen + Gesamtinsulin + Das Master-Passwort wird für die Backup-Verschlüsselung und zur Außerkraftsetzung der Sicherheit in der Anwendung verwendet. Merke es Dir oder bewahre es an einem sicheren Ort auf. + Die Passwörter stimmen nicht überein. + Aktuelles Master-Passwort + Statusanzeige + Einstellung aus NS kopieren + NS-Einstellungen kopieren (falls vorhanden)? diff --git a/app/src/main/res/values-de-rDE/validator.xml b/app/src/main/res/values-de-rDE/validator.xml index 3ea04e700d..37392b77d7 100644 --- a/app/src/main/res/values-de-rDE/validator.xml +++ b/app/src/main/res/values-de-rDE/validator.xml @@ -1,2 +1,21 @@ - + + Nur numerische Ziffern zulässig. + Bitte verwende nur Ziffern von %1$s - %2$s. + Dieses Feld darf kein Sonderzeichen enthalten. + Nur Standard-Buchstaben sind erlaubt + Das Feld darf nicht leer sein. + E-Mail Adresse ungültig + Kreditkartennummer ist ungültig. + Telefonnummer ist nicht gültig + Domain-Name nicht gültig + IP-Adresse nicht gültig + Web-Adresse (URL) ungültig + Kein gültiger Vor- oder Nachname + Kein gültiger vollständiger Name. + Ungültig Format + Bitte 4-stellige Zahl verwenden + Bitte 6-stellige Zahl verwenden + Mindestlänge nicht erreicht + Pin sollte 3- bis 6-stellig sein, unterschiedliche und nicht aufeinanderfolgende Zahlen enthalten. + diff --git a/app/src/main/res/values-el-rGR/strings.xml b/app/src/main/res/values-el-rGR/strings.xml index b710a364fe..df59b1b91a 100644 --- a/app/src/main/res/values-el-rGR/strings.xml +++ b/app/src/main/res/values-el-rGR/strings.xml @@ -105,7 +105,6 @@ Διαφορά: Διαμόρφωση Βήματα - OpenAPS MA Επισκόπηση Προφίλ NS Απλό Προφίλ @@ -518,8 +517,6 @@ Ενεργοποίηση superbolus στον σύντομο οδηγό Ενεργοποιήστε την λειτουργία superbolus στον σύντομο οδηγό. Μην το κάνετε μέχρι να μάθετε τι ακριβώς κάνει. ΜΠΟΡΕΙ ΝΑ ΕΓΧΥΣΕΙ ΠΑΡΑΠΑΝΩ ΔΟΣΕΙΣ ΙΝΣΟΥΛΙΝΗΣ ΑΝ ΧΡΗΣΙΜΟΠΟΙΗΘΕΙ ΛΑΝΘΑΣΜΕΝΑ! Εμφάνιση του φωτισμού κατάστασης στην αρχική οθόνη - Εμφάνιση του φωτισμού κατάστασης στην αρχική οθόνη - Ενεργοποίηση του φωτισμού κατάστασης για cage, iage, sage, reservoir και επίπεδο μπαταρίας στην αρχική οθόνη. Όριο προειδοποίησης χαμηλής αμπούλας [U] Όριο προειδοποίησης πολύ χαμηλής αμπούλας [U] Όριο προειδοποίησης χαμηλής μπαταρίας [%] diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 09bb718f0e..b7498bed57 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -105,7 +105,6 @@ Variación: Tabla de configuraciones Objetivos - OpenAPS MA Inicio Perfil NS Perfil simple @@ -218,6 +217,36 @@ Max IOB basal que OpenAPs puede emitir [U] Este valor es llamado Max Iob en el OpenAPS\nEsta es la máxima insulina en [U] que APS puede entregar a la vez. DESCARTAR + Se le solicitará la contraseña maestra, que se utilizará para cifrar las preferencias exportadas. + Se le solicitará la contraseña maestra, que es necesaria para descifrar las preferencias importadas. + ¡Exportación cancelada! ¡Las preferencias NO se han exportado! + ¡Importación cancelada! ¡Las preferencias NO se han importado! + Por favor, compruebe las preferencias antes de importar: + ¡Las preferencias no se pueden importar! + ¡Las preferencias no se deben importar! + Explicar problemas de importación… + Importar + Importar de todos modos (¡PELIGROSO!) + Las preferencias se han creado en un dispositivo distinto. Está bien si va a importar desde un teléfono más antiguo/diferente, pero ¡asegúrese de que las preferencias importadas son correctas! + ¡Estás usando el obsoleto formato heredado de versiones antiguas de AAPS, que no es seguro! Únicamente utilizarlo como último recurso, si no tiene una exportación en formato JSON actual. + Las preferencias importadas ya tienen %1$s días! ¿Tal vez tengas preferencias más actualizadas o eligiste el archivo equivocado? ¡Recuerda exportar las preferencias regularmente! + ¡Formato de fecha no válido! + Formato del archivo + Creado el + Versión de AAPS + Exportar el nombre del paciente del dispositivo + Exportar modelo de dispositivo + Encriptación de archivos + Formato de exportación antiguo + Nuevo formato cifrado + Nuevo formato de depuración (sin cifrar) + Formato de exportación desconocido + Archivo de configuración alterado + El archivo de configuración es seguro + Error de descifrado, la contraseña proporcionada no puede descifrar el archivo + ¡El archivo se ha modificado tras la exportación! + Error de descifrado, ¡el análisis de las preferencias ha fallado! + ¡Algoritmo de cifrado no soportado o no especificado! DanaR Conectando Conectado @@ -507,6 +536,9 @@ Adulto Adulto resistente a la insulina Por favor elige la edad del paciente para ajustar los límites de seguridad + Nombre del paciente + Proporcione el nombre de paciente o el apodo para diferenciar entre varias configuraciones + Usuario Glimp %1$s necesita una optimización de la batería para funcionar óptimamente Loop desactivado @@ -543,8 +575,6 @@ Activar superbolo en asistente Activar función superbolo en asistente. No lo actives hasta que hayas aprendido lo que realmente hace. ¡PUEDE CAUSAR SOBREDOSIS DE INSULINA usándolo sin precaución! Mostrar luces de estado en la pantalla de inicio - Mostrar luces de estado extendidas en pantalla de inicio - Habilita luces de estado extendidas para tiempo de cánula, tiempo de insulina, tiempo del sensor, reservorio y nivel de batería en pantalla de inicio. Umbral de advertencia de nivel de reservorio [U] Umbral crítico de nivel de reservorio [U] Umbral de advertencia de nivel de pila [%] @@ -704,8 +734,12 @@ Ajuste de subida de datos de glucosa Mostrar detalles delta Mostrar delta con un decimal mas + Con qué frecuencia se administrarán los SMB en min Minutos máximos SMB Minutos máximos de basal para limitar SMB + Minutos máximos de UAM SMB + Minutos máximos de basal para limitar SMB para UAM + Umbral de sugerencia de Carbohidratos Firmware de la bomba no soportado Mandar datos BG a xDrip+ En xDrip+ elige 640g/Eversense como fuente de datos @@ -969,6 +1003,7 @@ = 100]]> Objetivo temporal bajo reduce sensibilidad + Sensibilidad aumenta objetivo Configuración de la bomba incorrecta, leer la documentación y comprobar que el menú de Quick Info se llama QUICK INFO usando el software de configuración 360. Personalizado Diferencia de tiempo grande @@ -978,6 +1013,8 @@ Atención: si activas y conectas al hardware de la bomba, AndroidAPS copiará los ajustes basales del perfil de la bomba, sobrescribiendo el actual perfil basal de la bomba. Comprueba que tengas el perfil basal correcto en AndroidAPS. Si no estás seguro o no quieres sobrescribir los ajustes basales en la bomba, presiona cancelar y repite cambio de la bomba más tarde. Datos de tratamiento incompletos Ajustes de mantenimiento + Email + Cifrar valores exportados Ningún registro para enviar Mantenimiento MANT @@ -1185,6 +1222,8 @@ existe no existe Objetivo temporal %1$s + Conexión Bluetooth con el dispositivo %1$s %2$s + Conectar con dispositivo Bluetooth SSID WiFi %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1239,6 +1278,7 @@ Alcalina (vista extendida) Litio (vista extendida) NiZn (vista ampliada) + NiMH (vista extendida) Bolos/Depuración de Tratamientos ESCANEAR @@ -1439,4 +1479,14 @@ Tiempo requerido de SMB Tiempo de ejecución de SMB + Habilitar autentificador + Configuración de autentificación + ¿Está seguro de que desea restablecer la clave del autenticador? Los autenticadores configurados actualmente no seran válidos, y tendrá que volver a configurarlos. + ¡Se ha generado una clave de autenticador nueva! Utilice QRCode actualizado para suministrar autenticadores. + 1. Instalar autenticador + Restablecer autentificadores + Al resetear el autenticador haces que todos los autenticadores ya provistos no sean válidos. ¡Necesitarás configurarlos de nuevo! + Al conectar + Al desconectar + Predicciones diff --git a/app/src/main/res/values-fr-rFR/objectives.xml b/app/src/main/res/values-fr-rFR/objectives.xml index 58f83d4a9c..a9031a324e 100644 --- a/app/src/main/res/values-fr-rFR/objectives.xml +++ b/app/src/main/res/values-fr-rFR/objectives.xml @@ -20,7 +20,9 @@ 1 semaine de Boucle Fermée en journée en saisissant régulièrement les glucides Activation de fonctionnalités supplémentaires en journée, comme l\'Aide au Repas Améliorée ARA (AMA) Activation de fonctionnalités supplémentaires pour l\'utilisation en journée, telles que la fonction SMB + Activation de l\'automatisation Lisez le wiki et augmentez le maxIA pour que les SMBs fonctionnent correctement ! Un bon début est maxIA = moyenne des Bolus Repas + 3 x maximum débit Basal quotidien + Lisez la documentation comment l\'automatisation fonctionne. Configurez vos premières règles simples. Au lieu de mettre une action, configurez une notification. Quand vous êtes sûr que l\'automatisation est déclenchée au bon moment, remplacez la notification par une action réelle. (https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/Automation.html) Glycémie disponible sur NS Statut de la pompe disponible sur NS Activation manuelle diff --git a/app/src/main/res/values-fr-rFR/protection.xml b/app/src/main/res/values-fr-rFR/protection.xml index 3ea04e700d..4b38aa53da 100644 --- a/app/src/main/res/values-fr-rFR/protection.xml +++ b/app/src/main/res/values-fr-rFR/protection.xml @@ -1,2 +1,23 @@ - + + Authentification requise + Placez votre doigt sur le lecteur d\'empreintes digitales pour vérifier votre identité + Protection des paramètres + Protection de l\'Application + Protection des bolus + Mot de passe principal + Mot de passe des paramètres + Mot de passe de l\'application + Mot de passe des bolus + Déverrouiller les paramètres + Biométrique + Mot de passe personnalisé + Pas de Protection + Protection + Le mot de passe principal n\'est pas défini !\n\nVeuillez définir votre mot de passe principal dans les préférences (%1$s → %2$s) + Mot de passe défini ! + Mot de passe non défini + Mot de passe non modifié + Mot de passe supprimé ! + Entrez le mot de passe ici + diff --git a/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml index bb30f2183d..92b4ec3892 100644 --- a/app/src/main/res/values-fr-rFR/strings.xml +++ b/app/src/main/res/values-fr-rFR/strings.xml @@ -43,6 +43,7 @@ Intégration pompe pour les personnes qui font des injections quotidiennes multiples pour le traitement de leur diabète Intégration pour les pompes qui n’ont pas encore de pilote (Boucle Ouverte) La sensibilité est calculée de la même manière que Oref0, mais vous pouvez spécifier la période concernée. L\'absorption minimale des glucides est calculée à partir des temps d’absorption max des glucides du menu préférences. + La sensibilité est calculée à partir des données des dernières 8 heures et les glucides (si non absorbés) ne sont plus pris en compte après le temps spécifié dans les préférences. Le plugin calcule également les RNS (UAM). La sensibilité est calculée comme une moyenne pondérée des écarts. Les écarts les plus récents ont un poids plus élevé. L\'absorption minimale des glucides est calculée à partir des temps d’absorption des glucides max du menu préférences. Cet algorithme est le plus rapide pour s\'adapter aux changements de sensibilité. Recevoir les valeurs de glycémie de l’app Eversense patchée. Recevoir les glycémies depuis Glimp. @@ -105,7 +106,6 @@ Delta: Générateur de configuration Objectifs - OpenAPS MA Aperçu Profil NS Profil simple @@ -218,6 +218,44 @@ IA basale max que OpenAPS pourra délivrer [U] Cette valeur est appelée Max IA (Insuline Active) dans le contexte OpenAPS\nC\'estlle maximum d\'insuline en [U] que APS peut délivrer en une seule fois. FERMER + Le mot de passe principal vous sera demandé pour crypter les préférences exportées. + Le mot de passe principal vous sera demandé pour décrypter les préférences exportées. + Export annulé ! Les préférences n\'ont PAS été exportées ! + Import annulé ! Les préférences n\'ont PAS été importées ! + Vérifiez les préférences avant d\'importer : + Les préférences ne peuvent pas être importées ! + Les préférences ne doivent pas être importées ! + Explication des problèmes d\'importation… + Détails des problèmes d\'importation + Import + Importer quand même (DANGEREUX !) + Des préférences ont été créées avec des variantes différentes d\'AAPS (%1$s) quand vous avez : %2$s.\n\nCertains paramètres peuvent manquer ou ou ne pas être valides après l\'import, vérifiez et mettez à jour vos préférences. + Les préférences ont été créées sur un autre périphérique. C\'est OK si vous importez à partir d\'un téléphone ancien/différent, mais vérifiez les préférences importées sont correctes ! + Vous utilisez le format obsolète des anciennes versions d\'APPS qui n\'est pas sécurisé ! Utilisez-le uniquement en dernier recours, si vous n\'avez pas d\'export au format JSON actuel. + Les préférences importées ont déjà %1$s jours ! Vous avez peut-être des préférences plus récentes ou vous avez sélectionné un mauvais fichier ? N\'oubliez pas d\'exporter vos préférences régulièrement ! + Format de date invalide ! + Format de fichier + Créé le + Version d\'AAPS + Variante de Build + Export du nom du patient de l\'appareil + Export du modèle de l\'appareil + Cryptage du fichier + Ancien format d\'export + Nouveau format crypté + Nouveau format de débug (non crypté) + Format d\'export inconnu + Fichier paramètres altérés + Fichier paramètres sécurisé + Utilisation non sécurisée, fichier paramètres non crypté + Erreur de format JSON, zone obligatoire manquante (format, contenu, métadonnées ou sécurité) + Erreur de décryptage, le mot de passe indiqué ne permet pas le décryptage du fichier + Checksum du fichier manquant, vérification de l\'authenticité des pararamètres impossible ! + Le fichier a été modifié après l\'export ! + Erreur de décryptage, échec de l\'import des préférences ! + Erreur de décryptage, le mot de passe fourni est invalide ou le fichier de paramètres à été modifié ! Cela peut arriver si le fichier a été exporté avec un mot de passe principal différent. + Configuration du cryptage manquant, format des paramètres invalide ! + Algorithme de cryptage non pris en charge ou non spécifié ! DanaR Connection en cours Connectée @@ -253,8 +291,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Pour injecter le bolus repas de %1$.2fU renvoyer le code %2$s Pour définir la Cible Temp %1$s renvoyer le code %2$s Pour annuler la Cible Temp renvoyer le code %1$s - Pour désactiver les commandes à distance SMS renvoyer le code %1$s.\n\nGardez à l\'esprit que vous ne pourrez le réactiver que directement à partir de l\'application AAPS du smartphone maitre. - Service de commande à distance SMS arrêté. Pour le réactiver, utilisez AAPS sur le smartphone maitre. + Pour désactiver les commandes à distance SMS renvoyer le code %1$s.\n\nGardez à l\'esprit que vous ne pourrez le réactiver que directement à partir de l\'application AAPS du smartphone maître. + Service de commande à distance SMS arrêté. Pour le réactiver, utilisez AAPS sur le smartphone maître. Renvoyer le code %2$s pour envoyer la calibration %1$.2f Échec du Bolus Nombre minimum de minutes qu\'il doit y avoir entre un bolus distant et le suivant @@ -508,6 +546,9 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Adulte Adulte résistant à l\'insuline Veuillez svp sélectionner l’âge du patient pour définir les limites de sécurité + Nom du patient + Veuillez indiquer un nom ou pseudo du patient pour différencier plusieurs configurations + Patient Glimp %1$s a besoin d\'optimisation de la batterie (whitelisting) pour une performance correcte La Boucle est suspendue @@ -544,8 +585,14 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Activer les Superbolus dans l’Assistant Activer la fonctionnalité SuperBolus dans l’Assistant. Ne pas l’activer avant de bien comprendre comment cela fonctionne réellement. IL PEUT PROVOQUER UNE OVERDOSE D’INSULINE SI UTILISÉ AVEUGLÉMENT ! Afficher les voyants d\'état sur l\'écran d\'accueil - Afficher les voyants d\'état prolongés sur l\'écran d\'accueil - Activer les voyants d\'état prolongés pour AgeC, AgeI, AgeS, niveaux du réservoir et de batterie sur l\'écran d\'accueil. + Seuil d\'alerte âge canule [h] + Seuil critique âge canule [h] + Seuil d\'alerte âge insuline [h] + Seuil critique âge insuline [h] + Seuil d\'alerte âge capteur [h] + Seuil critique âge capteur [h] + Seuil d\'alerte niveau pile [h] + Seuil critique niveau pile [h] Seuil d\'avertissement de niveau du réservoir [U] Seuil critique de niveau du réservoir [U] Seuil d’avertissement du niveau de batterie [%] @@ -705,8 +752,13 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Paramètres de téléchargement des glycémies Afficher le delta détaillé Afficher delta avec une décimale supplémentaire + Fréquence des SMB en min SMB minutes max Max. minutes de basal pour limiter le SMB + SMB RNS minutes max + Minutes de basal max pour limiter les SMB des RNS + Seuil de suggestionde glucides + Quantité de glucides à partir de laquelle une notification est envoyée Firmware pompe incompatible Transmettre les Gly vers xDrip+ Dans xDrip+ veuillez séléctionner 640g/Eversense comme source de données @@ -773,6 +825,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S passé(e)s %1$.2f h %1$d min + %1$dm Activer en permanence les SMB Activer toujours SMB de manière autonome pour les bolus. Ceci est possible uniquement avec une source de glycémie ayant un très bon filtrage de données comme le G5 Activer SMB après ingestion de glucides @@ -971,6 +1024,10 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S = 100]]> Cible temp. basse abaisse la sensibilité + La résistance diminue la cible + Quand une résistance est détectée, baisse de la glycémie cible + Sensibilité augmente la cible + Quand une sensibilité est détectée, augmentation de la glycémie cible Paramétrage de la pompe invalide. Vérifiez la documentation et le menu QUICK INFO en utilisant le logiciel de configuration 360. Personnalisé Différence horaire importante @@ -980,6 +1037,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S ATTENTION : Si vous activez et connectez à une vraie pompe, AndroidAPS copiera les paramètres Basals du profil vers la pompe, écrasant le taux basal existant stocké sur la pompe. Assurez-vous d\'avoir correctement saisi et réglé les paramètres Basal dans AndroidAPS. Si vous ne savez pas ou si ne voulez pas écraser les paramètres Basal sur votre pompe, appuyez sur Annuler et reporter le passage à la pompe à une date ultérieure. Données de traitement incomplètes Paramètres de maintenance + E-mail + Crypter les paramètres exportés Nombre de journaux (Logs) à envoyer Maintenance MAINT @@ -1187,6 +1246,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S existe n\'existe pas Cible Temp. %1$s + Connexion Bluetooth à l\'appareil %1$s %2$s + Connecter à un appareil Bluetooth SSID WiFi %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1241,6 +1302,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Alcaline (vue étendue) Lithium (vue étendue) NiZn (vue étendue) + NiMH (vue Étendue) Débogage de Bolus/Traitements SCANNER @@ -1256,6 +1318,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Recherche en cours Recherche finie Erreur de recherche : %1$d + Jamais Paramètres Historique @@ -1389,6 +1452,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Suppression démarrée Détection de temps Voulez-vous réinitialiser le début de l\'objectif ? Vous risquez de perdre vos progrès. + Heure et/ou fuseau horaire changé sur la pompe Aucune pompe sélectionnée Sélectionnez les unités dans lesquelles vous souhaitez afficher les valeurs Remonter les modifications de profil local dans NS @@ -1445,4 +1509,34 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Heure d\'exécution basal temp Alertes Pompe Insight + depuis l\'appli. Authenticateur pour : %1$s + Activer l\'Authentificateur + Authentifier les commandes à l\'aide des mots de passe uniques (OTP) générés par Google Authenticator ou des applications 2FA similaires. + Code PIN supplémentaire à la fin de l\'OTP + Chiffres supplémentaires qui doivent être mémorisés et collés à la fin de chaque OTP généré + Configuration de l\'Authentificateur + OTP à vérifier : + Réinitialiser les authentificateurs + Réinitialiser la clé de l\'Authentificateur + Voulez-vous réinitialiser la clé de l\'Authenticateur ? Cela rendra tous authentificateurs configurés invalides, et vous devrez les configurer à nouveau. + Nouvelle clé de l\'Authenticateur générée ! Veuillez utiliser le QRCode mis à jour pour les authentificateurs. + 1. Installation l\'Authentificateur + 2. Scan du code pour configurer les codes OTP AndroidAPS + 3. Test Mot-de-Passe-Unique (OTP) + Réinitialiser les authentificateurs + Sur chaque téléphone suiveur, installez une appli. Authentificateur qui prend en charge les jetons RFC 6238 TOTP. Les applications libres populaires sont:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator + NE PAS PARTAGER ce code en ligne !\nUtilisez-le uniquement pour configurer l\'appli. Authenticateur sur les téléphones suiveurs. + En réinitialisant l\'Authentificateur, vous invalidez tous les authentificateurs déjà initialisés. Vous devrez les reconfigurer ! + À la connexion + À la déconnexion + Prédictions + Pente de déviations + Echec de l\'authentification + Insuline absolue + Le mot de passe principal est utilisé pour crypter les sauvegardes et superviser la sécurité de l\'application. Rappelez-vous en ou stockez le en lieu sûr. + Les mots de passe ne correspondent pas + Mot de passe principal actuel + Voyants d\'état + Copier les paramètres depuis NS + Copier les paramètres NS (s\'ils existent)? diff --git a/app/src/main/res/values-fr-rFR/validator.xml b/app/src/main/res/values-fr-rFR/validator.xml index 3ea04e700d..f18febf0f4 100644 --- a/app/src/main/res/values-fr-rFR/validator.xml +++ b/app/src/main/res/values-fr-rFR/validator.xml @@ -1,2 +1,21 @@ - + + Seuls les chiffres sont autorisés + Seuls les chiffres entre %1$s et %2$s sont autorisés + Ce champ ne doit pas contenir de caractères spéciaux + Seules les lettres standard sont autorisées + Le champ ne doit pas être vide + Adresse email non valide + Numéro de carte de crédit non valide + Téléphone non valide + Nom de domaine non valide + Adresse IP non valide + Url Web non valide. + Prénom ou Nom non valide + Nom complet non valide + Format non valide + Doit être 4 chiffres + Doit être 6 chiffres + Longueur minimale non respectée + le PIN doit être entre 3 et 6 chiffres différents et non en série + diff --git a/app/src/main/res/values-it-rIT/objectives.xml b/app/src/main/res/values-it-rIT/objectives.xml index 84a9152c3d..ba4a3d013f 100644 --- a/app/src/main/res/values-it-rIT/objectives.xml +++ b/app/src/main/res/values-it-rIT/objectives.xml @@ -20,7 +20,10 @@ 1 settimana di looping diurno con inserimento regolare dei carboidrati, eseguito con successo Abilitazione funzioni aggiuntive per l\'uso diurno, ad esempio AMA (advanced meal assist - assistenza avanzata del pasto) Abilitazione funzioni aggiuntive per l\'uso diurno, come SMB + Abilitazione automazione È necessario leggere il wiki e aumentare maxIOB affinché le azioni di SMB funzionino adeguatamente! Un buon inizio è maxIOB = media bolo posto + 3 x max basale giornaliera + Leggi la documentazione su come funziona l\'automazione. Configura le tue prime semplici regole. Consenti ad AAPS solo di visualizzare una notifica, non di eseguire un\'azione. Quando sei sicuro che l\'automazione viene attivata al momento giusto, sostituisci la notifica con un\'azione reale. +(https://androidaps.readthedocs.io/en/latest/EN/Usage/Automation.html) Glicemia disponibile in NS Stato micro disponibile in NS Attivazioni manuali diff --git a/app/src/main/res/values-it-rIT/protection.xml b/app/src/main/res/values-it-rIT/protection.xml index 3ea04e700d..bb153b84e7 100644 --- a/app/src/main/res/values-it-rIT/protection.xml +++ b/app/src/main/res/values-it-rIT/protection.xml @@ -1,2 +1,23 @@ - + + Autenticazione richiesta + Posiziona il tuo dito sul lettore di impronte digitali per verificare la tua identità + Protezione impostazioni + Protezione applicazione + Protezione bolo + Password Master + Password impostazioni + Password applicazione + Password bolo + Impostazioni sblocco + Biometrico + Password personalizzata + Nessuna protezione + Protezione + La password master non è impostata!\n\nImposta la tua password Master in Preferenze (%1$s → %2$s) + Password impostata! + Password non impostata + Password non modificata + Password cancellata! + Inserisci qui la password + diff --git a/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/values-it-rIT/strings.xml index bdeb463adb..cc4b846a9b 100644 --- a/app/src/main/res/values-it-rIT/strings.xml +++ b/app/src/main/res/values-it-rIT/strings.xml @@ -106,7 +106,6 @@ Delta: Configuratore strutturale Obiettivi - OpenAPS MA Panoramica Profilo NS Profilo semplice @@ -220,8 +219,43 @@ Questo valore è chiamato Max IOB nel contesto OpenAPS\nIndica l\'insulina massima in [U] che APS può erogare in contemporanea. RIMUOVI Ti verrà richiesta la password principale, che verrà utilizzata per crittografare le preferenze esportate. + Ti verrà chiesta la password master, che è necessaria per decrittare le preferenze importate. + Esportazione annullata! Le preferenze NON sono state esportate! + Importazione annullata! Le preferenze NON sono state importate! + Verifica le preferenze prima dell\'importazione: Le preferenze non possono essere importate! Le preferenze non dovrebbero essere importate! + Descrivi i problemi importazione… + Dettagli dei problemi di importazione + Importa + Importa comunque (PERICOLOSO!) + Le preferenze sono state create con una differente versione di AAPS (%1$s) mentre invece tu hai: %2$s.\n\nAlcune impostazioni potrebbero mancare o non essere valide - dopo l\'importazione controlla e aggiornare le tue preferenze. + Le preferenze sono state create su un dispositivo diverso. Va bene importarle da un vecchio/diverso telefono, ma assicurati che le preferenze importate siano corrette! + Stai utilizzando il formato precedente (obsoleto) delle vecchie versioni di APPS, che non è sicuro! Utilizzalo solo come ultima risorsa, se non hai un\'esportazione nel corrente formato JSON. + Le preferenze importate hanno già %1$s giorni! Forse hai preferenze più aggiornate. Hai scelto il file sbagliato? Ricorda di esportare le preferenze regolarmente! + Formato data-ora non valido! + Formato file + Creato: + Versione AAPS + Variante build + Nome paziente del dispositivo esportatore + Modello dispositivo esportatore + Crittografia file + Vecchio formato esportazione + Nuovo formato crittografato + Nuovo formato di debug (non crittografato) + Formato esportazione sconosciuto + File delle impostazioni manomesso + Il file delle impostazioni è sicuro + Utilizzo non sicuro, formato impostazioni non crittografato + Errore formato JSON, campo obbligatorio mancante (formato, contenuto, metadati o sicurezza) + Errore decrittazione, la password data non può decrittare il file + File checksum (hash) mancante, impossibile verificare l\'autenticità delle impostazioni! + Il file è stato modificato dopo l\'esportazione! + Errore decrittazione, analisi preferenze fallita! + Errore decrittazione, la password fornita è errata o il file delle impostazioni è stato modificato! È possibile che il file importato sia stato esportato con una diversa password master. + Configurazione crittografia mancante, il formato delle impostazioni non è valido! + Algoritmo di crittografia non supportato o non specificato! DanaR Connessione Connesso @@ -511,6 +545,9 @@ Adulto Adulto insulino-resistente Seleziona l\'età del paziente per impostare i limiti di sicurezza + Nome paziente + Fornisci il nome del paziente o il nickname per distinguere questa configurazione tra altre + Utente Glimp Per un buon funzionamento, %1$s ha bisogno di essere nella whitelist della funzione \"ottimizzazione batteria\" di Android Loop sospeso @@ -547,8 +584,14 @@ Abilita superbolo nel calcolatore Abilita la funzionalità superbolo nel calcolatore. Non abilitare fino a quando non impari ciò che realmente fa. PUÒ CAUSARE SOVRADOSAGGIO DI INSULINA SE USATO IMPROPRIAMENTE! Mostra indicatori di stato sulla home - Mostra indicatori estesi sulla home - Abilita indicatori di stato estesi per \"età\" cannula, insulina, sensore, serbatoio e livello batteria sulla schermata iniziale. + Soglia di avviso età cannula [h] + Soglia età cannula critica [h] + Soglia di avviso età insulina [h] + Soglia età insulina critica [h] + Soglia di avviso età sensore [h] + Soglia età sensore critica [h] + Soglia di avviso età batteria [h] + Soglia età batteria critica [h] Soglia di avviso livello serbatoio [U] Soglia livello serbatoio critico [U] Soglia di avviso livello batteria [%] @@ -708,8 +751,13 @@ Impostazioni caricamento BG Mostra delta dettagliato Mostra delta con una cifra decimale in più + Frequenza di erogazione SMB (min) Max minuti SMB Max minuti di basale a cui limitare SMB + SMB UAM max minuti + Max minuti di basale a cui limitare SMB per UAM + Soglia proposta CHO + Quando vengono proposti carboidrati, la quantità minima per la quale verrà mostrata una notifica Firmware del micro non supportato Invia dati BG a xDrip+ In xDrip+ seleziona origine dati 640g/Eversense @@ -776,6 +824,7 @@ fa %1$.2f h %1$d min + %1$dm Abilita SMB sempre Abilita SMB sempre, indipendentemente dai boli. Possibile solo con sorgente glicemia con un buon filtraggio dei dati, come G5 Abilita SMB dopo i CHO @@ -926,7 +975,7 @@ Lettura stato Le modifiche devono essere fatte in NS Salta configurazione guidata - Premi il tasto in basso per permettere ad AndroidAPS di suggerire/fare modifiche alla basale + Premi il tasto in basso per permettere ad AndroidAPS di proporre/fare modifiche alla basale Configura il plugin APS Configura il plugin di Sensibilità Il plugin di Sensibilità è utilizzato per il rilevamento della sensibilità all\'insulina e il calcolo di COB. Per ulteriori informazioni visita: @@ -974,6 +1023,10 @@ = 100]]> Temp-Target \"basso\" riduce la sensibilità + La resistenza abbassa il target + Quando viene rilevata resistenza, ridurre la glicemia target + La sensibilità aumenta il target + Quando viene rilevata sensibilità, aumentare la glicemia target Configurazione micro non valida, controlla la documentazione e verifica che il menu Quick Info sia denominato QUICK INFO utilizzando \"360 configuration software\". Personalizzato Grande differenza oraria @@ -983,6 +1036,8 @@ Attenzione: se attivi e connetti un micro, AndroidAPS copierà le impostazioni della basale dal profilo al micro, sovrascrivendo la velocità basale esistente memorizzata sul micro. Assicurati di avere la giusta impostazione della basale in AndroidAPS. Se non sei sicuro o non vuoi sovrascrivere le impostazioni della basale sul micro, premi annulla e ripeti il processo in un altro momento. Dati trattamento incompleti Impostazioni manutenzione + Destinatario email + Crittografa impostazioni esportate Numero di log da inviare Manutenzione MANUT @@ -1190,6 +1245,8 @@ esiste non esiste Temp-Target %1$s + Connessione Bluetooth a dispositivo %1$s %2$s + Connessione a dispositivo Bluetooth WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1244,6 +1301,7 @@ Alcalina (Extended view) Litio (Extended view) NiZn (Extended view) + NiMH (Extended view) Debug Bolo/Trattamenti SCAN @@ -1259,6 +1317,7 @@ Scansione Scansione terminata Errore scansione: %1$d + Mai Impostazioni Storico @@ -1392,6 +1451,7 @@ Cancella avvio Rilevazione tempo Vuoi resettare l\'avvio dell\'obiettivo? Potresti perdere i tuoi progressi. + Cambio di ora e/o fuso orario sul micro Nessun micro selezionato Seleziona le unità in cui vuoi visualizzare i valori Carica modifiche al profilo locale in NS @@ -1448,4 +1508,34 @@ Esecuzione basale temporanea (momento) Avvisi micro Insight + da app Autenticatore per: %1$s + Abilita Autenticatore + Autentica i comandi utilizzando OTP (One Time Password) generate da Google Authenticator o app 2FA simili. + PIN aggiuntivo a fine token + Cifre aggiuntive che devono essere memorizzate e incollate alla fine di ogni OTP generata + Configurazione Autenticatore + OTP per verifica: + Resetta Autenticatori + Resetta Chiave Autenticatore + Sei sicuro di resettare la chiave Autenticatore? Renderà non validi tutti gli Autenticatori attualmente configurati e sarà necessario configurarli nuovamente. + La nuova Chiave Autenticatore è stata generata! Utilizza il QRCode aggiornato per fornire gli autenticatori. + 1. Installa l\'Autenticatore + 2. Scansione il codice per configurare i codici OTP di AndroidAPS + 3. Testa OTP + Resetta Autenticatori + Su ogni telefono follower installa una app Autenticatore che supporta i token RFC 6238 TOTP. App gratuite popolari sono:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator + NON CONDIVIDERE questo codice online!\nUtilizzalo solo per configurare l\'app Autenticatore sui telefoni follower. + Resettando l\'autenticatore rendi non validi tutti gli autenticatori già forniti. Dovrai configurarli di nuovo! + Alla connessione + Alla disconnessione + Predizioni + Pendenza deviazione + Autorizzazione fallita + Insulina assoluta + La password master viene utilizzata per la crittografia del backup e per gestire la sicurezza nell\'applicazione. Ricordala o conservala in un luogo sicuro. + Le password non coincidono + Password Master corrente + Indicatori di stato + Copia impostazioni da NS + Copiare impostazioni NS (se esiste)? diff --git a/app/src/main/res/values-it-rIT/validator.xml b/app/src/main/res/values-it-rIT/validator.xml index 3ea04e700d..032f0bbddd 100644 --- a/app/src/main/res/values-it-rIT/validator.xml +++ b/app/src/main/res/values-it-rIT/validator.xml @@ -1,2 +1,21 @@ - + + Sono consentite solo cifre numeriche. + Sono consentite solo cifre numeriche nel range %1$s - %2$s. + Questo campo non può contenere alcun carattere speciale + Sono consentite solo lettere standard + Il campo non deve essere vuoto + Indirizzo email non valido + Il numero della carta di credito non è valido + Numero di telefono non valido + Nome dominio non valido + Indirizzo IP non valido + L\'URL non è valido + Nome o Cognome non valido. + Nome completo non valido. + Formato non valido + Deve essere un numero di 4 cifre + Deve essere un numero di 6 cifre + Lunghezza minima non soddisfatta + Il PIN deve contenere da 3 a 6 cifre, non uguali o in serie + diff --git a/app/src/main/res/values-ko-rKR/strings.xml b/app/src/main/res/values-ko-rKR/strings.xml index 63a2e057da..414d29fbd6 100644 --- a/app/src/main/res/values-ko-rKR/strings.xml +++ b/app/src/main/res/values-ko-rKR/strings.xml @@ -105,7 +105,6 @@ Delta: 구성 관리자 목표 - OpenAPS MA NS 프로파일 Simple 프로파일 @@ -543,8 +542,6 @@ 마법사에서 Superbolus 활성화하기 마법사에서 Superbolus 기능을 활성화합니다. 어떤 기능인지 확실히 알기전까지 활성화 하지 마세요. 제대로 알지 못하고 사용하면 일슐린이 과다 주입될 수 있습니다! 홈화면에 상태 표시등 보여주기 - 홈화면에 확장 상태등 표시하기 - 홈화면에 캐뉼라 사용기간(cage), 인슐린 사용기간(iage), 센서 사용기간(sage), 펌프용 주사기(reservoir)와 배터리(battery) 남은 양에 대한 확장 표시등을 활성화합니다. 주사기량 경고 기준값[U] 주사기량 위험 기준값[U] 배터리 잔량 경고값 [%] diff --git a/app/src/main/res/values-lt-rLT/exam.xml b/app/src/main/res/values-lt-rLT/exam.xml index 36253d4dab..2eb97c9785 100644 --- a/app/src/main/res/values-lt-rLT/exam.xml +++ b/app/src/main/res/values-lt-rLT/exam.xml @@ -6,7 +6,7 @@ Mažiausia reikšmė - 5 valandos. https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin Jis yra lygus IVT parametrui, kuris naudojamas pompoje. - Jūs turite nustatyti jūsų individualias vertes (bet ne mažiau kaip 5 valandas). + Jūs turite nustatyti savo individualią reikšmę (bet ne mažiau kaip 5 val.). Tema: Hipo Laikinas tikslas Kokia yra pagrindinė priežastis nustatyti hipo laikiną tikslą? Užkirsti kelią kristi gliukozės kiekiui kraujyje, kai jau veikia nulinė laikina bazė. diff --git a/app/src/main/res/values-lt-rLT/objectives.xml b/app/src/main/res/values-lt-rLT/objectives.xml index 06357e3814..2ef9dbd944 100644 --- a/app/src/main/res/values-lt-rLT/objectives.xml +++ b/app/src/main/res/values-lt-rLT/objectives.xml @@ -35,6 +35,7 @@ Parodyti Ciklo įskiepio turinį Panaudokite vaizdo dydžio keitimo funkciją ilgai spaudžiant ant glikemijos kreivės Įeiti + Jei turite bent 3 mėnesių uždaro ciklo patirties kitose sistemose, galite gauti kodą, leidžiantį praleisti tikslus. Visą informaciją galite rasti čia: https://androidaps.readthedocs.io/en/latest/EN/Usage/Objectives.html#skip-objectives. Kodas priimtas Neteisingas kodas Patvirtinkite savo žinias @@ -52,21 +53,21 @@ Nepavyko nuskaityti laiko Tikslo reikalavimai neįvykdyti - %1$d diena - %1$d dienos(-ų) - %1$d dienos(-ų) - %1$d dienos(-ų) + %1$d d. + %1$d d. + %1$d d. + %1$d d. - %1$d valanda - %1$d valandos(-ų) - %1$d valandos(-ų) - %1$d valandos(-ų) + %1$d val. + %1$d val. + %1$d val. + %1$d val. - %1$d minutė - %1$d minutės(-čių) - %1$d minutės(-čių) - %1$d minutės(-čių) + %1$d min. + %1$d min. + %1$d min. + %1$d min. diff --git a/app/src/main/res/values-lt-rLT/strings.xml b/app/src/main/res/values-lt-rLT/strings.xml index 85e82fa262..31c388d786 100644 --- a/app/src/main/res/values-lt-rLT/strings.xml +++ b/app/src/main/res/values-lt-rLT/strings.xml @@ -43,6 +43,7 @@ Integracija žmonėms, naudojantiems insulino injektorius Integracija pompoms, kurios dar neturi reikalingo valdiklio (Atviras Ciklas) Jautrumas insulinui apskaičiuojamas taip pat kaip ir Oref0, tačiau jūs galite nustatyti, koks praeities laikotarpis bus naudojamas. Minimalus angliavandenių įsisavinimo greitis apskaičiuojamas remiantis maksimaliu angliavandenių įsisavinimo greičiu, kuris įvestas Nustatymuose. + Jautrumas insulinui apskaičiuojamas remiantis praėjusių 8 val. duomenimis, o (neįsisavinti) angliavandeniai neįtraukiami į skaičiavimus praėjus Nustatymuose nurodytam laikui. Įskiepis taip pat įskaičiuoja NDM (nedeklaruotą maistą). Jautrumas insulinui apskaičiuojamas kaip nuokrypių svertinis vidurkis. Naujausių nuokrypių svoris yra didesnis. Minimalus angliavandenių įsisavinimo greitis apskaičiuojamas iš maksimalaus angliavandenių įsisavinimo greičio, kuris nurodytas Nustatymuose. Šis algoritmas greičiausiai aptinka pasikeitusį jautrumą insulinui. Gauti kraujo gliukozės vertes iš modifikuotos Eversense programėlės. Gauti kraujo gliukozės vertes iš Glimp. @@ -54,9 +55,9 @@ Rodyti Ciklo informaciją laikrodyje, xDrip+ pradžios ekrane. Nuotolinis AndroidAPS valdymas naudojant SMS komandas. Vienetai - IVT (Insulino Veikimo Trukmė) - IA (insulino/angliavandenių santykis) - JIF (jautrumo insulinui faktorius) + IVT + IA + JIF Valandinė bazė Tikslas Nenustatytas profilis @@ -75,7 +76,7 @@ LT AV Korekcija - vv + V Bolusų AIO Paleisti dabar Virtuali pompa @@ -105,7 +106,6 @@ Pokytis: Konfigūracija Tikslai - OpenAPS MA Apžvalga NS profilis Paprastas profilis @@ -123,7 +123,7 @@ Bendrieji Bendrieji įskiepiai, kurie gali praversti. Kokie apribojimai taikomi? - dienos(-ų) + d. Apribojimai Ciklas Ciklas @@ -152,7 +152,7 @@ Valandinė bazė: AV Pakeiskite įvestus duomenis! - KG šaltinis + Glikemijos šaltinis Iš kur AndroidAPS gaus duomenis? xDrip DKS režimas @@ -166,16 +166,16 @@ CIKLAS NEAKTYVUS DĖL APRIBOJIMŲ Bazės AIO Pritaikytas boluso apribojimas - Pritaikytas angliavandenių apribojimas + Pritaikytas AV apribojimas KG testas Pranešimas Pastaba Klausimas Fizinis aktyvumas Kateterio keitimas - NGJ sensoriaus įvedimas - NGJ sensoriaus paleidimas - Insulino rezervuaro keitimas + NGJ įvedimas + NGJ paleidimas + Rezervuaro keitimas Profilio keitimas Bolusas užkandžiui Bolusas valgiui @@ -183,13 +183,13 @@ Kombinuotas bolusas Pradėta laikina bazė Užbaigta laikina bazė - Angliavandeniai korekcijai + AV korekcijai OpenAPS neprisijungus Įvykio tipas Kiti Matuoklis Sensorius - Angliavandeniai + AV Insulinas AV laikas Išskaidyti @@ -218,6 +218,44 @@ Didžiausias valandinės bazės insulino kiekis, kurį gali suleisti OpenAPS [U] Ši vertė OpenAPS kontekste vadinama Maks AIO\nTai maksimalus insulino vienetų [U] skaičius, kurį DKS gali suleisti vienu metu. ATMESTI + Jūsų paprašys nustatyti slaptažodį, kuris bus naudojamas užšifruojant eksportuojamus nustatymus. + Jūsų paprašys nustatyti slaptažodį, kuris bus naudojamas atšifruojant importuotus nustatymus. + Eksportas nutrauktas! Nustatymai NE eksportuoti! + Importas nutrauktas! Nustatymai NE importuoti! + Prašom patikrinti nustatymus prieš importuojant: + Nustatymai negali būti importuoti! + Nustatymai neturėtų būti importuoti! + Importo sutrikimų paaiškinimas… + Importo sutrikimų detalės + Importas + Importuoti vistiek (PAVOJINGA!) + Nustatymai sukurti naudojant skirtingą AAPS versiją (%1$s), jūsų turima: %2$s.\n\nKai kurių nustatymų gali trūkti arba jie gali būti neteisingi - po importavimo patikrinkite ir atnaujinkite nustatymus. + Nustatymai buvo sukurti naudojant kitą prietaisą. Viskas gerai, jei importuojante iš senesnio/kito telefono, tačiau įsitikinkite, kad visi importuoti nustatymai yra teisingi! + Jūs naudojate pasenusį formatą iš senos AAPS versijos, kuris nėra saugus! Naudokite tik kraštutiniu atveju, jei neturite nustatymų failo dabartiniu, JSON formatu. + Importuoti nustatymai yra %1$s d. senumo! Patikrinkite, gal pasirinkote neteisingą failą ir turite naujesnius? Nepamirškite reguliariai eksportuoti nustatymų! + Neteisingas datos ir laiko formatas! + Failo formatas + Sukurta + AAPS versija + Versijos variantas + Eksportuojamas paciento vardas + Eksportuojamas prietaiso modelis + Failo šifravimas + Senas eksporto formatas + Naujas šifruotas formatas + Naujas derinimo formatas (nešifruotas) + Nežinomas eksporto formatas + Nustatymų failas sugadintas + Nustatymų failas yra saugus + Naudojamas nesaugus, nešifruotas nustatymų formatas + JSON formato klaida, neužpildyti reikalingi laukai (formatas, turinys, metaduomenys arba saugumas) + Iššifravimo klaida, netinkamas slaptažodis + Trūksta failo kontrolinės žymės, neįmanoma patikrinti autentiškumo! + Failas pakeistas po eksportavimo! + Iššifravimo klaida, nustatymų analizė neįvyko! + Iššifravimas klaida, slaptažodis yra neteisingas arba nustatymų failas buvo pakeistas! Taip nutinka, jei importuotas failas buvo eksportuotas su kitu slaptažodžiu. + Trūksta šifravimo sąrankos parametrų, nustatymų formatas yra neteisingas! + Nepalaikomas arba nepatikslintas šifravimo algoritmas! DanaR Jungiamasi Prisijungta @@ -233,7 +271,7 @@ Pompos AIO Paros insulinas Paskutinis bolusas - Prieš %1$.1f valandų + Prieš %1$.1f val. Neteisingai įvesti duomenys Vertė nėra tinkamai nustatyta Atnaujinti profilį @@ -263,8 +301,8 @@ Bus suleista %1$.2fvv %1$.2fvv bolusas sėkmingai suleistas Bolusas %1$.2fvv sėkmingai suleistas - Tikslas %1$s %2$d minutėms - Tikslas %1$s %2$d minutėms nustatytas sėkmingai + Tikslas %1$s %2$d min. + Tikslas %1$s %2$d min. nustatytas sėkmingai Laikinas tikslas atšauktas sėkmingai Leidžiama %1$.2fvv Leisti nuotolines komandas SMS žinutėmis @@ -286,14 +324,14 @@ užpildymas valandinė bazė gliukozė - angliavandeniai + AV aliarmas Įkelta %1$d įrašų Paprastas bolusas Aliarmai Valandinė bazė Bolusai - Angliavandeniai + AV Paros insulinas Klaidos Gliukozė @@ -369,7 +407,7 @@ Vienetai mg/dl mmol/l - IVT (Insulino Veikimo Trukmė) + IVT Tikslinis diapazonas: Vizualizacijos diapazonas Aukštoji ir žemoji riba Apžvalgos grafikuose bei išmaniuosiuose laikrodžiuose @@ -420,7 +458,7 @@ BPD Data Koeficientas - # dienų + # d. Svoris Duomenys netikslūs, jei bolusai naudojami kateterių užpildymui! Duomenys seni, spauskite \"ATNAUJINTI\" @@ -507,6 +545,9 @@ Suaugęs Insulinui rezistentiškas suaugęs Pasirinkite paciento amžių saugumo riboms nustatyti + Paciento vardas + Pateikite paciento vardą arba slapyvardį, kad galima būtų atskirti tarp skirtingų konfigūracijų. + Vartotojas Glimp %1$s įtraukite į baterijos optimizavimo baltąjį sąrašą tinkamam veikimui užtikrinti Ciklas sustabdytas @@ -543,8 +584,6 @@ Įgalinti superbolusus skaičiuoklėje Įgalina superbolusų naudojimą insulino skaičiuoklėje. Nenaudokite, kol nesuprantate, ką superbolus funkcija atlieka. NAUDODAMI AKLAI GALITE PERDOZUOTI INSULINO! Pradžios ekrane rodyti spalvotus indikatorius - Pradžios ekrane rodyti papildomus šviesos indikatorius - Pradžios ekrane rodyti papildomus šviesos indikatorius kateterio, insulino, sensoriaus naudojimo trukmei bei baterijos įkrovimo lygiui. Įspėjimo apie žemą rezervuaro lygį riba [U] Įspėjimo apie kritiškai žemą rezervuaro lygį riba [U] Įspėjimo apie žemą baterijos įkrovimo lygį riba [%] @@ -570,11 +609,11 @@ Sensorius Kateteris Insulinas - valandos + val. Netinkamas profilis!!! Profilio keitimas - Pompos baterija - Pompos baterijos keitimas + Baterija + Baterijos keitimas Aliarmų nustatymai Kritiškai aukštas Aukštas @@ -673,7 +712,7 @@ Prijungimo laikas baigėsi Maistas g - min + min. val d ]]> @@ -704,8 +743,13 @@ KG duomenų perdavimo nustatymai Rodyti gliukozės pokyčio detales Rodyti pokytį su reikšme po kablelio - SMB max minutės + Kaip dažnai SMB bus leidžiami, min. + SMB maks. minutės SMB atitinka valandinės bazės insulino kiekį, kuris gaunamas ne daugiau, kaip per + NDM SMB maks. min. + NDM SMB atitinka valandinės bazės insulino kiekį, kuris gaunamas ne daugiau, kaip per + Angliavandenių pasiūlymo riba + Kai angliavandeniai yra siūlomi, kaip gramų angliavandenių aktyvuos pranešimą Pompos programinės įrangos versija nepalaikoma Siųsti KG duomenis į xDrip+ Xdrip+ pasirinkite 640g/Eversense duomenų šaltinį @@ -771,7 +815,8 @@ Sight prieš %1$.2f h - %1$d minutės + %1$d min. + %1$dm Leisti SMB visada Leisti SMB visada, nepriklausomai nuo bolusų. Įmanoma tik naudojant patikimų, filtruotų KG duomenų šaltinį, pvz.: Dexcom G5 Leisti SMB po angliavandenių įvedimo @@ -819,7 +864,7 @@ Nuokrypiai Aktyvūs angliavandeniai Aktyvus insulinas organizme - Valandinės bazės + Bazė Veiksmas nepasirinktas, nieko neįvyks Pradėti \"Hipo\" LT Naudojama neužbaigta versija. Uždaras ciklas neaktyvus. @@ -853,7 +898,7 @@ reikšmė turi būti teigiama maksimalus bazės daugiklis maksimalus paros bazės daugiklis - Bolusas buvo suleistas per paskutines 3 minutes, praleidžiant SMB + Bolusas buvo suleistas per paskutines 3 minutes, SMB praleidžiamas Bazė nustatyta teisingai Ribojamas maks procentų kiekis %1$d%%, nes %2$s Bolusas ribojamas iki %1$.1f vv dėl %2$s @@ -935,6 +980,7 @@ Pradėti jūsų pirmąjį tikslą Leidimas Prašyti leidimo + Norint gauti pranešimus, programai reikalingas sisteminio lango leidimas Aplikacijai reikia vietos nustatymo leidimo BT skenavimui atlikti Aplikacijai reikia leidimo prieigai prie saugyklos, kad galėtų išsaugoti žurnalo įrašus Užklausa @@ -969,6 +1015,9 @@ = 100]]> Pasyvus laikinas tikslas mažina jautrumą + Rezistencija mažina tikslą + Kai nustatoma rezistencija, tikslinė gliukozės vertė sumažinama + Jautrumas didina tikslą Netinkami pompos nustatymai, patikrinkite dokumentaciją ir įsitikinkite, kad Quick info meniu yra pavadintas QUICK INFO, naudojant 360 configuration software. Pasirinktinis Didelis laiko neatitikimas @@ -978,6 +1027,7 @@ Dėmesio: jei aktyvuosite ir prijungsite prie aparatinės pompos, AndroidAPS nukopijuos bazės nustatymus iš profilio į pompą, pakeisdamas esančius nustatymus pompoje. Įsitikinkite, kad turimi bazės nustatymai AndroidAPS yra teisingi. Jei nesate tikri arba nenorite iš naujo keisti bazės nustatymų jūsų pompoje, paspauskite atšaukti ir pakartokite prijungimą prie pompos kitą kartą. Terapijos duomenys nepilni Serviso nustatymai + Gavėjo el. paštas Siunčiamų įrašų skaičius Servisas Serv @@ -1120,14 +1170,14 @@ Tomato (MiaoMiao) Tomato sekundė - minutė - valanda - diena + min. + val. + d. savaitė sekundės - minutės - valandos - dienų + min. + val. + d. savaičių Jūsų Tidepool vartotojo vardas, įprastai jūsų el. pašto adresas Vartotojo vardas @@ -1169,7 +1219,7 @@ Nustatyta, kad naudojate neteisingą versiją. Ciklas išjungtas! sena versija labai sena versija - Nauja versija pasiekiama mažiausiai %1$d dienų! Po %2$d grįšite prie stabdymo prie žemo, po %3$d ciklas bus išjungtas + Nauja versija pasiekiama mažiausiai %1$d d.! Po %2$d grįšite prie stabdymo prie žemo, po %3$d ciklas bus išjungtas 2 val %1$.2fV Dexcom programėlė (modifikuota) @@ -1234,7 +1284,7 @@ Pažadinti ir nustatyti Išvalyti Boluso bloką Išvalyti RileyLink nustatymus - Baterijos tipas (galios vaizdas) + Baterijos tipas (pagal galią) Nepasirinkta (paprastas vaizdas) Šarminė (išplėstinis vaizdas) Ličio (išplėstinis vaizdas) @@ -1311,7 +1361,7 @@ Operacija negalima. \n\n Pirmiausia turite sukonfigūruoti Medronic pompą prieš atliekant šią operaciją. Laiko pokytis didesnis nei 24 val. - Valandinės bazės + Bazė Nustatymai Pranešimai Statistika @@ -1328,7 +1378,7 @@ Aktyvi Užmigusi - Atšaukėte Bolusą, kuris jau buvo nustatytas pompoje. Medronic pompa nepalaiko šio atšaukimo, todėl turite jį atšaukti rankiniu būdu. Sustabdykite pompą ir vėl ją paleiskite (jei vis dar norite atšaukti Bolusą). Aplikacija perims pokyčius su kitu atnaujinimu (per mažiau nei 5 minutes). + Atšaukėte bolusą, kuris jau buvo nustatytas pompoje. Medronic pompa nepalaiko šio atšaukimo, todėl turite jį atšaukti rankiniu būdu. Sustabdykite pompą ir vėl ją paleiskite (jei vis dar norite atšaukti bolusą). Aplikacija perims pokyčius su kitu atnaujinimu (per mažiau nei 5 minutes). Negalima sužinoti dabartinės laikinos bazės. Negalima atšaukti dabartinės laikinos bazės. Operacija stabdoma. Profilio nustatymas nepavyko dėl per didelės nustatytos bazės: %1$s @@ -1390,9 +1440,9 @@ Pompa nepasirinkta Pasirinkite vienetus, kurių vertes norite parodyti Įkelti vietinio profilio pakeitimus į NS - IVT (Insulino Veikimo Trukmė) - IA (insulino/angliavandenių santykis) - JIF (jautrumo insulinui faktorius) + IVT + IA + JIF TIKSLAS Klonuoti Pirmiausia išsaugoti arba anuliuoti dabartinius pokyčius @@ -1434,5 +1484,13 @@ Ištęsto boluso funkcija sustabdys uždaro ciklo režimą ištęsto boluso veikimo metu. Ar tikrai norite patvirtinti savo pasirinkimą? Uždara ciklas išjungtas dėl ištęsto boluso veikimo IB (Ištęstas bolusas) + \"PhoneChecker\" + Grafiko meniu + AS + SMB užklausos laikas + SMB įvykdymo laikas + Laikinos bazės užklausos laikas + Laikinos bazės įvykdymo laikas + Insight pompos aliarmai diff --git a/app/src/main/res/values-nl-rNL/strings.xml b/app/src/main/res/values-nl-rNL/strings.xml index f35d153c0d..1d91d77a7f 100644 --- a/app/src/main/res/values-nl-rNL/strings.xml +++ b/app/src/main/res/values-nl-rNL/strings.xml @@ -105,7 +105,6 @@ Verschil: Configurator Doelen - OpenAPS MA Overzicht NS Profiel Eenvoudig profiel @@ -543,8 +542,6 @@ Activeer superbolus in de wizard Activeer de superbolus functie in de wizard. Activeer deze niet tot je begrijpt wat dit doet. OVERDOSIS IS MOGELIJK BIJ BLINDELINGS GEBRUIK! Toon statusindicatoren op startscherm - Toon uitgebreide statusindicatoren op overzicht scherm - Statusindicatoren inschakelen voor cage, iage, sage, reservoir en batterijniveau op het overzicht scherm. Drempel waarschuwing reservoir niveau [E] Drempel alarm reservoir niveau [E] Drempel waarschuwing batterij niveau [%] diff --git a/app/src/main/res/values-pl-rPL/objectives.xml b/app/src/main/res/values-pl-rPL/objectives.xml index a2be1d375e..d2daad672f 100644 --- a/app/src/main/res/values-pl-rPL/objectives.xml +++ b/app/src/main/res/values-pl-rPL/objectives.xml @@ -20,7 +20,9 @@ 1 tydzień sukcesu w działaniu pętli w ciągu dnia z regularnym wprowadzaniem spożywanych węglowodanów Włączanie dodatkowych funkcji do użytku, jak AMA Włączanie dodatkowych funkcji do użytku, jak SMB (Super Mikro Bolusy) + Włączanie automatyzacji Musisz przeczytać wiki i zwiększyć maxIOB, aby SMB działało dobrze! Dobrym początkiem jest maxIOB = średni bolus + 3 x maks. dzienna dawka bazowa + Przeczytaj dokumenty jak działa automatyzacja. Skonfiguruj swoje pierwsze proste zasady. Na początku zamiast działań pozwól AAPS wyświetlać powiadomienia. Gdy jesteś pewien, że automatyzacja jest uruchamiana we właściwym czasie, zastąp powiadomienie prawdziwymi działaniami. (https://androidaps.readthedocs.io/en/latest/EN/Usage/Automation.html) BG dostępne w NS Status pompy dostępny w NS Ręczne zarządzanie @@ -35,6 +37,7 @@ Wyświetl zawartość wtyczki Pętla (Loop) Użyj funkcji skalowania przez dłuższe przytrzymanie wykresu glikemii Wprowadź + Jeśli masz co najmniej 3 miesiące doświadczenia w zamkniętej pętli z innymi systemami, możesz zakwalifikować się do otrzymania kodu do pominięcia etapu nauki. Zobacz https://androidaps.readthedocs.io/en/latest/EN/Usage/Objectives.html#skip-targets. Kod został zaakceptowany Niepoprawny kod Potwierdź swoje umiejętności diff --git a/app/src/main/res/values-pl-rPL/protection.xml b/app/src/main/res/values-pl-rPL/protection.xml index 3ea04e700d..d2b1b43d2a 100644 --- a/app/src/main/res/values-pl-rPL/protection.xml +++ b/app/src/main/res/values-pl-rPL/protection.xml @@ -1,2 +1,23 @@ - + + Wymagane uwierzytelnienie + Umieść palec na czytniku linii papilarnych, aby zweryfikować swoją tożsamość + Ochrona ustawień + Ochrona aplikacji + Ochrona Bolusa + Hasło główne + Hasło ustawień + Hasło aplikacji + Hasło bolusa + Odblokuj ustawienia + Biometryczne + Hasło użytkownika + Bez ochrony + Z ochroną + Hasło główne nie jest ustawione!\n\nProszę ustawić swoje hasło główne w preferencjach (%1$s → %2$s) + Hasło ustawione! + Hasło nie ustawione + Hasło nie zostało zmienione + Hasło usunięte! + Wpisz hasło tutaj + diff --git a/app/src/main/res/values-pl-rPL/strings.xml b/app/src/main/res/values-pl-rPL/strings.xml index 1e75d9a959..769d87d688 100644 --- a/app/src/main/res/values-pl-rPL/strings.xml +++ b/app/src/main/res/values-pl-rPL/strings.xml @@ -105,7 +105,6 @@ Delta: Konfiguracja Zadania - OpenAPS MA Przegląd Profil Nightscout Prosty profil @@ -543,8 +542,14 @@ Zezwalaj na superbolus w kalkulatorze Włącz funkcję Superbolus w kalkulatorze. Nie uruchamiaj, dopóki nie nauczysz się jak ta funkcja działa. MOŻESZ DOPROWADZIĆ DO PRZEDAWKOWANIA INSULINY JEŻELI UŻYJESZ TEJ FUNKCJI NIE POSIADAJĄC ODPOWIEDNIEJ WIEDZY! Pokaż diody stanu na ekranie głównym - Pokaż diody stanu na ekranie głównym - Włącz diody stanu dla cage, iage, sage, rezerwuar i poziom baterii na ekranie głównym. + Ostrzeżenie o czasie wkłucia [h] + Krytyczny czas wkłucia [h] + Ostrzeżenie o czasie insuliny [h] + Krytyczny czas insuliny [h] + Ostrzeżenie o czasie sensora CGM [h] + Krytyczny czas sensora CGM [h] + Ostrzeżenie o czasie baterii [h] + Krytyczny czas baterii [h] Próg ostrzeżenia o poziomie zbiornika [U] Próg ostrzeżenia o krytycznym poziomie zbiornika [U] Próg ostrzeżenia o poziomie baterii [%] @@ -1433,4 +1438,6 @@ Wiadomość Wyczyścić kolejkę? Wszystkie dane w kolejce zostaną utracone! + Wskaźniki stanu + Kopiowanie ustawień z NS diff --git a/app/src/main/res/values-pt-rBR/objectives.xml b/app/src/main/res/values-pt-rBR/objectives.xml index 3ff8541944..76c269ca71 100644 --- a/app/src/main/res/values-pt-rBR/objectives.xml +++ b/app/src/main/res/values-pt-rBR/objectives.xml @@ -20,6 +20,7 @@ 1 semana de looping durante o dia com sucesso com entrada regular de hidratos de carbono A activar recursos adicionais para uso durante o dia, como assistente avançado de refeição Activando recursos adicionais para uso durante o dia, como SMB + A activar a automação Deverá ler a wiki e aumentar a IOB máx para que os SMBs funcionem devidamente! Inicialmente poderá considerar maxIOB=média dos bólus + 3 x a basal máxima Glic disponível no NS Estado da Bomba disponível no NS diff --git a/app/src/main/res/values-pt-rBR/protection.xml b/app/src/main/res/values-pt-rBR/protection.xml index 3ea04e700d..67ae6b40c1 100644 --- a/app/src/main/res/values-pt-rBR/protection.xml +++ b/app/src/main/res/values-pt-rBR/protection.xml @@ -1,2 +1,23 @@ - + + Autenticação necessária + Coloque o dedo sobre o leitor de impressões digitais para verificar a sua identidade + Definições Protecção + Protecção Aplicação + Protecção Bólus + Password Mestre + Definições Password + Password Aplicação + Password Bólus + Definições Desbloqueio + Biométrico + Password Personalizada + Sem Protecção + Protecção + A Password Mestre não está definida!\n\nPor favor, configure Password Mestre em Preferências (%1$s → %2$s) + Password foi definida! + Password não foi definida + Password não foi alterada + Password apagada! + Insira a password aqui + diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index dfe11392ab..93f7ede06e 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -43,6 +43,7 @@ Integração para as pessoas que fazem múltiplas injeções diárias para a sua terapia de diabetes Integração para as bombas que não têm qualquer driver ainda (Open Loop) A sensibilidade é calculada da mesma forma que Oref0, mas você pode especificar o período de tempo para o passado. A absorção mínima de hidratos de carbono é calculada a partir do tempo máximo de absorção de hidratos de carbono das preferências. + A sensibilidade é calculada a partir de dados das últimas 8h ou 24h (usando qualquer um que é mais sensível). Hidratos são cortados (se não absorvidos) após o tempo especificado nas preferências. O Plugin também calcula o UAM. A sensibilidade é calculada como uma média ponderada de desvios. Desvios mais recentes têm maior peso. A absorção mínima de hidratos de carbono é calculada a partir do tempo máximo de absorção de hidratos de carbono das preferências. Este algoritmo é o mais rápido em seguir as mudanças de sensibilidade. Receber valores de Glicose da aplicação Eversense modificada. Receber valores BG do Glimp. @@ -105,7 +106,6 @@ Delta: Configurador Objetivos - OpenAPS MA Visão geral Perfil NS Perfil simples @@ -218,17 +218,44 @@ Basal Máxima IOB que OpenAPS pode dar [U] Este valor é denominado Max IOB em contexto OpenAPS \nEste é o valor máximo de insulina em [U] que APS pode dar de uma vez. Dispensar + Será perguntado pela password mestre, que será usada para encriptar preferências exportadas. + Será perguntado pela password mestre, que será necessária para desencriptar preferências importadas. + Exportação cancelada! Preferências NÃO foram exportadas! + Importação cancelada! Preferências NÃO foram importadas! + Por favor, verifique as preferências antes da importação: + Preferências não podem ser importadas! + As preferências não devem ser importadas! Explicar problemas de importação… Detalhes de problemas de importação Importar Importar mesmo assim (PERIGOSO!) + As preferências foram criadas com uma variante diferente do AAPS (%1$s) enquanto tem: %2$s.\n\nAlgumas configurações podem estar ausentes ou inválidas - após a importação, por favor verifique e actualize suas preferências. + Preferências foram criadas num dispositivo diferente. Não há problema se estiver a importar de telefone diferente/antigo, mas se certifique que as preferências importadas estão corretas! + Está a usar formato ultrapassado herdado a partir de versões antigas do AAPS, o que não é seguro! Use-o apenas como um último recurso, se não tiver uma exportação no actual no formato JSON. + Preferências importadas já são %1$s dias antigas! Talvez tenha preferências mais actualizadas ou escolheu o ficheiro errado? Lembre-se de exportar preferências regularmente! + Formato de data-hora inválido! Formato do ficheiro Criado em Versão AAPS Variante de Compilação + A exportar nome do paciente do dispositivo + A exportar modelo do dispositivo Encriptação do Ficheiro Antigo Formato de Exportação Novo formato de encriptação + Novo formato de depuração (não encriptado) + Formato de exportação desconhecido + Ficheiro de configurações adulterado + Ficheiro de configurações é seguro + A usar um formato de configurações não seguro e não encriptado + Erro de formato JSON, campo necessário ausente (formato, conteúdo, metadados ou segurança) + Erro ao desencriptar, a password inserida não pode desencriptar o ficheiro + Ficheiro de verificação (hash) em falta, não é possível verificar a autenticidade de configurações! + Ficheiro foi modificado após exportação! + Erro Desencriptação, a análise de preferências falhou! + Erro de Desencriptação, a password é inválida ou configurações de arquivo foram modificadas! Pode acontecer que o ficheiro importado foi exportado com uma Password Mestre diferente. + Configuração de encriptação ausente, formato de configurações é inválido! + Algoritmo de encriptação não suportado ou não especificado! DanaR Conectando Conectado @@ -518,6 +545,8 @@ Adulto Adulto resistente insulina Por favor seleccione a idade do diabético para definir os limites de segurança + Nome do Paciente + Por favor, forneça nome do paciente ou alcunha para diferenciar entre várias configurações Utilizador Glimp %1$s necessita de autorizar a não optimização da bateria para assegurar a performance necessária @@ -555,8 +584,6 @@ Activar superbólus no assistente Habilite a funcionalidade de superbolus no assistente. Não habilite até que aprenda o funcionamento. PODE CAUSAR OVERDOSE DE INSULINA SE USAR INDISCRIMINADAMENTE! Mostrar luzes de estado no ecrã principal - Mostrar luzes de estado estendido no ecrã principal - Ativar as luzes de status estendida para idade da cânula, insulina, sensor, reservatório e bateria no ecrã inicial. Limite de aviso de nível de reservatório [U] Limite crítico de nível de reservatório [U] Limite de aviso de nível de bateria [%] @@ -716,8 +743,13 @@ Configurações de upload de BG Mostrar Delta detalho Mostrar delta com mais um ponto decimal + Com que frequência em min os SMBs serão dados SMB máx. minutos Limite de minutos de basal para SMB + UAM SMB máx minutos + Max minutos de basal para limitar SMB para UAM + Limite Sugestão de Hidratos + Quando Hidratos são sugeridos, quantos hidratos irá solicitar uma notificação Firmware bomba não suportado Enviar dados Glic. para xDrip+ Seleccionar 640g/Eversense como fonte no xDrip+ @@ -983,6 +1015,10 @@ = 100]]> Baixo alvotemp baixa sensibilidade + Resistência reduz alvo + Quando a resistência for detectada, diminui o alvo de glicose + Sensibilidade aumenta o alvo + Quando a sensibilidade é detectada, aumenta o alvo glicose Configuração da bomba inválida, verifique a documentação e se o menu de informações rápidas está nomeado de QUICK INFO utilizando o programa de configuração 360. Personalizado Grande diferença Horária @@ -992,6 +1028,8 @@ Atenção: Se conectar à sua bomba física e activar o perfil, o AndroidAPS irá copiar as definições desse perfil para as definições da bomba, apagando o memorizado na bomba. Por favor verifique que o que preencheu no perfil da app tem os mesmos valores que estão na bomba. Em caso contrario pressione imediatamente cancelar e corrija antes de voltar a ligar à bomba. Dados tratamento incompletos Configurações de manutenção + Email destinatário + Encriptar configurações exportadas Nr. de registos a enviar Manutenção MANU @@ -1199,6 +1237,8 @@ existe não existe Alvo Temp %1$s + Ligação Bluetooth com o dispositivo %1$s %2$s + Ligação ao dispositivo Bluetooth WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1458,7 +1498,31 @@ Hora de execução Basal Temp Alertas Bomba Insight + a partir da app Autenticador para: %1$s + Activar Autenticador + Autenticar comandos usando Uma-Password-Única que sejam geradas pelo Google Authenticator ou app 2FA similar. + PIN adicional no token final + Dígitos adicionais que devem ser memorizados e colados no final de cada Uma-Password-Única que seja gerada + Configuração do Autenticador + OTP para verificar: + Repor Autenticadores + Repor Chave Autenticador + Tem certeza de redefinir chave Authenticador? Ele tornará todos os Authenticators configurados actualmente como inválidos, e precisará de os configurar novamente. + Nova Chave do Autenticador foi gerada! Por favor, use o QRCode actualizado para os autenticadores. + 1. Instalar Autenticador + 2. Pesquise o código para configurar os códigos OTP do AndroidAPS + 3. Teste Uma-Password-Única + Repor Autenticadores + Instalar uma app Autenticador que suporte Tokens RFC 6238 TOTP em cada telefone seguidor. Populares aplicativos gratuitos são:\n • Authy\n • o Google Authenticator\n • LastPass Autenticador\n • FreeOTP Autenticador + NÃO PARTILHE este código online!\nUse-o apenas para a instalação da app Autenticador nos telefones seguidores. + Ao repor o autenticador, torna inválidos todos os autenticadores já provisionados. Precisará de os configurar novamente! Ao ligar Ao desligar Previsões + Desvio de inclinação + Falha na autorização + Insulina absoluta + Password Mestre é usada para encriptação da cópia de segurança e substituir segurança na aplicação. Lembre-se dela ou guarde-a em um lugar seguro. + As passwords não coincidem + Password Mestre actual diff --git a/app/src/main/res/values-pt-rBR/validator.xml b/app/src/main/res/values-pt-rBR/validator.xml index 3ea04e700d..d15d4fb95f 100644 --- a/app/src/main/res/values-pt-rBR/validator.xml +++ b/app/src/main/res/values-pt-rBR/validator.xml @@ -1,2 +1,21 @@ - + + Apenas dígitos numéricos são permitidos. + Apenas dígitos numéricos dentro de um intervalo de %1$s - %2$s são permitidos. + Este campo não pode conter qualquer carácter especial + Apenas letras padrão são permitidas + Este campo não deve estar vazio + Endereço de e-mail inválido + Número de cartão de crédito inválido + Número de telefone inválido + Nome de domínio inválido + Endereço IP inválido + Url do site não é válido + Não é um nome ou sobrenome válido. + Nome completo inválido. + Formato inválido + Deve ser número de 4 dígitos + Deve ser número de 6 dígitos + Não um comprimento mínimo + Pin deve ser de 3 a 6 dígitos, não o mesmo ou em série + diff --git a/app/src/main/res/values-pt-rPT/objectives.xml b/app/src/main/res/values-pt-rPT/objectives.xml index 4722ee8fa8..195da54c80 100644 --- a/app/src/main/res/values-pt-rPT/objectives.xml +++ b/app/src/main/res/values-pt-rPT/objectives.xml @@ -20,7 +20,9 @@ 1 semana de looping durante o dia com sucesso com entrada regular de hidratos de carbono A activar recursos adicionais para uso durante o dia, como assistente avançado de refeição Activando recursos adicionais para uso durante o dia, como SMB + A activar a automação Deverá ler a wiki e aumentar a IOB máx para que os SMBs funcionem devidamente! Inicialmente poderá considerar maxIOB=média dos bólus + 3 x a basal máxima + Leia os documentos de como a automação funciona. Configure primeiro regras simples. Em vez de acção deixe AAPS apresentar apenas a notificação. Quando tem certeza de automação é accionada no momento certo substitua a notificação por acção real. (https://androidaps.readthedocs.io/en/latest/EN/Usage/Automation.html) Glic disponível no NS Estado da Bomba disponível no NS Execução manual diff --git a/app/src/main/res/values-pt-rPT/protection.xml b/app/src/main/res/values-pt-rPT/protection.xml index 3ea04e700d..67ae6b40c1 100644 --- a/app/src/main/res/values-pt-rPT/protection.xml +++ b/app/src/main/res/values-pt-rPT/protection.xml @@ -1,2 +1,23 @@ - + + Autenticação necessária + Coloque o dedo sobre o leitor de impressões digitais para verificar a sua identidade + Definições Protecção + Protecção Aplicação + Protecção Bólus + Password Mestre + Definições Password + Password Aplicação + Password Bólus + Definições Desbloqueio + Biométrico + Password Personalizada + Sem Protecção + Protecção + A Password Mestre não está definida!\n\nPor favor, configure Password Mestre em Preferências (%1$s → %2$s) + Password foi definida! + Password não foi definida + Password não foi alterada + Password apagada! + Insira a password aqui + diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index c4ca9542cc..b31fcdf7d7 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -43,6 +43,7 @@ Integração para as pessoas que fazem múltiplas injeções diárias para a sua terapia de diabetes Integração para as bombas que não têm qualquer driver ainda (Open Loop) A sensibilidade é calculada da mesma forma que Oref0, mas você pode especificar o período de tempo para o passado. A absorção mínima de hidratos de carbono é calculada a partir do tempo máximo de absorção de hidratos de carbono das preferências. + A sensibilidade é calculada a partir de dados das últimas 8h ou 24h (usando qualquer um que é mais sensível). Hidratos são cortados (se não absorvidos) após o tempo especificado nas preferências. O Plugin também calcula o UAM. A sensibilidade é calculada como uma média ponderada de desvios. Desvios mais recentes têm maior peso. A absorção mínima de hidratos de carbono é calculada a partir do tempo máximo de absorção de hidratos de carbono das preferências. Este algoritmo é o mais rápido em seguir as mudanças de sensibilidade. Receber valores de Glicose da aplicação Eversense modificada. Receber valores Glucose do Glimp. @@ -105,7 +106,6 @@ Delta: Configurador Objetivos - OpenAPS MA Visão geral Perfil NS Perfil simples @@ -218,17 +218,44 @@ Basal Máxima IOB que OpenAPS pode dar [U] Este valor é denominado Max IOB em contexto OpenAPS \nEste é o valor máximo de insulina em [U] que APS pode dar de uma vez. Dispensar + Será perguntado pela password mestre, que será usada para encriptar preferências exportadas. + Será perguntado pela password mestre, que será necessária para desencriptar preferências importadas. + Exportação cancelada! Preferências NÃO foram exportadas! + Importação cancelada! Preferências NÃO foram importadas! + Por favor, verifique as preferências antes da importação: + Preferências não podem ser importadas! + As preferências não devem ser importadas! Explicar problemas de importação… Detalhes de problemas de importação Importar Importar mesmo assim (PERIGOSO!) + As preferências foram criadas com uma variante diferente do AAPS (%1$s) enquanto tem: %2$s.\n\nAlgumas configurações podem estar ausentes ou inválidas - após a importação, por favor verifique e actualize suas preferências. + Preferências foram criadas num dispositivo diferente. Não há problema se estiver a importar de telefone diferente/antigo, mas se certifique que as preferências importadas estão corretas! + Está a usar formato ultrapassado herdado a partir de versões antigas do AAPS, o que não é seguro! Use-o apenas como um último recurso, se não tiver uma exportação no actual no formato JSON. + Preferências importadas já são %1$s dias antigas! Talvez tenha preferências mais actualizadas ou escolheu o ficheiro errado? Lembre-se de exportar preferências regularmente! + Formato de data-hora inválido! Formato do ficheiro Criado em Versão AAPS Variante de Compilação + A exportar nome do paciente do dispositivo + A exportar modelo do dispositivo Encriptação do Ficheiro Antigo Formato de Exportação Novo formato de encriptação + Novo formato de depuração (não encriptado) + Formato de exportação desconhecido + Ficheiro de configurações adulterado + Ficheiro de configurações é seguro + A usar um formato de configurações não seguro e não encriptado + Erro de formato JSON, campo necessário ausente (formato, conteúdo, metadados ou segurança) + Erro ao desencriptar, a password inserida não pode desencriptar o ficheiro + Ficheiro de verificação (hash) em falta, não é possível verificar a autenticidade de configurações! + Ficheiro foi modificado após exportação! + Erro Desencriptação, a análise de preferências falhou! + Erro de Desencriptação, a password é inválida ou configurações de arquivo foram modificadas! Pode acontecer que o ficheiro importado foi exportado com uma Password Mestre diferente. + Configuração de encriptação ausente, formato de configurações é inválido! + Algoritmo de encriptação não suportado ou não especificado! DanaR A ligar Ligado @@ -518,6 +545,8 @@ Adulto Adulto resistente insulina Por favor seleccione a idade do diabético para definir os limites de segurança + Nome do Paciente + Por favor, forneça nome do paciente ou alcunha para diferenciar entre várias configurações Utilizador Glimp %1$s necessita de autorizar a não optimização da bateria para assegurar a performance necessária @@ -555,8 +584,14 @@ Activar superbólus no assistente Habilite a funcionalidade de superbolus no assistente. Não habilite até que aprenda o funcionamento. PODE CAUSAR OVERDOSE DE INSULINA SE USAR INDISCRIMINADAMENTE! Mostrar luzes de estado no ecrã principal - Mostrar luzes de estado no ecrã principal - Activar as luzes de estado para idade da cânula, idade da insulina, idade do sensor, reservatório e bateria no ecrã inicial. + Limite aviso idade canula [h] + Limite Crítico Idade Canula [h] + Limite aviso idade insulina [h] + Limite crítico idade insulina [h] + Limite aviso idade sensor [h] + Limite crítico idade sensor [h] + Limite de aviso de nível de bateria [h] + Limite crítico de nível de bateria [h] Limite de aviso de nível de reservatório [U] Limite crítico de nível de reservatório [U] Limite de aviso de nível de bateria [%] @@ -716,8 +751,13 @@ Configurações de upload de BG Mostrar Delta detalho Mostrar delta com mais um ponto decimal + Com que frequência em min os SMBs serão dados SMB máx. minutos Limite de minutos de basal para SMB + UAM SMB máx minutos + Max minutos de basal para limitar SMB para UAM + Limite Sugestão de Hidratos + Quando Hidratos são sugeridos, quantos hidratos irá solicitar uma notificação Firmware bomba não suportado Enviar dados Glic. para xDrip+ Seleccionar 640g/Eversense como fonte no xDrip+ @@ -983,6 +1023,10 @@ = 100]]> Baixo alvotemp baixa sensibilidade + Resistência reduz alvo + Quando a resistência for detectada, diminui o alvo de glicose + Sensibilidade aumenta o alvo + Quando a sensibilidade é detectada, aumenta o alvo glicose Configuração da bomba inválida, verifique a documentação e se o menu de informações rápidas está nomeado de QUICK INFO utilizando o programa de configuração 360. Personalizado Grande diferença Horária @@ -992,6 +1036,8 @@ Atenção: Se conectar à sua bomba física e activar o perfil, o AndroidAPS irá copiar as definições desse perfil para as definições da bomba, apagando o memorizado na bomba. Por favor verifique que o que preencheu no perfil da app tem os mesmos valores que estão na bomba. Em caso contrario pressione imediatamente cancelar e corrija antes de voltar a ligar à bomba. Dados tratamento incompletos Configurações de manutenção + Email destinatário + Encriptar configurações exportadas Nr. de registos a enviar Manutenção MANU @@ -1199,6 +1245,8 @@ existe não existe Alvo Temp %1$s + Ligação Bluetooth com o dispositivo %1$s %2$s + Ligação ao dispositivo Bluetooth WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1458,7 +1506,31 @@ Hora de execução Basal Temp Alertas Bomba Insight + a partir da app Autenticador para: %1$s + Activar Autenticador + Autenticar comandos usando Uma-Password-Única que sejam geradas pelo Google Authenticator ou app 2FA similar. + PIN adicional no token final + Dígitos adicionais que devem ser memorizados e colados no final de cada Uma-Password-Única que seja gerada + Configuração do Autenticador + OTP para verificar: + Repor Autenticadores + Repor Chave Autenticador + Tem certeza de redefinir chave Authenticador? Ele tornará todos os Authenticators configurados actualmente como inválidos, e precisará de os configurar novamente. + Nova Chave do Autenticador foi gerada! Por favor, use o QRCode actualizado para os autenticadores. + 1. Instalar Autenticador + 2. Pesquise o código para configurar os códigos OTP do AndroidAPS + 3. Teste Uma-Password-Única + Repor Autenticadores + Instalar uma app Autenticador que suporte Tokens RFC 6238 TOTP em cada telefone seguidor. Populares aplicativos gratuitos são:\n • Authy\n • o Google Authenticator\n • LastPass Autenticador\n • FreeOTP Autenticador + NÃO PARTILHE este código online!\nUse-o apenas para a instalação da app Autenticador nos telefones seguidores. + Ao repor o autenticador, torna inválidos todos os autenticadores já provisionados. Precisará de os configurar novamente! Ao ligar Ao desligar Previsões + Desvio de inclinação + Falha na autorização + Insulina absoluta + Password Mestre é usada para encriptação da cópia de segurança e substituir segurança na aplicação. Lembre-se dela ou guarde-a em um lugar seguro. + As passwords não coincidem + Password Mestre actual diff --git a/app/src/main/res/values-pt-rPT/validator.xml b/app/src/main/res/values-pt-rPT/validator.xml index 3ea04e700d..d15d4fb95f 100644 --- a/app/src/main/res/values-pt-rPT/validator.xml +++ b/app/src/main/res/values-pt-rPT/validator.xml @@ -1,2 +1,21 @@ - + + Apenas dígitos numéricos são permitidos. + Apenas dígitos numéricos dentro de um intervalo de %1$s - %2$s são permitidos. + Este campo não pode conter qualquer carácter especial + Apenas letras padrão são permitidas + Este campo não deve estar vazio + Endereço de e-mail inválido + Número de cartão de crédito inválido + Número de telefone inválido + Nome de domínio inválido + Endereço IP inválido + Url do site não é válido + Não é um nome ou sobrenome válido. + Nome completo inválido. + Formato inválido + Deve ser número de 4 dígitos + Deve ser número de 6 dígitos + Não um comprimento mínimo + Pin deve ser de 3 a 6 dígitos, não o mesmo ou em série + diff --git a/app/src/main/res/values-ro-rRO/strings.xml b/app/src/main/res/values-ro-rRO/strings.xml index b72c1dadd9..f4f0cf24c9 100644 --- a/app/src/main/res/values-ro-rRO/strings.xml +++ b/app/src/main/res/values-ro-rRO/strings.xml @@ -104,7 +104,6 @@ Diferență: Configurator Obiective - OpenAPS MA Privire de ansamblu Profil NS Profil simplu @@ -517,8 +516,6 @@ Activează superbolus în asistent Activează funcționalitatea de superbolus în asistentul de buclă. Nu activați până nu înțelegeți ce face cu adevărat. DACĂ ESTE FOLOSIT ÎN NECUNOȘTINȚĂ DE CAUZĂ POATE DUCE LA SUPRADOZĂ DE INSULINĂ! Afișați indicatorii luminoși ai pompei pe ecranul de start - Afișați indicatorii luminoși referitori la starea detaliată a pompei pe ecranul principal - Activați indicatori pentru CAGE, IAGE, SAGE, nivel baterie și rezervor pe ecranul principal. Pragul de avertisment pentru insulina din rezervor [U] Pragul critic al nivelului insulinei în rezervor [U] IOB diff --git a/app/src/main/res/values-ru-rRU/objectives.xml b/app/src/main/res/values-ru-rRU/objectives.xml index 38c25925e7..bc0e840894 100644 --- a/app/src/main/res/values-ru-rRU/objectives.xml +++ b/app/src/main/res/values-ru-rRU/objectives.xml @@ -20,7 +20,9 @@ 1 неделя успешной дневной работы с регулярным введением углеводов Активация таких доп функций для дневного времени как расширенный калькулятор болюса advanced meal assist Активация таких доп функций для дневного времени как супер микро болюс SMB + Включение автоматизации Прочтите wiki и увеличьте maxIOB чтобы супер микро болюс SMB заработал как положено! Хорошее начало – maxIOB = средний болюс на еду + троекратный максимальный суточный базал + Прочтите документацию по автоматизации. Настройте свои первые простые правила. Вместо действия позвольте AAPS только выводить уведомления. Если вы уверены, что автоматизация инициируется в нужное время, замените уведомление реальным действием. гликемия доступна в NS Статус помпы доступен в NS Ввод вручную diff --git a/app/src/main/res/values-ru-rRU/protection.xml b/app/src/main/res/values-ru-rRU/protection.xml index 3ea04e700d..6198bca5d9 100644 --- a/app/src/main/res/values-ru-rRU/protection.xml +++ b/app/src/main/res/values-ru-rRU/protection.xml @@ -1,2 +1,23 @@ - + + Требуется авторизация + Поместите палец на устройство считывания отпечатков, чтобы подтвердить свою идентичность + Защита настроек + Защита приложения + Защита болюсов + Главный пароль + Пароль параметров + Пароль приложения + Пароль болюсов + Разблокировать настройки + Биометрия + Настраиваемый пароль + Без защиты + Защита + Не задан главный пароль!\n\nЗадайте главный пароль в настройках (%1$s → %2$s) + Пароль задан! + Пароль не задан + Пароль не был изменён + Пароль сброшен! + Введите пароль здесь + diff --git a/app/src/main/res/values-ru-rRU/strings.xml b/app/src/main/res/values-ru-rRU/strings.xml index 7f549201e0..dc101ab364 100644 --- a/app/src/main/res/values-ru-rRU/strings.xml +++ b/app/src/main/res/values-ru-rRU/strings.xml @@ -43,6 +43,7 @@ Интеграция с помпой для тех, кто делает многочисленные подколки для компенсации диабета Интеграция с помпами, еще не имеющими драйвера (незамкнутый цикл) Чувствительность вычисляется аналогично алгоритму oref0, но можно включить период прошлого. Минимальное усвоение углеводов вычисляется на основе макс усвоения из настроек. + Чувствительность рассчитывается на основе данных за прошедшие 8 часов и (неусвоенные) углеводы не учитываются после времени указанного в настройках. Плагин также вычисляет UAM. Чувствительность рассчитывается как средневзвешенное от отклонений (deviations). Более поздние отклонения имеют больший вес. Минимальное усвоение углеводов рассчитывается на основе макс времени усвоения углеводов в настройках. Этот алгоритм быстрее всего отслеживает изменения чувствительности. Получать данные гликемии от пропатченного приложения Eversense. Получать данные гликемии от Glimp. @@ -105,7 +106,6 @@ дельта: конфигуратор Цели - Помощник болюса OpenAPS MA начало профиль NS простой профиль @@ -218,6 +218,44 @@ макс базал активн инс подаваемый с OpenAPS (ед) Эта величина называется Max IOB (макс активн инс) в OpenAPS\n. Это макс кол-во инсулина в ед. [U] которое APS может подать единовременно. отклонить + Будет предложено ввести главный пароль, который будет использоваться для шифрования экспортированных параметров. + Вам будет предложено ввести главный пароль, необходимый для расшифровки импортированных настроек. + Экспорт отменен! Настройки НЕ экспортированы! + Импорт отменен! Настройки не импортированы! + Проверьте настройки перед импортом: + Не удается импортировать настройки! + Не следует импортировать настройки! + Объяснить проблемы импорта… + Сведения о проблемах импорта + Импортировать + Импортировать в любом случае (ОПАСНО!) + Параметры были созданы с другим вариантом AAPS (%1$s) в то время как у вас: %2$s.\n\nНекоторые параметры могут отсутствать или быть недопустимы-после импорта проверьте и обновите параметры. + Параметры созданы на другом устройстве. Это нормально, если вы импортируете из старого/другого телефона, но убедитесь, что импортированные параметры - верные! + Вы используете устаревший формат из старых версий AAPS, который не безопасен! Используйте его только в крайнем случае, если у вас нет экспорта в текущем формате JSON. + Импортируемым параметрам уже %1$s дней! Может быть у вас есть более актуальные параметры или вы выбрали неправильный файл? Не забудьте регулярно экспортировать параметры! + Недопустимый формат даты и времени! + Формат файла + Дата создания + Версия AAPS + Версия сборки + Имя пациента экспортируемого устройства + Модель экспортируемого устройства + Шифрование файла + Старый формат экспорта + Новый зашифрованный формат + Новый формат отладки (незашифрованный) + Неизвестный формат экспорта + Файл параметров несанкционированно изменен + Файл настроек безопасен + Применяется незащищенный, незашифрованный формат параметров + Ошибка формата JSON, отсутствует обязательное поле (формат, содержимое, метаданные или защита) + Ошибка расшифровки, указанный пароль не может расшифровать файл + Отсутствует контрольная сумма файла (хэш), не удалось проверить подлинность параметров! + Файл был изменен после экспорта! + Ошибка расшифровки, не удалось проанализировать настройки! + Ошибка расшифровки, указан недопустимый пароль или файл параметров изменен! Возможно, импортированный файл был экспортирован с использованием другого главного пароля. + Отсутствует конфигурация шифрования, формат параметров недопустим! + Неподдерживаемый или не прописанный алгоритм шифрования! DanaR соединение устанавливается соединение установлено @@ -507,6 +545,9 @@ взрослый Инсулинорезистентный взрослый выберите возраст пациента для определения ограничителей безопасности + Имя пациента + Укажите имя или псевдоним пациента, чтобы распознавать разные настройки + Пользователь Glimp %1$s необходимо включить в белый список оптимизации батареи для корректной работы ЗЦ остановлен @@ -543,8 +584,14 @@ активировать суперболюс активировать возможность суперболюса в мастере. не активируйте если не знаете что это. МОЖЕТ ВЫЗВАТЬ ПЕРЕДОЗИРОВКУ ИНСУЛИНА ЕСЛИ ИСПОЛЬЗУЕТСЯ ВСЛЕПУЮ Показать индикаторы состояния на главном экране - Показывать подробные индикаторы состояния на главном экране - Включить на главном экране подробные индикаторы отработанного времени для канюли помпы, инсулина, сенсора, резервуара, а также уровня заряда батареи. + Порог предупреждения о времени, отработанном катетером [h] + Критический порог предупреждения о времени, отработанном катетером [h] + Порог предупреждения о времени, отработанном инсулином [h] + Критический порог предупреждения о времени, отработанном инсулином [h] + Порог предупреждения о времени, отработанном сенсором [h] + Критический порог предупреждения о времени, отработанном сенсором [h] + Порог предупреждения о разрядке батареи [h] + Порог предупреждения о критическом уровне разрядки батареи [h] Порог уровня наполненности резервуара для оповещения [ед.] Порог критического уровня наполненности резервуара [U] Порог предупреждения о разрядке батареи [%] @@ -704,8 +751,13 @@ Параметры загрузки СК Показать подробно дельту Показать дельту еще с одним десятичным знаком + Как часто SMB будут подаваться в минутах Максимум минут микроболюса SMB Верхний лимит минут базала на SMB + Максимум минут микроболюса SMB для непредвиденного приема пищи UAM + Максимум минут базала ограничивающего микроболюсы SMB на непредвиденный прием пищи UAM + Порог предлагаемых углеводов + Когда предлагаются углеводы, какое количество инициирует уведомление Неподдерживаемая версия прошивки помпы Отправить данные СК на xDrip+ В xDrip + выберите источник данных 640g/Eversense @@ -772,6 +824,7 @@ тому назад %1$.2f ч %1$d мин + %1$dm Всегда включать супер микро болюс SMB Всегда включать супер микро болюс SMB независимо от болюсов. Возможно только для источников СК с хорошей фильтрацией данных вроде G5 Активировать супер микро болюс SMB после углеводов @@ -972,6 +1025,10 @@ Context | Edit Context = 100]]> Низкая временная цель temptarget снижает чувствительность = 100]]> + Сопротивляемость понижает цель + При обнаружении сопротивляемости целевой уровень гликемии понижается + Чувствительность поднимает цель + При обнаружении чувствительности целевой уровень глюкозы повышается Недопустимые установки помпы, проверьте документацию и убедитесь, что меню Quick Info называется QUICK INFO, используя приложение 360 для конфигурации помпы. Пользовательские Большая разница во времени @@ -981,6 +1038,8 @@ Context | Edit Context Внимание: Если вы активируете подключение к невиртуальной помпе, AndroidAPS скопирует настройки базала в профиль помпы, перезаписывая существующие настройки, хранящиеся в ней. Убедитесь, что настройки базала в AndroidAPS корректны. Если вы не уверены или не хотите перезаписать настройки базала на помпу, нажмите отменить и повторите подключение в другое время. Данные терапии неполные Параметры обслуживания + Адрес электронной почты + Зашифровать экспортируемые параметры Количество логов для отправки Обслуживание ОБСЛУЖ @@ -1188,6 +1247,8 @@ Context | Edit Context существует не существует Врем цель %1$s + Подключение Bluetooth к устройству %1$s %2$s + Соединение с устройством Bluetooth WiFi SSID %1$s %2$s Автосенс %1$s %2$s %% Автосенс % @@ -1242,6 +1303,7 @@ Context | Edit Context Щелочная (Подробный вид) Литиевая (Подробный вид) NiZn (Подробный вид) + Никель-металлогидридная (подробно) Отладка Болюс/Назначения СКАН @@ -1257,6 +1319,7 @@ Context | Edit Context Сканирование Сканирование завершено Ошибка сканирования: %1$d + Никогда Настройки История @@ -1390,6 +1453,7 @@ Context | Edit Context Очистить начатые Определение времени Хотите сбросить начатую цель? Можете потерять уже достигнутое. + Изменение времени и/или часового пояса на помпе Помпа не выбрана Выберите единицы, в которых вы хотите отображать значения Перенести изменения локального профиля в NS @@ -1446,4 +1510,34 @@ Context | Edit Context Время выполнения временной базальной скорости Оповещения помпы Insight + из приложения Authenticator на: %1$s + Включить аутентификатор + Аутентифицировать команды с помощью одноразовых паролей, сгенерированных Google Authenticator или похожими приложениями 2FA. + Дополнительный PIN-код в конце маркера + Дополнительные цифры, которые должны быть запомнены и добавлены в конце каждого сгенерированного одноразового пароля + Настройка аутентификации + OTP для проверки: + Сбросить аутентификаторы + Сбросить ключ идентификации + Вы действительно хотите сбросить ключ аутентификации? Все сконфигурированные в настоящее время ключи станут недопустимы, и придется их настроить заново. + Создан новый ключ аутентификации! Для идентификации используйте обновленный QRCode. + 1. Установить Аутентификатор + 2. Код сканирования для настройки кодов OTP AndroidAPS + 3. Одноразовый Пароль + Сбросить аутентификаторы + В каждом отслеживающем телефоне установите приложение Authenticator, поддерживающее маркеры TOTP RFC 6238. Популярные бесплатные приложения: \n Authy\n Google Authenticator\n LastPass Authenticator\n FreeOTP Authenticator + Не переправляйте этот код через интернет!\nИспользуйте его только для настройки приложения Authenticator на отслеживающих телефонах. + После сброса аутентификатора вы делаете все созданные идентификаторы недействительными. Вам нужно будет снова создать их! + При подключении + При отключении + Прогнозирование + Линия отклонения + Ошибка авторизации + Абсолютный инсулин + Главный пароль используется для шифрования резервных копий и для переопределения защиты в приложении. Запомните его или храните в безопасном месте. + Пароли не совпадают + Текущий главный пароль + Индикаторы состояния + Копировать параметры из NS + Копировать настройки NS (если есть)? diff --git a/app/src/main/res/values-ru-rRU/validator.xml b/app/src/main/res/values-ru-rRU/validator.xml index 3ea04e700d..38ad359082 100644 --- a/app/src/main/res/values-ru-rRU/validator.xml +++ b/app/src/main/res/values-ru-rRU/validator.xml @@ -1,2 +1,21 @@ - + + Можно вводить только цифры. + Разрешены только цифровые значения в диапазоне %1$s - %2$s. + Это поле не может содержать специальные символы + Разрешены только стандартные буквы + Поле не может быть пустым + Недопустимый адрес электронной почты + Недопустимый номер кредитной карты + Некорректный номер телефона + Недопустимое имя домена + Недопустимый IP + Недопустимый Url-адрес + Недопустимое имя или фамилия. + Недопустимое полное имя. + Недопустимый формат + Должен быть 4-значным числом + Должен быть 6-значным числом + Не минимальной длины + Пин-код должен состоять из 3-6 цифр, не одинаковых или идущих подряд + diff --git a/app/src/main/res/values-sk-rSK/objectives.xml b/app/src/main/res/values-sk-rSK/objectives.xml index 5da99833ad..b76ff17397 100644 --- a/app/src/main/res/values-sk-rSK/objectives.xml +++ b/app/src/main/res/values-sk-rSK/objectives.xml @@ -20,7 +20,9 @@ Jeden týždeň úspešného používania s bežným príjmom sacharidov Povolenie doplnkových funkcií pre každodenné použitie, ako napr. pokročilý asistent jedál (AMA) Povoliť ďalšie funkcie pre bežné používanie ako SMB + Povolenie automatiky Prečítať si dokumentáciu a zvýšiť maximálne IOB, aby mohlo správne fungovať SMB! Pre začiatok sa dá použiť veľkosť bežného bolusu + 3x maximálny denný bazál + Prečítajte si dokumentáciu na wiki, ako automatika funguje. Najskôr nastavte iba jednoduché pravidlá. Namiesto vykonávania akcií nechajte AAPS zobrazovať iba oznámenia. Pokiaľ ste si istý, že automatika je spustená v správnom čase, môžete oznámenie nahradiť vykonaním akcie.(https://androidaps.readdocs.io/en/latest/CROWDIN/cs/Usage/Automation.html) Glykémia dostupná v NS Stav pumpy dostupný v NS Spustené manuálne diff --git a/app/src/main/res/values-sk-rSK/protection.xml b/app/src/main/res/values-sk-rSK/protection.xml index 3ea04e700d..99bcd7815b 100644 --- a/app/src/main/res/values-sk-rSK/protection.xml +++ b/app/src/main/res/values-sk-rSK/protection.xml @@ -1,2 +1,23 @@ - + + Vyžaduje sa autentifikácia + Priložte prst na čítačku odtlačkov prstov pre overenie vašej totožnosti + Ochrana nastavení + Ochrana aplikácie + Ochrana bolusu + Hlavné heslo + Heslo pre nastavenia + Heslo aplikácie + Heslo pre bolus + Odomknúť nastavenia + Biometria + Vlastné heslo + Bez ochrany + Ochrana + Hlavné heslo nie je nastavené!\n\nProsím nastavte svoje hlavné heslo v nastaveniach (%1$s → %2$s) + Heslo nastavené! + Heslo nie je nastavené + Heslo nezmenené + Heslo vymazané! + Zadajte heslo + diff --git a/app/src/main/res/values-sk-rSK/strings.xml b/app/src/main/res/values-sk-rSK/strings.xml index 62336b935b..572d405cf4 100644 --- a/app/src/main/res/values-sk-rSK/strings.xml +++ b/app/src/main/res/values-sk-rSK/strings.xml @@ -43,6 +43,7 @@ Ovládač pumpy pre užívateľov používajúcich k liečbe diabetu inzulínové perá Ovládač pumpy pre užívateľov bez podporovanej pumpy (Otvorený okruh) Citlivosť je počítaná tým istým spôsobom ako v Oref0, ale je možné špecifikovať časové okno do minulosti. Minimálne vstrebávanie sacharidov je počítané dynamicky z maximálnej doby vstrebávania, definovanej v nastaveniach. + Citlivosť je počítaná za posledných 8h, alebo 24h (použiť to, ktoré je citlivejšie) a sacharidy (pokiaľ nie sú vstrebané), sú orezané po čase definovanom v nastaveniach. Modul tiež počíta s UAM (neoznámené jedlo). Citlivosť je počítaná ako vážený priemer z odchýlok. Novšie majú vyššiu prioritu. Minimálna vstrebateľnosť sacharidov je počítaná dynamicky z maximálnej doby vstrebateľnosti definovanej v nastaveniach. Tento algoritmus je najrýchlejší v sledovaní zmien citlivosti. Získavať glykémie z upravenej Eversense aplikácie. Získavať hodnoty glykémií z aplikácie Glimp. @@ -105,7 +106,6 @@ Rozdiel: Konfigurácia Ciele - OpenAPS MA Prehľad NS Profil Jednoduchý profil @@ -218,6 +218,44 @@ Maximálny bazálny IOB, ktorý OpenAPS môže podať [JI] Táto hodnota je nazývaná v kontexte OpenAPS ako max IOB, je to maximálne množstvo inzulínu v [JI], ktoré APS môže naraz podať. POTVRDIŤ + Budete vyzvaný na zadanie hlavného hesla, ktoré bude použité na dešifrovanie exportovaných nastavení. + Budete vyzvaný na zadanie hlavného hesla, ktoré bude použité na dešifrovanie importovaných nastavení. + Export zrušený! Nastavenia neboli exportované! + Import zrušený! Nastavenia neboli importované! + Prosím skontrolujte nastavenia predtým, ako importujete: + Nastavenia nemôžu byť importované! + Nastavenia by nemali byť importované! + Vysvetli chyby pri importe... + Podrobnosti chýb pri importe + Importovať + Importovať rovnako (NEBEZPEČNÉ!) + Nastavenia boli vytvorené inou verziou AAPS (%1$s) pretože máte: %2$s.\n\nNiektoré nastavenia môžu chýbať, alebo byť poškodené - po importovaní prosím skontrolujte a upravte nastavenia. + Nastavenia boli vytvorené na inom zariadení. Je to v poriadku, keď importujete zo staršieho/iného telefónu, ale skontrolujte, že importované nastavenia sú správne! + Používate zastaralý formát zo staršej verzie AAPS, čo nie je bezpečné! Používajte len ako poslednú možnosť, ak nemáte export v aktuálnom, JSON formáte. + Importované nastavenia sú už %1$s dní staré! Možno máte viacero novších nastavení, alebo ste zvolili nesprávny súbor? Nezabúdajte pravidelne exportovať nastavenia! + Nesprávny formát dátumu a času! + Formát súboru + Vytvorené + Verzia AAPS + Verzia zostavy + Meno pacienta použité pri exporte + Model zariadenia použitý pri exporte + Šifrovanie súborov + Zastaralý formát exportu + Nový šifrovaný formát + Nový formát pre ladenie (nešifrovaný) + Neznámy formát exportu + Súbor s nastaveniami poškodený + Súbor s nastaveniami je zabezpečený + Použitie nezabezpečeného, nešifrovaného formátu nastavení + Chyba formátu JSON, chýba povinné pole (formát, obsah, metadáta, alebo zabezpečenie) + Chyba dešifrovania, dané heslo nemôže dešifrovať súbor + Chýba kontrolný súčet súboru (hash), nedá sa overiť pravosť nastavení! + Súbor bol po exporte zmenený! + Chyba dešifrovania, analýza nastavení zlyhala! + Chyba dešifrovania, zadané heslo je neplatné, alebo bol súbor nastavení zmenený! Môže sa stať, že importovaný súbor bol exportovaný s iným hlavným heslom. + Chýba konfigurácia šifrovania, formát nastavení je neplatný! + Nepodporovaný alebo neurčený šifrovací algoritmus! DanaR Pripájanie Pripojené @@ -507,6 +545,9 @@ Dospelý Dospelý s nízkou citlivosťou Vyberte vek pacienta pre nastavenie bezpečnostných limitov + Meno pacienta + Zadajte meno pacienta, alebo prezývku pre rozlíšenie medzi viacerými nastaveniami + Používateľ Glimp %1$s potrebuje vypnúť optimalizáciu batérie pre optimálny výkon Uzavretý okruh pozastavený @@ -543,8 +584,14 @@ Povoliť superbolus Povolenie superbolusu v kalkulátore. Nepovoľujte, pokiaľ se nenaučíte, čo to v skutočnosti robí. MÔŽE SPÔSOBIŤ PREDÁVKOVANIE INZULÍNOM PRI NESPRÁVNOM POUŽITÍ! Zobraziť indikátory stavu na domovskej obrazovke - Zobraziť rozšírené indikátory stavu na domovskej obrazovke - Povoliť rozšírené indikátory stavu pre CAGE, IAGE, SAGE, Reservoir a Battery Level na domovskej obrazovke. + Prah upozornenia na vek kanyly [h] + Prah kritického veku kanyly [h] + Prah upozornenia na vek inzulínu [h] + Prah kritického veku inzulínu [h] + Prah upozornenia na vek senzora [h] + Prah kritického veku senzora [h] + Prah upozornenia na úroveň batérie [h] + Prah kritickej úrovne batérie [h] Prah upozornenia na úroveň hladiny zásobníka [JI] Prah kritickej úrovne hladiny zásobníka [JI] Prah upozornenia na úroveň batérie [%] @@ -704,8 +751,13 @@ Nastavenie nahrávania glykémie Zobrazovať detailné zmeny Zobrazovať rozdiel s jedným desatinným miestom naviac + Ako často budú SMB podávané (v minutách) SMB max. minút Maximálny počet minút bazálu, ku ktorým se limituje SMB + UAM SMB max. minút + Maximální počet minút bazálu, ku ktorým sa limituje SMB pre UAM + Prahová hodnota doporučenia sacharidov + Po navrhnutí sacharidov, aké množstvo sacharidov vyvolá upozornenie Nepodporovaný firmware v pumpe Odosielať glykémie do xDrip+ V xDrip+ vyberte zdroj dát 640g/Eversense @@ -772,6 +824,7 @@ pred %1$.2f h %1$d min + %1$dm Vždy povoliť SMB Povoliť SMB nezávisle na bolusoch. Možno iba zo zdrojom glykémií s dobrým filtrovaním dát, ako napr. G5 Povoliť SMB po jedle @@ -970,6 +1023,10 @@ = 5.5]]> Nízky dočasný cieľ zníži citlivosť + Rezistancia znižuje cieľ + Ak je zistená rezistancia, znížiť cieľovú hladinu glykémie + Citlivosť zvyšuje cieľ + Ak je zistená vyššia citlivosť, zvýši cieľovú hladinu glykémie Chybné nastavenie pumpy. Prejdite si dokumentáciu a presvedčte sa, že menu Quick Info se nazýva QUICK INFO, s použitím 360° Configuration Software. Voliteľný Veľký rozdiel v čase @@ -979,6 +1036,8 @@ POZOR: Pokiaľ aktivujete a pripojíte skutočnú pumpu, AndroidAPS nakopíruje (a bude udržiavať) nastavenie bazálu z aktívneho profilu do pumpy. Nastavenie bazálu v pumpe bude prepísané. Pokiaľ si nieste istí, alebo nechcete prepísať bazály v pumpe, stlačte Zrušiť a opakujte prepnutie na inú pumpu neskôr. Dáta ošetrení neúplné Nastavenie údržby + E-Mail + Šifrovať exportované nastavenia Počet protokolov na odoslanie Údržba Údržba @@ -1186,6 +1245,8 @@ existuje neexistuje Dočasný cieľ %1$s + Pripojenie Bluetooth k zariadeniu %1$s %2$s + Pripojenie k zariadeniu Bluetooth WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1240,6 +1301,7 @@ Alkalické (rozšírené zobrazenie) Líthiové (rozšírené zobrazenie) NiZn (Rozšírené) + NiMH (Rozšírené zobrazenie) Bolus/Ošetrenia ladenie VYHĽADAŤ @@ -1255,6 +1317,7 @@ Vyhľadávanie Vyhľadávanie dokončené Chyba vyhľadávania: %1$d + Nikdy Nastavenia História @@ -1388,6 +1451,7 @@ Vymazanie začaté Detekcia času Chcete resetovať začiatok cieľa? Môžete prísť o svoj pokrok. + Zmena času a/alebo časovej zóny na pumpe Nie je vybraná žiadna pumpa Vyberte jednotky, v ktorých chcete zobraziť hodnoty Odoslať zmeny lokálneho profilu do NS @@ -1444,4 +1508,34 @@ Čas spustenia dočasného bazálu Výstrahy pumpy Insight + z aplikácie Authenticator pre: %1$s + Povoliť Autentifikátor + Autentifikačné príkazy používajú jednorázové heslá generované Google Authenticator, alebo podobnými 2FA aplikáciami. + Ďalší PIN na konci tokenu + Ďalšie číslice, ktoré by mali byť zapamätané a pridané na koniec každého vygenerovaného jednorázového hesla + Nastavenie autentifikátora + OTP pre kontrolu: + Resetovať autentifikátory + Resetovať autentifikačný kľúč + Ste si istý, že chcete obnoviť autentifikačný kľúč? Vyresetujete tým všetky aktuálne nakonfigurované autentikátory a budete ich musieť znovu nastaviť. + Bol vygenerovaný nový autentifikačný kľúč! Prosím, použite aktualizovaný QR kód pre nastavenie autentifikátorov. + 1. Nainštalujte Autentifikátor + 2. Naskenujte kód pre nastavenie AndroidAPS OTP kódov + 3. Odtestujte jednorázové heslo + Resetovať autentifikátory + Na každom sledovacom telefóne nainštalujte Autentifikátor, ktorý podporuje tokeny TOTP RFC 6238. Najobľúbenejšie bezplatné aplikácie sú:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator + NEZDIEĽAJTE tento kód on-line!\nPoužiť iba na nastavenie Autentifikátora na sledujúcich telefónoch. + Resetovaním autentifikátora budú všetky už poskytnuté autentifikátory neplatné. Budete ich musieť znovu nastaviť! + Pri pripojení + Pri odpojení + Predikcie + Odchýlka sklonu + Autorizácia zlyhala + Celkový inzulín + Hlavné heslo sa používa na šifrovanie zálohy a na \"prebitie\" zabezpečenia v aplikácii. Dobre si ho zapamätajte, alebo uložte na bezpečnom mieste. + Heslá sa nezhodujú + Aktuálne hlavné heslo + Indikátory stavu + Kopírovať nastavenia z NS + Skopírovať nastavenia NS (ak existujú)? diff --git a/app/src/main/res/values-sk-rSK/validator.xml b/app/src/main/res/values-sk-rSK/validator.xml index 3ea04e700d..4962884868 100644 --- a/app/src/main/res/values-sk-rSK/validator.xml +++ b/app/src/main/res/values-sk-rSK/validator.xml @@ -1,2 +1,21 @@ - + + Povolené sú iba číslice. + Povolené iba čísla v rozsahu %1$s - %2$s. + Toto pole nemôže obsahovať žiadne špeciálne znaky + Sú povolené iba štandardné písmená + Toto pole nesmie byť prázdne + E-mailová adresa je neplatná + Číslo kreditnej karty je neplatné + Neplatné telefónne čislo + Názov domény je neplatný + IP Adresa je neplatná + Webová adresa je neplatná + Neplatné krstné meno, alebo priezvisko. + Nie je platné celé meno. + Formát nie je platný + Musí byť 4-miestne číslo + Musí byť 6-miestne číslo + Nie je splnená minimálna dĺžka + PIN by mal byť z 3 až 6 číslic, nie rovnakých, alebo za sebou nasledujúcich číslic + diff --git a/app/src/main/res/values-sv-rSE/objectives.xml b/app/src/main/res/values-sv-rSE/objectives.xml index 94b2ba5549..6f53a9be76 100644 --- a/app/src/main/res/values-sv-rSE/objectives.xml +++ b/app/src/main/res/values-sv-rSE/objectives.xml @@ -20,7 +20,9 @@ 1 veckas lyckad looping dagtid, där alla måltider lagts in Aktiverar extra funktioner som kan användas dagtid, såsom avancerad måltidsassistans, AMA Aktiverar ytterligare funktioner för användning dagtid, t ex SMB + Aktivera automatisering Du måste läsa på wikin och öka max IOB för att få SMB att fungera bra. En bra start är att sätta max IOB till din genomsnittliga måltidsbolus plus 3 gånger den högsta basalen du har under ett dygn + Läs dokumentationen hur automatisering fungerar. Konfigurera dina första enkla regler. I stället för att ange en åtgärd, låt bara AAPS visa en avisering. När du är säker på att automatisering utlöses vid rätt tidpunkt ersätt aviseringen med verklig åtgärd. (https://androidaps.readthedocs.io/en/latest/EN/Usage/Automation.html) BG är tillängligt i Nightscout Pumpstatus tillgängligt i Nightscout Manuella justeringar diff --git a/app/src/main/res/values-sv-rSE/protection.xml b/app/src/main/res/values-sv-rSE/protection.xml index 3ea04e700d..2586a94122 100644 --- a/app/src/main/res/values-sv-rSE/protection.xml +++ b/app/src/main/res/values-sv-rSE/protection.xml @@ -1,2 +1,23 @@ - + + Autentisering krävs + Placera fingret på fingeravtrycksläsaren för att verifiera din identitet + Skydd för inställningar + Skydd för app + Bolusskydd + Huvudlösenord + Lösenord för inställningar + Lösenord för app + Lösenord för bolus + Lås upp inställningar + Biometri + Eget lösenord + Inget skydd + Skydd + Huvudlösenord har inte angetts.\n\nAnge huvudlösenord i Inställningar (%1$s → %2$s) + Lösenord sparat! + Lösenord inte inställt + Lösenordet har inte ändrats + Lösenordet togs bort! + Ange lösenord här + diff --git a/app/src/main/res/values-sv-rSE/strings.xml b/app/src/main/res/values-sv-rSE/strings.xml index bd32a29734..7c4cc40f29 100644 --- a/app/src/main/res/values-sv-rSE/strings.xml +++ b/app/src/main/res/values-sv-rSE/strings.xml @@ -43,6 +43,7 @@ Integration för de som endast använder insulinpennor Integration för pumpar som ännu inte stöds av AndroidAPS (Open loop) Känsligheten beräknas på samma sätt som i Oref0, men du kan specificera hur mycket av historiken som ska tas med i beräkningen. Minimalt upptag av kolhydrater beräknas utifrån maximal upptagstid för kolhydrater som angetts i Inställningar. + Känsligheten beräknas både från 8 och 24 timmars data från historiken och väljer det resultat som har högst insulinkänslighet. Kolhydrater som ännu inte räknats av ignoreras efter tiden som ställts in i inställningarna. Insticksprogrammet beräknar också icke inmatade måltider, UAM. Känsligheten beräknas som ett viktat medelvärde av avvikelserna. Senare avvikelser får en högre vikt. Minimal upptagning av kolhydrater beräknas utifrån maximal upptagstid för kolhydrater som angetts i inställningarna. Den här algoritmen är den snabbaste att justera förändringar i känsligheten. Ta emot BG-data från den modifierade Eversense-appen. @@ -106,7 +107,6 @@ Eversense-appen. Delta: Konfigurationsverktyg Mål - OpenAPS MA Översikt NS-profil Enkel profil @@ -219,6 +219,44 @@ Eversense-appen. Maximal basal IOB som OpenAPS kan ge [E] Detta värde kallas Max IOB i OpenAPS. Det är ställt till noll från start. Efter flera dagar till veckor, beroende på hur du känner, kan du välja att justera denna. TA BORT + Du kommer att bli tillfrågad om huvudlösenordet som sedan kommer att användas för att kryptera exporterade inställningar. + Du kommer att bli tillfrågad om huvudlösenordet som sedan kommer att användas för att avkryptera importerade inställningar. + Exporten avbröts. Inställningarna har INTE exporterats! + Importen avbröts. Inställningarna har inte importerats! + Vänligen kontrollera inställningarna innan du importerar: + Inställningarna kan inte importeras! + Inställningar bör inte importeras! + Förklara importproblem… + Detaljer kring importproblem + Importera + Importera ändå (FARLIGT!) + Inställningar skapades med en annan variant av AAPS (%1$s). Du kör nu: %2$s.\n\nVissa inställningar kan saknas eller är ogiltiga. Efter att du importerat bör du kontrollera och uppdatera inställningarna. + Inställningar skapades på en annan enhet. Det är OK om du importerar från en äldre eller en annan telefon, men se till att importerade inställningar är korrekta! + Du använder det gamla formatet (från äldre versioner av AAPS) som inte är säkert. Använd det bara som en sista utväg om du inte har någon export i aktuellt format, JSON. + Importerade inställningar är %1$s dagar gamla. Du kanske har mer aktuella inställningar eller väljer du fel fil? Kom ihåg att exportera dina inställningar regelbundet! + Ogiltigt datumformat! + Filformat + Skapad + AAPS-version + Build-variant + Exporterar patientens namn + Exporterar enhetsmodell + · Filkryptering + Gammalt exportformat + Nytt krypterat format + Nytt debug-format (okrypterat) + Okänt exportformat + Inställningsfil manipulerad + Inställningsfilen är intakt + Använder icke säkrat, okrypterat format + JSON-formatfel, saknar obligatoriskt fält (format, innehåll, metadata eller säkerhet) + Dekrypteringsfel. Det angivna lösenordet kan inte dekryptera filen + Filen checksumma (hash) saknas. Det går inte att verifiera inställningarna! + Filen har ändrats efter export! + Dekrypteringsfel. Det gick inte att tolka inställningarna. + Dekrypteringsfel. Det angivna lösenordet är ogiltigt eller så har inställningsfilen ändrats. Filen verkar ha exporterats med ett annat lösenord. + Krypteringskonfigurationen saknas. Inställningsformatet är ogiltigt! + Ej stödd eller ej angiven krypteringsalgoritm! Dana R Ansluter Ansluten @@ -508,6 +546,9 @@ Eversense-appen. Vuxen Insulinresistent vuxen Vg ange personens ålder för inställningar av gränser + Patientens namn + Vänligen ange patientens namn eller smeknamn för att kunna skilja mellan flera uppsättningar av inställningar + Ditt namn Glimp %1$s behöver kunna kringgå batterisparfunktionerna för att fungera korrekt Loop pausad @@ -544,8 +585,6 @@ Eversense-appen. Aktivera superbolus i kalkylatorn Aktiverar superbolusfunktionen i kalkylatorn. Aktivera inte innan du förstått hur den fungerar. DEN KAN ORSAKA ÖVERDOSERING AV INSULIN OM INSIKT SAKNAS OM FUNKTIONEN! Visa \"statuslampor\" på hemskärmen - Visa utökade statusindikatorer - Aktivera statusindikatorerna för cage, iage, sage, reservoar och batterinivå på hemskärmen. Varningsnivå för reservoar [U] Akut varningsnivå för reservoar [U] Varningsnivå för batteri [%] @@ -705,8 +744,13 @@ Eversense-appen. Uppladdningsinställningar för BG Visa detaljerad delta Visa delta med en extra decimal + Minsta antal minuter mellan SMB SMB max minuter Max antal minuter som kan bli SMB + UAM SMB max minuter + Max antal minuter basal som kan bli SMB vid UAM + Min föreslagen mängd kolhydrater + När kolhydrater rekommenderas som korrektion, ange minsta mängd KH som ger notifiering Pumpens firmware stöds inte Skicka BG-data till xDrip+ Välj \"640G/Eversense\" som datakälla i xDrip+ @@ -773,6 +817,7 @@ Eversense-appen. sedan %1$.2f h %1$d min + %1$dm Använd alltid SMB Använd alltid SMB oberoende av bolus. Endast möjligt med en bra filtrerad BG-källa, t ex Dexcom G5. Använd SMB efter kolhydrater @@ -971,6 +1016,10 @@ Eversense-appen. Lågt målvärde sänker känsligheten + Insulinresistens sänker mål-BG + Om systemet upptäcker tillfällig insulinresistens, sänk mål-BG för att på så sätt tillåta mer insulin + Insulinkänslighet höjer mål-BG + Om systemet upptäcker tillfällig insulinkänslighet, höj mål-BG för att på så sätt minska insulindoseringen Felaktig pumpinstallation. Kontrollera dokumentationen och verifiera att Snabbmenyn heter QUICK INFO med hjälp av 360-mjukvaran. Anpassad Stor tidsskillnad @@ -980,6 +1029,8 @@ Eversense-appen. Varning: Om du aktiverar och ansluter en pump, kommer AndroidAPS skriva över pumpens basalprofil med den aktiva profilen i AndroidAPS. Se till att ha rätt inställningar i appen innan du ansluter. Om du är osäker, tryck på Avbryt och anslut pumpen på nytt vid ett senare tillfälle. Behandlingsdata ofullständigt Underhållsinställningar + e-postmottagare + Kryptera exporterade inställningar Antal loggar att skicka Underhåll UH @@ -1187,6 +1238,8 @@ Eversense-appen. finns finns inte Temp mål %1$s + Bluetooth-anslutning till enhet %1$s %2$s + Anslutning till Bluetooth-enhet WiFi SSID %1$s %2$s Autosens %1$s %2$s %% Autosens % @@ -1241,6 +1294,7 @@ Eversense-appen. Alkaliskt Litium NiZn (utökad vy) + NiMH (utökad vy) Avlusning av Bolus/Behandlingar SÖK @@ -1445,4 +1499,31 @@ Eversense-appen. Basalförändring utförd Pumpvarningar Insight + från autentiseringsapp för: %1$s + Aktivera autentiseraren + Autentisera kommandon med hjälp av engångslösenord som genererats av Google Authenticator eller liknande appar för tvåfaktorsautentisering. + Extra PIN-kod + Ytterligare siffror som ska memoreras och läggas till i slutet av varje genererat engångslösenord + Konfiguration av tvåfaktorsautentisering + Engångslösenord att kontrollera: + Återställ autentiserare + Återställ autentiseringsnyckel + Är du säker på att återställa autentiseringsnyckeln? Det gör alla konfigurerade autentiseringsappar ogiltiga och du kommer behöva ställa in dem igen. + Ny autentiseringsnyckel genererades! Använd uppdaterad QR-kod till att aktivera autentiserare. + 1. Installera autentiseringsapp + 2. Scanna koden för att ställa in engångslösenord för AndroidAPS + 3. Testa engångslösenord + Återställ autentiserare + På varje följartelefon behöver man installera en autentiseringsapp som stöder RFC 6238 TOTP tokens. Populära gratisappar är:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator + DELA INTE denna kod online!\nAnvänd den endast för att installera autentiseringsappen på följartelefoner. + Genom att återställa autentiseringsfunktionen kommer alla redan driftsatta autentiserare bli ogiltiga. Du kommer behöva sätta upp dem igen! + Vid anslutning + Vid frånkoppling + Beräknade resultat + Avvikelsekurva + Behörighetskontroll misslyckades + Absolut insulinmängd + Huvudlösenordet används för att kryptera backuper och för att åsidosätta vissa säkerhetsfunktioner i applikationen. Kom ihåg det eller förvara det på ett säkert ställe. + Lösenorden stämmer inte överens + Nuvarande huvudlösenord diff --git a/app/src/main/res/values-sv-rSE/validator.xml b/app/src/main/res/values-sv-rSE/validator.xml index 3ea04e700d..3b2288d895 100644 --- a/app/src/main/res/values-sv-rSE/validator.xml +++ b/app/src/main/res/values-sv-rSE/validator.xml @@ -1,2 +1,21 @@ - + + Endast siffror tillåtna. + Endast siffror mellan %1$s - %2$s är tillåtna. + Det här fältet får inte innehålla något specialtecken + Endast vanliga bokstäver är tillåtna + Detta fält får inte vara tomt + Ogiltig e-postadress + Ogiltigt kreditkortsnummer + Ogiltigt telefonnummer + Ogiltigt domännamn + Ogiltig IP-adress + Ogiltig URL + Ogiltigt för- eller efternamn. + Ogiltigt namn + Ogiltigt format + Måste vara fyra siffror + Måste vara sex siffror + För kort + Pin ska vara 3-6 siffror, inte samma eller efter varandra + diff --git a/app/src/main/res/values-tr-rTR/strings.xml b/app/src/main/res/values-tr-rTR/strings.xml index e596cbc9b0..733b287549 100644 --- a/app/src/main/res/values-tr-rTR/strings.xml +++ b/app/src/main/res/values-tr-rTR/strings.xml @@ -100,7 +100,6 @@ Delta: Konfigurasyon oluştur Hedefler - OpenAPS MA Genel Bakış Nightscout Profil Basit Profil diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 9afcdb66e9..0ae0966cf2 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -102,7 +102,6 @@ 增量: 配置生成器 目标 - OpenAPS MA 首页概览 NS 配置文件 简单配置文件