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; - } - - }