Merge remote-tracking branch 'origin/mdtrefactor' into dev

This commit is contained in:
Milos Kozak 2020-04-26 16:17:19 +02:00
commit 2eb0122dd6
47 changed files with 642 additions and 590 deletions

View file

@ -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.local.LocalProfileFragment
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import info.nightscout.androidaps.plugins.pump.combo.ComboFragment 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.danaR.DanaRFragment
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment
@ -113,4 +115,7 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesWizardInfoDialog(): WizardInfoDialog @ContributesAndroidInjector abstract fun contributesWizardInfoDialog(): WizardInfoDialog
@ContributesAndroidInjector abstract fun contributesPasswordCheck(): PasswordCheck @ContributesAndroidInjector abstract fun contributesPasswordCheck(): PasswordCheck
@ContributesAndroidInjector abstract fun contributesRileyLinkStatusGeneral(): RileyLinkStatusGeneralFragment
@ContributesAndroidInjector abstract fun contributesRileyLinkStatusHistoryFragment(): RileyLinkStatusHistoryFragment
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector 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.RileyLinkBluetoothStateReceiver
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver
import info.nightscout.androidaps.receivers.* import info.nightscout.androidaps.receivers.*
@Module @Module
@ -17,4 +18,6 @@ abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
@ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver @ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver
} }

View file

@ -70,6 +70,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
.enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump)); .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump));
*/ */
protected PumpDescription pumpDescription = new PumpDescription(); protected PumpDescription pumpDescription = new PumpDescription();
@Deprecated // TODO remove this reference
protected PumpStatus pumpStatus; protected PumpStatus pumpStatus;
protected ServiceConnection serviceConnection = null; protected ServiceConnection serviceConnection = null;
protected boolean serviceRunning = false; protected boolean serviceRunning = false;

View file

@ -60,6 +60,8 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
@Inject SP sp; @Inject SP sp;
@Inject RxBusWrapper rxBus; @Inject RxBusWrapper rxBus;
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject RileyLinkUtil rileyLinkUtil;
@Inject MedtronicUtil medtronicUtil;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 30241; // arbitrary. private static final int PERMISSION_REQUEST_COARSE_LOCATION = 30241; // arbitrary.
private static final int REQUEST_ENABLE_BT = 30242; // arbitrary private static final int REQUEST_ENABLE_BT = 30242; // arbitrary
@ -108,9 +110,9 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
sp.putString(RileyLinkConst.Prefs.RileyLinkAddress, bleAddress); sp.putString(RileyLinkConst.Prefs.RileyLinkAddress, bleAddress);
RileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress); rileyLinkUtil.getRileyLinkSelectPreference().setSummary(bleAddress);
MedtronicPumpStatus pumpStatus = MedtronicUtil.getPumpStatus(); MedtronicPumpStatus pumpStatus = medtronicUtil.getPumpStatus();
pumpStatus.verifyConfiguration(); // force reloading of address pumpStatus.verifyConfiguration(); // force reloading of address
rxBus.send(new EventMedtronicPumpConfigurationChanged()); rxBus.send(new EventMedtronicPumpConfigurationChanged());
@ -189,7 +191,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
} }
// disable currently selected RL, so that we can discover it // disable currently selected RL, so that we can discover it
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnect); rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnect);
} }

View file

@ -51,8 +51,8 @@ public abstract class RileyLinkCommunicationManager {
public RileyLinkCommunicationManager(RFSpy rfspy) { public RileyLinkCommunicationManager(RFSpy rfspy) {
this.rfspy = rfspy; this.rfspy = rfspy;
this.rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData(); this.rileyLinkServiceData = RileyLinkUtil.getInstance().getRileyLinkServiceData();
RileyLinkUtil.setRileyLinkCommunicationManager(this); RileyLinkUtil.getInstance().setRileyLinkCommunicationManager(this);
configurePumpSpecificSettings(); configurePumpSpecificSettings();
} }
@ -151,7 +151,7 @@ public abstract class RileyLinkCommunicationManager {
// **** FIXME: this wakeup doesn't seem to work well... must revisit // **** FIXME: this wakeup doesn't seem to work well... must revisit
// receiverDeviceAwakeForMinutes = duration_minutes; // receiverDeviceAwakeForMinutes = duration_minutes;
MedtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp);
if (force) if (force)
nextWakeUpRequired = 0L; nextWakeUpRequired = 0L;
@ -195,7 +195,7 @@ public abstract class RileyLinkCommunicationManager {
public double tuneForDevice() { public double tuneForDevice() {
return scanForDevice(RileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies()); return scanForDevice(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies());
} }
@ -209,7 +209,7 @@ public abstract class RileyLinkCommunicationManager {
*/ */
public boolean isValidFrequency(double frequency) { public boolean isValidFrequency(double frequency) {
double[] scanFrequencies = RileyLinkUtil.getRileyLinkTargetFrequency().getScanFrequencies(); double[] scanFrequencies = RileyLinkUtil.getInstance().getRileyLinkTargetFrequency().getScanFrequencies();
if (scanFrequencies.length == 1) { if (scanFrequencies.length == 1) {
return RileyLinkUtil.isSame(scanFrequencies[0], frequency); return RileyLinkUtil.isSame(scanFrequencies[0], frequency);

View file

@ -5,8 +5,7 @@ import android.content.Intent;
import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.slf4j.Logger; import org.jetbrains.annotations.NotNull;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@ -15,9 +14,12 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import info.nightscout.androidaps.logging.L; import javax.inject.Inject;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import javax.inject.Singleton;
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.common.hw.rileylink.ble.RileyLinkBLE; 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.Encoding4b6b;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding.Encoding4b6bGeoff; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.encoding.Encoding4b6bGeoff;
@ -42,143 +44,160 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDe
* Created by andy on 17/05/2018. * Created by andy on 17/05/2018.
*/ */
@Singleton
public class RileyLinkUtil { public class RileyLinkUtil {
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP); public List<RLHistoryItem> historyRileyLink = new ArrayList<>();
protected static List<RLHistoryItem> historyRileyLink = new ArrayList<>(); public RileyLinkCommunicationManager rileyLinkCommunicationManager;
protected static RileyLinkCommunicationManager rileyLinkCommunicationManager;
static ServiceTask currentTask; static ServiceTask currentTask;
private static Context context; private RileyLinkBLE rileyLinkBLE;
private static RileyLinkBLE rileyLinkBLE; private RileyLinkServiceData rileyLinkServiceData;
private static RileyLinkServiceData rileyLinkServiceData; private RileyLinkService rileyLinkService;
private static RileyLinkService rileyLinkService; private RileyLinkTargetFrequency rileyLinkTargetFrequency;
private static RileyLinkTargetFrequency rileyLinkTargetFrequency;
private static RileyLinkTargetDevice targetDevice; private RileyLinkTargetDevice targetDevice;
private static RileyLinkEncodingType encoding; private RileyLinkEncodingType encoding;
private static RileyLinkSelectPreference rileyLinkSelectPreference; private RileyLinkSelectPreference rileyLinkSelectPreference;
private static Encoding4b6b encoding4b6b; private Encoding4b6b encoding4b6b;
private static RileyLinkFirmwareVersion firmwareVersion; private RileyLinkFirmwareVersion firmwareVersion;
public static void setContext(Context contextIn) { @NotNull private final Context context;
RileyLinkUtil.context = contextIn; @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;
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; return encoding;
} }
public static void setEncoding(RileyLinkEncodingType encoding) { public void setEncoding(RileyLinkEncodingType encoding) {
RileyLinkUtil.encoding = encoding; this.encoding = encoding;
if (encoding == RileyLinkEncodingType.FourByteSixByteLocal) { if (encoding == RileyLinkEncodingType.FourByteSixByteLocal) {
RileyLinkUtil.encoding4b6b = new Encoding4b6bGeoff(); this.encoding4b6b = new Encoding4b6bGeoff();
} }
} }
public static void sendBroadcastMessage(String message) { public void sendBroadcastMessage(String message) {
if (context != null) { Intent intent = new Intent(message);
Intent intent = new Intent(message); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
LocalBroadcastManager.getInstance(RileyLinkUtil.context).sendBroadcast(intent);
}
} }
public static void setServiceState(RileyLinkServiceState newState) { public void setServiceState(RileyLinkServiceState newState) {
setServiceState(newState, null); setServiceState(newState, null);
} }
public static RileyLinkError getError() { public RileyLinkError getError() {
if (RileyLinkUtil.rileyLinkServiceData != null) if (rileyLinkServiceData != null)
return RileyLinkUtil.rileyLinkServiceData.errorCode; return rileyLinkServiceData.errorCode;
else else
return null; return null;
} }
public static RileyLinkServiceState getServiceState() { public RileyLinkServiceState getServiceState() {
return workWithServiceState(null, null, false); return workWithServiceState(null, null, false);
} }
public static void setServiceState(RileyLinkServiceState newState, RileyLinkError errorCode) { public void setServiceState(RileyLinkServiceState newState, RileyLinkError errorCode) {
workWithServiceState(newState, errorCode, true); workWithServiceState(newState, errorCode, true);
} }
private static synchronized RileyLinkServiceState workWithServiceState(RileyLinkServiceState newState, private synchronized RileyLinkServiceState workWithServiceState(RileyLinkServiceState newState,
RileyLinkError errorCode, boolean set) { RileyLinkError errorCode, boolean set) {
if (set) { if (set) {
RileyLinkUtil.rileyLinkServiceData.serviceState = newState; rileyLinkServiceData.serviceState = newState;
RileyLinkUtil.rileyLinkServiceData.errorCode = errorCode; rileyLinkServiceData.errorCode = errorCode;
if (L.isEnabled(L.PUMP)) aapsLogger.info(LTag.PUMP, "RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: "
LOG.info("RileyLink State Changed: {} {}", newState, errorCode == null ? "" : " - Error State: " + errorCode.name());
+ errorCode.name());
RileyLinkUtil.historyRileyLink.add(new RLHistoryItem(RileyLinkUtil.rileyLinkServiceData.serviceState, historyRileyLink.add(new RLHistoryItem(rileyLinkServiceData.serviceState,
RileyLinkUtil.rileyLinkServiceData.errorCode, targetDevice)); rileyLinkServiceData.errorCode, targetDevice));
RxBus.Companion.getINSTANCE().send(new EventMedtronicDeviceStatusChange(newState, errorCode)); rxBus.send(new EventMedtronicDeviceStatusChange(newState, errorCode));
return null; return null;
} else { } else {
return (RileyLinkUtil.rileyLinkServiceData == null || RileyLinkUtil.rileyLinkServiceData.serviceState == null) ? // return (rileyLinkServiceData == null || rileyLinkServiceData.serviceState == null) ? //
RileyLinkServiceState.NotStarted RileyLinkServiceState.NotStarted
: RileyLinkUtil.rileyLinkServiceData.serviceState; : rileyLinkServiceData.serviceState;
} }
} }
public static RileyLinkBLE getRileyLinkBLE() { public RileyLinkBLE getRileyLinkBLE() {
return RileyLinkUtil.rileyLinkBLE; return rileyLinkBLE;
} }
public static void setRileyLinkBLE(RileyLinkBLE rileyLinkBLEIn) { public void setRileyLinkBLE(RileyLinkBLE rileyLinkBLEIn) {
RileyLinkUtil.rileyLinkBLE = rileyLinkBLEIn; rileyLinkBLE = rileyLinkBLEIn;
} }
public static RileyLinkServiceData getRileyLinkServiceData() { public RileyLinkServiceData getRileyLinkServiceData() {
return RileyLinkUtil.rileyLinkServiceData; return rileyLinkServiceData;
} }
public static void setRileyLinkServiceData(RileyLinkServiceData rileyLinkServiceData) { public void setRileyLinkServiceData(RileyLinkServiceData rileyLinkServiceData) {
RileyLinkUtil.rileyLinkServiceData = rileyLinkServiceData; this.rileyLinkServiceData = rileyLinkServiceData;
} }
public static boolean hasPumpBeenTunned() { public boolean hasPumpBeenTunned() {
return RileyLinkUtil.rileyLinkServiceData.tuneUpDone; return rileyLinkServiceData.tuneUpDone;
} }
public static RileyLinkService getRileyLinkService() { public RileyLinkService getRileyLinkService() {
return RileyLinkUtil.rileyLinkService; return rileyLinkService;
} }
public static void setRileyLinkService(RileyLinkService rileyLinkService) { public void setRileyLinkService(RileyLinkService rileyLinkService) {
RileyLinkUtil.rileyLinkService = rileyLinkService; this.rileyLinkService = rileyLinkService;
} }
public static RileyLinkCommunicationManager getRileyLinkCommunicationManager() { public RileyLinkCommunicationManager getRileyLinkCommunicationManager() {
return RileyLinkUtil.rileyLinkCommunicationManager; return rileyLinkCommunicationManager;
} }
public static void setRileyLinkCommunicationManager(RileyLinkCommunicationManager rileyLinkCommunicationManager) { void setRileyLinkCommunicationManager(RileyLinkCommunicationManager rileyLinkCommunicationManager) {
RileyLinkUtil.rileyLinkCommunicationManager = rileyLinkCommunicationManager; this.rileyLinkCommunicationManager = rileyLinkCommunicationManager;
} }
@ -222,13 +241,13 @@ public class RileyLinkUtil {
} }
public static RileyLinkTargetFrequency getRileyLinkTargetFrequency() { public RileyLinkTargetFrequency getRileyLinkTargetFrequency() {
return RileyLinkUtil.rileyLinkTargetFrequency; return rileyLinkTargetFrequency;
} }
public static void setRileyLinkTargetFrequency(RileyLinkTargetFrequency rileyLinkTargetFrequency) { public void setRileyLinkTargetFrequency(RileyLinkTargetFrequency rileyLinkTargetFrequency) {
RileyLinkUtil.rileyLinkTargetFrequency = rileyLinkTargetFrequency; this.rileyLinkTargetFrequency = rileyLinkTargetFrequency;
} }
@ -286,44 +305,42 @@ public class RileyLinkUtil {
} }
public static List<RLHistoryItem> getRileyLinkHistory() { public List<RLHistoryItem> getRileyLinkHistory() {
return historyRileyLink; return historyRileyLink;
} }
public static RileyLinkTargetDevice getTargetDevice() { public RileyLinkTargetDevice getTargetDevice() {
return targetDevice; return targetDevice;
} }
public static void setTargetDevice(RileyLinkTargetDevice targetDevice) { public void setTargetDevice(RileyLinkTargetDevice targetDevice) {
RileyLinkUtil.targetDevice = targetDevice; this.targetDevice = targetDevice;
} }
public static void setRileyLinkSelectPreference(RileyLinkSelectPreference rileyLinkSelectPreference) { public void setRileyLinkSelectPreference(RileyLinkSelectPreference rileyLinkSelectPreference) {
this.rileyLinkSelectPreference = rileyLinkSelectPreference;
RileyLinkUtil.rileyLinkSelectPreference = rileyLinkSelectPreference;
} }
public static RileyLinkSelectPreference getRileyLinkSelectPreference() { public RileyLinkSelectPreference getRileyLinkSelectPreference() {
return rileyLinkSelectPreference; return rileyLinkSelectPreference;
} }
public static Encoding4b6b getEncoding4b6b() { public Encoding4b6b getEncoding4b6b() {
return RileyLinkUtil.encoding4b6b; return encoding4b6b;
} }
public static void setFirmwareVersion(RileyLinkFirmwareVersion firmwareVersion) { public void setFirmwareVersion(RileyLinkFirmwareVersion firmwareVersion) {
RileyLinkUtil.firmwareVersion = firmwareVersion; this.firmwareVersion = firmwareVersion;
} }
public static RileyLinkFirmwareVersion getFirmwareVersion() { public RileyLinkFirmwareVersion getFirmwareVersion() {
return firmwareVersion; return firmwareVersion;
} }
} }

View file

@ -91,7 +91,7 @@ public class RFSpy {
public void initializeRileyLink() { public void initializeRileyLink() {
bleVersion = getVersion(); bleVersion = getVersion();
firmwareVersion = getFirmwareVersion(); firmwareVersion = getFirmwareVersion();
RileyLinkUtil.setFirmwareVersion(firmwareVersion); RileyLinkUtil.getInstance().setFirmwareVersion(firmwareVersion);
} }
@ -296,7 +296,7 @@ public class RFSpy {
this.currentFrequencyMHz = freqMHz; this.currentFrequencyMHz = freqMHz;
configureRadioForRegion(RileyLinkUtil.getRileyLinkTargetFrequency()); configureRadioForRegion(RileyLinkUtil.getInstance().getRileyLinkTargetFrequency());
} }
@ -403,7 +403,7 @@ public class RFSpy {
if (resp.isOK()) { if (resp.isOK()) {
reader.setRileyLinkEncodingType(encoding); reader.setRileyLinkEncodingType(encoding);
RileyLinkUtil.setEncoding(encoding); RileyLinkUtil.getInstance().setEncoding(encoding);
} }
return resp; return resp;

View file

@ -142,7 +142,7 @@ public class RileyLinkBLE {
if (newState == BluetoothProfile.STATE_CONNECTED) { if (newState == BluetoothProfile.STATE_CONNECTED) {
if (status == BluetoothGatt.GATT_SUCCESS) { if (status == BluetoothGatt.GATT_SUCCESS) {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.BluetoothConnected);
} else { } else {
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("BT State connected, GATT status {} ({})", status, getGattStatusMessage(status)); 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" : // LOG.debug("We are in {} state.", status == BluetoothProfile.STATE_CONNECTING ? "Connecting" :
// "Disconnecting"); // "Disconnecting");
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) { } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkDisconnected);
if (manualDisconnect) if (manualDisconnect)
close(); close();
LOG.warn("RileyLink Disconnected."); LOG.warn("RileyLink Disconnected.");
@ -240,19 +240,19 @@ public class RileyLinkBLE {
if (rileyLinkFound) { if (rileyLinkFound) {
mIsConnected = true; mIsConnected = true;
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkReady);
// RileyLinkUtil.sendNotification(new // RileyLinkUtil.sendNotification(new
// ServiceNotification(RileyLinkConst.Intents.RileyLinkReady), null); // ServiceNotification(RileyLinkConst.Intents.RileyLinkReady), null);
} else { } else {
mIsConnected = false; mIsConnected = false;
RileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkError, RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.RileyLinkError,
RileyLinkError.DeviceIsNotRileyLink); RileyLinkError.DeviceIsNotRileyLink);
} }
} else { } else {
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("onServicesDiscovered " + getGattStatusMessage(status)); LOG.debug("onServicesDiscovered " + getGattStatusMessage(status));
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkGattFailed);
} }
} }
}; };

View file

@ -57,7 +57,7 @@ public class SendAndListen extends RileyLinkCommand {
// If firmware version is not set (error reading version from device, shouldn't happen), // If firmware version is not set (error reading version from device, shouldn't happen),
// we will default to version 2 // 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; .isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher) : true;
ArrayList<Byte> bytes = new ArrayList<Byte>(); ArrayList<Byte> bytes = new ArrayList<Byte>();

View file

@ -17,7 +17,7 @@ public class SetPreamble extends RileyLinkCommand {
super(); super();
// this command was not supported before 2.0 // 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"); throw new NotImplementedException("Old firmware does not support SetPreamble command");
} }

View file

@ -33,7 +33,7 @@ public class RadioPacket {
public byte[] getEncoded() { public byte[] getEncoded() {
switch (RileyLinkUtil.getEncoding()) { switch (RileyLinkUtil.getInstance().getEncoding()) {
case Manchester: { // We have this encoding in RL firmware case Manchester: { // We have this encoding in RL firmware
return pkt; return pkt;
} }
@ -41,7 +41,7 @@ public class RadioPacket {
case FourByteSixByteLocal: { case FourByteSixByteLocal: {
byte[] withCRC = getWithCRC(); byte[] withCRC = getWithCRC();
byte[] encoded = RileyLinkUtil.getEncoding4b6b().encode4b6b(withCRC); byte[] encoded = RileyLinkUtil.getInstance().getEncoding4b6b().encode4b6b(withCRC);
return ByteUtil.concat(encoded, (byte)0); return ByteUtil.concat(encoded, (byte)0);
} }
@ -50,7 +50,7 @@ public class RadioPacket {
} }
default: default:
throw new NotImplementedException(("Encoding not supported: " + RileyLinkUtil.getEncoding().toString())); throw new NotImplementedException(("Encoding not supported: " + RileyLinkUtil.getInstance().getEncoding().toString()));
} }
} }

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data;
import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.NotImplementedException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
@ -75,8 +74,8 @@ public class RadioResponse {
} }
byte[] encodedPayload; byte[] encodedPayload;
if (RileyLinkFirmwareVersion.isSameVersion(RileyLinkUtil.getRileyLinkServiceData().versionCC110, if (RileyLinkFirmwareVersion.isSameVersion(RileyLinkUtil.getInstance().getRileyLinkServiceData().versionCC110,
RileyLinkFirmwareVersion.Version2)) { RileyLinkFirmwareVersion.Version2)) {
encodedPayload = ByteUtil.substring(rxData, 3, rxData.length - 3); encodedPayload = ByteUtil.substring(rxData, 3, rxData.length - 3);
rssi = rxData[1]; rssi = rxData[1];
responseNumber = rxData[2]; responseNumber = rxData[2];
@ -92,23 +91,23 @@ public class RadioResponse {
// well, for non-radio commands we shouldn't even reach this point // well, for non-radio commands we shouldn't even reach this point
// but getVersion is kind of exception // but getVersion is kind of exception
if (command != null && // if (command != null && //
command.getCommandType() != RileyLinkCommandType.SendAndListen) { command.getCommandType() != RileyLinkCommandType.SendAndListen) {
decodedOK = true; decodedOK = true;
decodedPayload = encodedPayload; decodedPayload = encodedPayload;
return; return;
} }
switch (RileyLinkUtil.getEncoding()) { switch (RileyLinkUtil.getInstance().getEncoding()) {
case Manchester: case Manchester:
case FourByteSixByteRileyLink: { case FourByteSixByteRileyLink: {
decodedOK = true; decodedOK = true;
decodedPayload = encodedPayload; decodedPayload = encodedPayload;
} }
break; break;
case FourByteSixByteLocal: { case FourByteSixByteLocal: {
byte[] decodeThis = RileyLinkUtil.getEncoding4b6b().decode4b6b(encodedPayload); byte[] decodeThis = RileyLinkUtil.getInstance().getEncoding4b6b().decode4b6b(encodedPayload);
if (decodeThis != null && decodeThis.length > 2) { if (decodeThis != null && decodeThis.length > 2) {
decodedOK = true; decodedOK = true;
@ -118,17 +117,17 @@ public class RadioResponse {
byte calculatedCRC = CRC.crc8(decodedPayload); byte calculatedCRC = CRC.crc8(decodedPayload);
if (receivedCRC != calculatedCRC) { if (receivedCRC != calculatedCRC) {
LOG.error(String.format("RadioResponse: CRC mismatch, calculated 0x%02x, received 0x%02x", LOG.error(String.format("RadioResponse: CRC mismatch, calculated 0x%02x, received 0x%02x",
calculatedCRC, receivedCRC)); calculatedCRC, receivedCRC));
} }
} else { } else {
throw new RileyLinkCommunicationException(RileyLinkBLEError.TooShortOrNullResponse); throw new RileyLinkCommunicationException(RileyLinkBLEError.TooShortOrNullResponse);
} }
} }
break; break;
default: default:
throw new NotImplementedException("this {" + RileyLinkUtil.getEncoding().toString() throw new NotImplementedException("this {" + RileyLinkUtil.getInstance().getEncoding().toString()
+ "} encoding is not supported"); + "} encoding is not supported");
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
decodedOK = false; decodedOK = false;

View file

@ -26,6 +26,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { public class RileyLinkStatusActivity extends NoSplashAppCompatActivity {
@Inject ResourceHelper resourceHelper; @Inject ResourceHelper resourceHelper;
@Inject RileyLinkUtil rileyLinkUtil;
TextView connectionStatus; TextView connectionStatus;
TextView configuredAddress; TextView configuredAddress;
@ -76,7 +77,7 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity {
this.connectedDevice = findViewById(R.id.rls_t1_connected_device); this.connectedDevice = findViewById(R.id.rls_t1_connected_device);
this.connectionError = findViewById(R.id.rls_t1_connection_error); this.connectionError = findViewById(R.id.rls_t1_connection_error);
rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData(); rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData();
// // 7-12 // // 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, // // 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 = new SectionsPagerAdapter(getSupportFragmentManager());
mSectionsPagerAdapter.addFragment(new RileyLinkStatusGeneral(), resourceHelper.gs(R.string.rileylink_settings_tab1)); mSectionsPagerAdapter.addFragment(new RileyLinkStatusGeneralFragment(), resourceHelper.gs(R.string.rileylink_settings_tab1));
mSectionsPagerAdapter.addFragment(new RileyLinkStatusHistory(), resourceHelper.gs(R.string.rileylink_settings_tab2)); mSectionsPagerAdapter.addFragment(new RileyLinkStatusHistoryFragment(), resourceHelper.gs(R.string.rileylink_settings_tab2));
//mSectionsPagerAdapter.addFragment(new RileyLinkStatusDevice(), "Medtronic"); //mSectionsPagerAdapter.addFragment(new RileyLinkStatusDevice(), "Medtronic");
mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setAdapter(mSectionsPagerAdapter);

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog; package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog;
import android.os.Bundle; import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -11,6 +10,9 @@ import org.joda.time.LocalDateTime;
import java.util.Locale; import java.util.Locale;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface;
@ -27,7 +29,10 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
* Created by andy on 5/19/18. * Created by andy on 5/19/18.
*/ */
public class RileyLinkStatusGeneral extends Fragment implements RefreshableInterface { public class RileyLinkStatusGeneralFragment extends DaggerFragment implements RefreshableInterface {
@Inject RileyLinkUtil rileyLinkUtil;
@Inject MedtronicUtil medtronicUtil;
TextView connectionStatus; TextView connectionStatus;
TextView configuredAddress; TextView configuredAddress;
@ -43,7 +48,6 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
RileyLinkServiceData rileyLinkServiceData; RileyLinkServiceData rileyLinkServiceData;
MedtronicPumpStatus medtronicPumpStatus;
boolean first = false; boolean first = false;
@ -58,7 +62,7 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
@Override @Override
public void onStart() { public void onStart() {
super.onStart(); super.onStart();
rileyLinkServiceData = RileyLinkUtil.getRileyLinkServiceData(); rileyLinkServiceData = rileyLinkUtil.getRileyLinkServiceData();
this.connectionStatus = getActivity().findViewById(R.id.rls_t1_connection_status); this.connectionStatus = getActivity().findViewById(R.id.rls_t1_connection_status);
this.configuredAddress = getActivity().findViewById(R.id.rls_t1_configured_address); this.configuredAddress = getActivity().findViewById(R.id.rls_t1_configured_address);
@ -93,12 +97,12 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
public void refreshData() { 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))); this.connectionStatus.setText(MainApp.gs(RileyLinkServiceState.NotStarted.getResourceId(targetDevice)));
else else
this.connectionStatus.setText(MainApp.gs(RileyLinkUtil.getServiceState().getResourceId(targetDevice))); this.connectionStatus.setText(MainApp.gs(rileyLinkUtil.getServiceState().getResourceId(targetDevice)));
if (rileyLinkServiceData != null) { if (rileyLinkServiceData != null) {
this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress); this.configuredAddress.setText(rileyLinkServiceData.rileylinkAddress);
@ -109,7 +113,7 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
RileyLinkFirmwareVersion firmwareVersion = rileyLinkServiceData.versionCC110; RileyLinkFirmwareVersion firmwareVersion = rileyLinkServiceData.versionCC110;
if (firmwareVersion==null) { if (firmwareVersion == null) {
this.firmwareVersion.setText("BLE113: -\nCC110: -"); this.firmwareVersion.setText("BLE113: -\nCC110: -");
} else { } else {
this.firmwareVersion.setText("BLE113: " + rileyLinkServiceData.versionBLE113 + // this.firmwareVersion.setText("BLE113: " + rileyLinkServiceData.versionBLE113 + //
@ -119,7 +123,7 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
} }
// TODO add handling for Omnipod pump status // TODO add handling for Omnipod pump status
this.medtronicPumpStatus = MedtronicUtil.getPumpStatus(); MedtronicPumpStatus medtronicPumpStatus = medtronicUtil.getPumpStatus();
if (medtronicPumpStatus != null) { if (medtronicPumpStatus != null) {
this.deviceType.setText(MainApp.gs(RileyLinkTargetDevice.MedtronicPump.getResourceId())); this.deviceType.setText(MainApp.gs(RileyLinkTargetDevice.MedtronicPump.getResourceId()));
@ -129,8 +133,8 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
// TODO extend when Omnipod used // TODO extend when Omnipod used
if (MedtronicUtil.getMedtronicPumpModel() != null) if (medtronicUtil.getMedtronicPumpModel() != null)
this.connectedDevice.setText("Medtronic " + MedtronicUtil.getMedtronicPumpModel().getPumpModel()); this.connectedDevice.setText("Medtronic " + medtronicUtil.getMedtronicPumpModel().getPumpModel());
else else
this.connectedDevice.setText("???"); this.connectedDevice.setText("???");

View file

@ -5,9 +5,11 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import android.os.Bundle; import android.os.Bundle;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -15,6 +17,9 @@ import android.widget.TextView;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; 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.RileyLinkUtil;
@ -27,7 +32,9 @@ import info.nightscout.androidaps.utils.DateUtil;
* Created by andy on 5/19/18. * 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; RecyclerView recyclerView;
RecyclerViewAdapter recyclerViewAdapter; RecyclerViewAdapter recyclerViewAdapter;
@ -40,7 +47,7 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rileylink_status_history, container, false); View rootView = inflater.inflate(R.layout.rileylink_status_history, container, false);
recyclerView = (RecyclerView)rootView.findViewById(R.id.rileylink_history_list); recyclerView = (RecyclerView) rootView.findViewById(R.id.rileylink_history_list);
recyclerView.setHasFixedSize(true); recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(getActivity().getApplicationContext()); llm = new LinearLayoutManager(getActivity().getApplicationContext());
@ -63,8 +70,8 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
@Override @Override
public void refreshData() { public void refreshData() {
if (RileyLinkUtil.getRileyLinkHistory()!=null) { if (rileyLinkUtil.getRileyLinkHistory() != null) {
recyclerViewAdapter.addItemsAndClean(RileyLinkUtil.getRileyLinkHistory()); recyclerViewAdapter.addItemsAndClean(rileyLinkUtil.getRileyLinkHistory());
} }
} }
@ -105,10 +112,10 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
PumpDeviceState pumpState = item.getPumpDeviceState(); PumpDeviceState pumpState = item.getPumpDeviceState();
if ((pumpState != null) && // if ((pumpState != null) && //
(pumpState == PumpDeviceState.Sleeping || // (pumpState == PumpDeviceState.Sleeping || //
pumpState == PumpDeviceState.Active || // pumpState == PumpDeviceState.Active || //
pumpState == PumpDeviceState.WakingUp // pumpState == PumpDeviceState.WakingUp //
)) ))
return false; return false;
return true; return true;
@ -120,7 +127,7 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
@Override @Override
public RecyclerViewAdapter.HistoryViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { public RecyclerViewAdapter.HistoryViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rileylink_status_history_item, // View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rileylink_status_history_item, //
viewGroup, false); viewGroup, false);
return new RecyclerViewAdapter.HistoryViewHolder(v); return new RecyclerViewAdapter.HistoryViewHolder(v);
} }
@ -158,9 +165,9 @@ public class RileyLinkStatusHistory extends Fragment implements RefreshableInter
HistoryViewHolder(View itemView) { HistoryViewHolder(View itemView) {
super(itemView); super(itemView);
timeView = (TextView)itemView.findViewById(R.id.rileylink_history_time); timeView = (TextView) itemView.findViewById(R.id.rileylink_history_time);
typeView = (TextView)itemView.findViewById(R.id.rileylink_history_source); typeView = (TextView) itemView.findViewById(R.id.rileylink_history_source);
valueView = (TextView)itemView.findViewById(R.id.rileylink_history_description); valueView = (TextView) itemView.findViewById(R.id.rileylink_history_description);
} }
} }
} }

View file

@ -15,6 +15,7 @@ import javax.inject.Inject
class RileyLinkBluetoothStateReceiver : DaggerBroadcastReceiver() { class RileyLinkBluetoothStateReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var rileyLinkUtil: RileyLinkUtil
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent) super.onReceive(context, intent)
@ -27,7 +28,7 @@ class RileyLinkBluetoothStateReceiver : DaggerBroadcastReceiver() {
BluetoothAdapter.STATE_ON -> { BluetoothAdapter.STATE_ON -> {
aapsLogger.debug("RileyLinkBluetoothStateReceiver: Bluetooth back on. Sending broadcast to RileyLink Framework") aapsLogger.debug("RileyLinkBluetoothStateReceiver: Bluetooth back on. Sending broadcast to RileyLink Framework")
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected) rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.Intents.BluetoothReconnected)
} }
} }
} }

View file

@ -5,20 +5,22 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service;
*/ */
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import dagger.android.DaggerBroadcastReceiver;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; 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.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.ServiceTask;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; 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.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 * 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 * where we get a lot of problems. Especially merging between AAPS and RileyLinkAAPS. I might put it back at
* later time * 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); private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM);
@ -88,6 +93,7 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent == null) { if (intent == null) {
LOG.error("onReceive: received null intent"); LOG.error("onReceive: received null intent");
@ -135,10 +141,9 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnected)) { if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnected)) {
if (BluetoothAdapter.getDefaultAdapter().isEnabled()) { if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
RileyLinkUtil rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable);
.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable);
} else { } else {
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled);
} }
return true; return true;
@ -166,14 +171,14 @@ public class RileyLinkBroadcastReceiver extends BroadcastReceiver {
LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name()); LOG.debug("RfSpy Radio version (CC110): " + rlVersion.name());
this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; this.serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion;
ServiceTask task = new InitializePumpManagerTask(RileyLinkUtil.getTargetDevice()); ServiceTask task = new InitializePumpManagerTask(rileyLinkUtil.getTargetDevice());
ServiceTaskExecutor.startTask(task); ServiceTaskExecutor.startTask(task);
if (isLoggingEnabled()) if (isLoggingEnabled())
LOG.info("Announcing RileyLink open For business"); LOG.info("Announcing RileyLink open For business");
return true; return true;
} else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) { } else if (action.equals(RileyLinkConst.Intents.RileyLinkNewAddressSet)) {
String RileylinkBLEAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); String RileylinkBLEAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, "");
if (RileylinkBLEAddress.equals("")) { if (RileylinkBLEAddress.equals("")) {
LOG.error("No Rileylink BLE Address saved in app"); LOG.error("No Rileylink BLE Address saved in app");
} else { } else {

View file

@ -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.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.sharedPreferences.SP; 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. * Created by andy on 5/6/18.
* Split from original file and renamed. * Split from original file and renamed.
@ -36,6 +34,8 @@ public abstract class RileyLinkService extends DaggerService {
@Inject protected AAPSLogger aapsLogger; @Inject protected AAPSLogger aapsLogger;
@Inject protected SP sp; @Inject protected SP sp;
@Inject protected Context context; @Inject protected Context context;
@Inject protected RileyLinkUtil rileyLinkUtil;
@Inject protected MedtronicUtil medtronicUtil;
public RileyLinkBLE rileyLinkBLE; // android-bluetooth management public RileyLinkBLE rileyLinkBLE; // android-bluetooth management
@ -49,9 +49,8 @@ public abstract class RileyLinkService extends DaggerService {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
RileyLinkUtil.setContext(this.context); rileyLinkUtil.setRileyLinkService(this);
RileyLinkUtil.setRileyLinkService(this); rileyLinkUtil.setEncoding(getEncoding());
RileyLinkUtil.setEncoding(getEncoding());
initRileyLinkServiceData(); initRileyLinkServiceData();
mBroadcastReceiver = new RileyLinkBroadcastReceiver(this, this.context); mBroadcastReceiver = new RileyLinkBroadcastReceiver(this, this.context);
@ -131,27 +130,26 @@ public abstract class RileyLinkService extends DaggerService {
// We've received a service startCommand, we grab the lock. // We've received a service startCommand, we grab the lock.
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
RileyLinkUtil.setContext(getApplicationContext());
return (START_STICKY); return (START_STICKY);
} }
public boolean bluetoothInit() { public boolean bluetoothInit() {
aapsLogger.debug(LTag.PUMPCOMM, "bluetoothInit: attempting to get an adapter"); aapsLogger.debug(LTag.PUMPCOMM, "bluetoothInit: attempting to get an adapter");
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) { if (bluetoothAdapter == null) {
aapsLogger.error("Unable to obtain a BluetoothAdapter."); aapsLogger.error("Unable to obtain a BluetoothAdapter.");
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter);
} else { } else {
if (!bluetoothAdapter.isEnabled()) { if (!bluetoothAdapter.isEnabled()) {
aapsLogger.error("Bluetooth is not enabled."); aapsLogger.error("Bluetooth is not enabled.");
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled);
} else { } else {
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady);
return true; return true;
} }
} }
@ -164,11 +162,11 @@ public abstract class RileyLinkService extends DaggerService {
public boolean reconfigureRileyLink(String deviceAddress) { public boolean reconfigureRileyLink(String deviceAddress) {
if (rileyLinkBLE == null) { if (rileyLinkBLE == null) {
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothInitializing);
return false; return false;
} }
RileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkInitializing); rileyLinkUtil.setServiceState(RileyLinkServiceState.RileyLinkInitializing);
if (rileyLinkBLE.isConnected()) { if (rileyLinkBLE.isConnected()) {
if (deviceAddress.equals(rileyLinkServiceData.rileylinkAddress)) { if (deviceAddress.equals(rileyLinkServiceData.rileylinkAddress)) {
@ -189,10 +187,10 @@ public abstract class RileyLinkService extends DaggerService {
} else { } else {
aapsLogger.debug(LTag.PUMPCOMM, "Using RL " + deviceAddress); aapsLogger.debug(LTag.PUMPCOMM, "Using RL " + deviceAddress);
if (RileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) { if (rileyLinkUtil.getServiceState() == RileyLinkServiceState.NotStarted) {
if (!bluetoothInit()) { if (!bluetoothInit()) {
aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. {}", 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; return false;
} }
} }
@ -211,8 +209,8 @@ public abstract class RileyLinkService extends DaggerService {
// FIXME: This needs to be run in a session so that is interruptable, has a separate thread, etc. // FIXME: This needs to be run in a session so that is interruptable, has a separate thread, etc.
public void doTuneUpDevice() { public void doTuneUpDevice() {
RileyLinkUtil.setServiceState(RileyLinkServiceState.TuneUpDevice); rileyLinkUtil.setServiceState(RileyLinkServiceState.TuneUpDevice);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); medtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping);
double lastGoodFrequency = 0.0d; double lastGoodFrequency = 0.0d;
@ -236,11 +234,10 @@ public abstract class RileyLinkService extends DaggerService {
if (newFrequency == 0.0d) { if (newFrequency == 0.0d) {
// error tuning pump, pump not present ?? // error tuning pump, pump not present ??
RileyLinkUtil rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed);
.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed);
} else { } else {
getRileyLinkCommunicationManager().clearNotConnectedCount(); rileyLinkUtil.getRileyLinkCommunicationManager().clearNotConnectedCount();
RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); rileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady);
} }
} }
@ -252,7 +249,7 @@ public abstract class RileyLinkService extends DaggerService {
rileyLinkServiceData.rileylinkAddress = null; rileyLinkServiceData.rileylinkAddress = null;
} }
RileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady); rileyLinkUtil.setServiceState(RileyLinkServiceState.BluetoothReady);
} }

View file

@ -23,8 +23,8 @@ public class DiscoverGattServicesTask extends ServiceTask {
public void run() { public void run() {
if (needToConnect) if (needToConnect)
RileyLinkUtil.getRileyLinkBLE().connectGatt(); RileyLinkUtil.getInstance().getRileyLinkBLE().connectGatt();
RileyLinkUtil.getRileyLinkBLE().discoverServices(); RileyLinkUtil.getInstance().getRileyLinkBLE().discoverServices();
} }
} }

View file

@ -1,9 +1,6 @@
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks; package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks;
import android.util.Log;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; 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.RileyLinkServiceState;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; 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; import info.nightscout.androidaps.utils.SP;
/** /**
@ -43,42 +39,42 @@ public class InitializePumpManagerTask extends ServiceTask {
double lastGoodFrequency = 0.0d; double lastGoodFrequency = 0.0d;
if (RileyLinkUtil.getRileyLinkServiceData().lastGoodFrequency==null) { if (RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency == null) {
lastGoodFrequency = SP.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0d); lastGoodFrequency = SP.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0d);
lastGoodFrequency = Math.round(lastGoodFrequency * 1000d) / 1000d; lastGoodFrequency = Math.round(lastGoodFrequency * 1000d) / 1000d;
RileyLinkUtil.getRileyLinkServiceData().lastGoodFrequency = lastGoodFrequency; RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency = lastGoodFrequency;
// if (RileyLinkUtil.getRileyLinkTargetFrequency() == null) { // if (RileyLinkUtil.getRileyLinkTargetFrequency() == null) {
// String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null); // String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null);
// } // }
} else { } else {
lastGoodFrequency = RileyLinkUtil.getRileyLinkServiceData().lastGoodFrequency; lastGoodFrequency = RileyLinkUtil.getInstance().getRileyLinkServiceData().lastGoodFrequency;
} }
if ((lastGoodFrequency > 0.0d) 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)) if (L.isEnabled(L.PUMPCOMM))
LOG.info("Setting radio frequency to {} MHz", lastGoodFrequency); 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) { if (foundThePump) {
RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorReady); RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorReady);
} else { } else {
RileyLinkUtil.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkUtil.getInstance().setServiceState(RileyLinkServiceState.PumpConnectorError,
RileyLinkError.NoContactWithDevice); RileyLinkError.NoContactWithDevice);
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump);
} }
} else { } else {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump);
} }
} }
} }

View file

@ -1,12 +1,13 @@
package info.nightscout.androidaps.plugins.pump.common.ui; package info.nightscout.androidaps.plugins.pump.common.ui;
import android.content.Context; import android.content.Context;
import androidx.preference.Preference;
import android.util.AttributeSet; import android.util.AttributeSet;
import androidx.preference.Preference;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
@ -19,7 +20,7 @@ public class RileyLinkSelectPreference extends Preference {
super(context); super(context);
setInitialSummaryValue(); setInitialSummaryValue();
MedtronicUtil.setRileyLinkSelectPreference(this); RileyLinkUtil.getInstance().setRileyLinkSelectPreference(this);
} }
@ -27,7 +28,7 @@ public class RileyLinkSelectPreference extends Preference {
super(context, attrs); super(context, attrs);
setInitialSummaryValue(); setInitialSummaryValue();
MedtronicUtil.setRileyLinkSelectPreference(this); RileyLinkUtil.getInstance().setRileyLinkSelectPreference(this);
} }

View file

@ -57,6 +57,8 @@ class MedtronicFragment : DaggerFragment() {
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin
@Inject lateinit var warnColors: WarnColors @Inject lateinit var warnColors: WarnColors
@Inject lateinit var rileyLinkUtil: RileyLinkUtil
@Inject lateinit var medtronicUtil: MedtronicUtil
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -85,7 +87,7 @@ class MedtronicFragment : DaggerFragment() {
medtronic_pump_status.text = "{fa-bed}" medtronic_pump_status.text = "{fa-bed}"
medtronic_history.setOnClickListener { medtronic_history.setOnClickListener {
if (MedtronicUtil.getPumpStatus().verifyConfiguration()) { if (medtronicUtil.getPumpStatus().verifyConfiguration()) {
startActivity(Intent(context, MedtronicHistoryActivity::class.java)) startActivity(Intent(context, MedtronicHistoryActivity::class.java))
} else { } else {
displayNotConfiguredDialog() displayNotConfiguredDialog()
@ -93,7 +95,7 @@ class MedtronicFragment : DaggerFragment() {
} }
medtronic_refresh.setOnClickListener { medtronic_refresh.setOnClickListener {
if (!MedtronicUtil.getPumpStatus().verifyConfiguration()) { if (!medtronicUtil.getPumpStatus().verifyConfiguration()) {
displayNotConfiguredDialog() displayNotConfiguredDialog()
} else { } else {
medtronic_refresh.isEnabled = false medtronic_refresh.isEnabled = false
@ -107,7 +109,7 @@ class MedtronicFragment : DaggerFragment() {
} }
medtronic_stats.setOnClickListener { medtronic_stats.setOnClickListener {
if (MedtronicUtil.getPumpStatus().verifyConfiguration()) { if (medtronicUtil.getPumpStatus().verifyConfiguration()) {
startActivity(Intent(context, RileyLinkStatusActivity::class.java)) startActivity(Intent(context, RileyLinkStatusActivity::class.java))
} else { } else {
displayNotConfiguredDialog() displayNotConfiguredDialog()
@ -147,7 +149,7 @@ class MedtronicFragment : DaggerFragment() {
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ .subscribe({
aapsLogger.debug(LTag.PUMP, "EventMedtronicPumpConfigurationChanged triggered") aapsLogger.debug(LTag.PUMP, "EventMedtronicPumpConfigurationChanged triggered")
MedtronicUtil.getPumpStatus().verifyConfiguration() medtronicUtil.getPumpStatus().verifyConfiguration()
updateGUI() updateGUI()
}, { fabricPrivacy.logException(it) }) }, { fabricPrivacy.logException(it) })
disposable += rxBus disposable += rxBus
@ -171,12 +173,12 @@ class MedtronicFragment : DaggerFragment() {
@Synchronized @Synchronized
private fun setDeviceStatus() { private fun setDeviceStatus() {
val pumpStatus: MedtronicPumpStatus = MedtronicUtil.getPumpStatus() val pumpStatus: MedtronicPumpStatus = medtronicUtil.getPumpStatus()
pumpStatus.rileyLinkServiceState = checkStatusSet(pumpStatus.rileyLinkServiceState, pumpStatus.rileyLinkServiceState = checkStatusSet(pumpStatus.rileyLinkServiceState,
RileyLinkUtil.getServiceState()) as RileyLinkServiceState? rileyLinkUtil.getServiceState()) as RileyLinkServiceState?
val resourceId = pumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump) val resourceId = pumpStatus.rileyLinkServiceState.getResourceId(RileyLinkTargetDevice.MedtronicPump)
val rileyLinkError = RileyLinkUtil.getError() val rileyLinkError = rileyLinkUtil.getError()
medtronic_rl_status.text = medtronic_rl_status.text =
when { when {
pumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) pumpStatus.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId)
@ -187,7 +189,7 @@ class MedtronicFragment : DaggerFragment() {
} }
medtronic_rl_status.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) 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 = medtronic_errors.text =
pumpStatus.rileyLinkError?.let { pumpStatus.rileyLinkError?.let {
@ -195,7 +197,7 @@ class MedtronicFragment : DaggerFragment() {
} ?: "-" } ?: "-"
pumpStatus.pumpDeviceState = checkStatusSet(pumpStatus.pumpDeviceState, pumpStatus.pumpDeviceState = checkStatusSet(pumpStatus.pumpDeviceState,
MedtronicUtil.getPumpDeviceState()) as PumpDeviceState? medtronicUtil.getPumpDeviceState()) as PumpDeviceState?
when (pumpStatus.pumpDeviceState) { when (pumpStatus.pumpDeviceState) {
null, null,
@ -208,17 +210,17 @@ class MedtronicFragment : DaggerFragment() {
PumpDeviceState.InvalidConfiguration -> medtronic_pump_status.text = " " + resourceHelper.gs(pumpStatus.pumpDeviceState.resourceId) PumpDeviceState.InvalidConfiguration -> medtronic_pump_status.text = " " + resourceHelper.gs(pumpStatus.pumpDeviceState.resourceId)
PumpDeviceState.Active -> { PumpDeviceState.Active -> {
val cmd = MedtronicUtil.getCurrentCommand() val cmd = medtronicUtil.getCurrentCommand()
if (cmd == null) if (cmd == null)
medtronic_pump_status.text = " " + resourceHelper.gs(pumpStatus.pumpDeviceState.resourceId) medtronic_pump_status.text = " " + resourceHelper.gs(pumpStatus.pumpDeviceState.resourceId)
else { else {
aapsLogger.debug(LTag.PUMP, "Command: " + cmd) aapsLogger.debug(LTag.PUMP, "Command: " + cmd)
val cmdResourceId = cmd.resourceId val cmdResourceId = cmd.resourceId
if (cmd == MedtronicCommandType.GetHistoryData) { if (cmd == MedtronicCommandType.GetHistoryData) {
medtronic_pump_status.text = MedtronicUtil.frameNumber?.let { medtronic_pump_status.text = medtronicUtil.frameNumber?.let {
resourceHelper.gs(cmdResourceId, MedtronicUtil.pageNumber, MedtronicUtil.frameNumber) resourceHelper.gs(cmdResourceId, medtronicUtil.pageNumber, medtronicUtil.frameNumber)
} }
?: resourceHelper.gs(R.string.medtronic_cmd_desc_get_history_request, MedtronicUtil.pageNumber) ?: resourceHelper.gs(R.string.medtronic_cmd_desc_get_history_request, medtronicUtil.pageNumber)
} else { } else {
medtronic_pump_status.text = " " + (cmdResourceId?.let { resourceHelper.gs(it) } medtronic_pump_status.text = " " + (cmdResourceId?.let { resourceHelper.gs(it) }
?: cmd.getCommandDescription()) ?: cmd.getCommandDescription())
@ -260,7 +262,7 @@ class MedtronicFragment : DaggerFragment() {
@Synchronized @Synchronized
fun updateGUI() { fun updateGUI() {
if (medtronic_rl_status == null) return if (medtronic_rl_status == null) return
val pumpStatus = MedtronicUtil.getPumpStatus() val pumpStatus = medtronicUtil.getPumpStatus()
setDeviceStatus() setDeviceStatus()
@ -321,7 +323,7 @@ class MedtronicFragment : DaggerFragment() {
?: "" ?: ""
// battery // battery
if (MedtronicUtil.getBatteryType() == BatteryType.None || pumpStatus.batteryVoltage == null) { if (medtronicUtil.getBatteryType() == BatteryType.None || pumpStatus.batteryVoltage == null) {
medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} " medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} "
} else { } else {
medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} " + pumpStatus.batteryRemaining + "%" + String.format(" (%.2f V)", pumpStatus.batteryVoltage) medtronic_pumpstate_battery.text = "{fa-battery-" + pumpStatus.batteryRemaining / 25 + "} " + pumpStatus.batteryRemaining + "%" + String.format(" (%.2f V)", pumpStatus.batteryVoltage)

View file

@ -34,7 +34,6 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventCustomActionsChanged;
import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider;
@ -53,6 +52,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.PumpDriverState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; 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.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.ResetRileyLinkConfigurationTask;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor;
@ -85,7 +85,6 @@ import info.nightscout.androidaps.utils.TimeChangeType;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.sendNotification;
/** /**
* Created by andy on 23.04.18. * Created by andy on 23.04.18.
@ -95,9 +94,13 @@ import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUt
@Singleton @Singleton
public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInterface { public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInterface {
private final SP sp;
private final RileyLinkUtil rileyLinkUtil;
private final MedtronicUtil medtronicUtil;
private final MedtronicPumpStatus medtronicPumpStatus;
protected static MedtronicPumpPlugin plugin = null; protected static MedtronicPumpPlugin plugin = null;
private RileyLinkMedtronicService medtronicService; private RileyLinkMedtronicService medtronicService;
private MedtronicPumpStatus pumpStatusLocal = null;
private MedtronicUIComm medtronicUIComm; private MedtronicUIComm medtronicUIComm;
// variables for handling statuses and history // variables for handling statuses and history
@ -124,7 +127,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
ActivePluginProvider activePlugin, ActivePluginProvider activePlugin,
SP sp, SP sp,
CommandQueueProvider commandQueue, CommandQueueProvider commandQueue,
FabricPrivacy fabricPrivacy FabricPrivacy fabricPrivacy,
RileyLinkUtil rileyLinkUtil,
MedtronicUtil medtronicUtil,
MedtronicPumpStatus medtronicPumpStatus
) { ) {
super(new PluginDescription() // super(new PluginDescription() //
@ -138,8 +144,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
); );
this.plugin = this; this.plugin = this;
this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil;
this.medtronicUtil = medtronicUtil;
this.sp = sp; this.sp = sp;
this.medtronicPumpStatus = medtronicPumpStatus;
displayConnectionMessages = false; displayConnectionMessages = false;
@ -160,9 +168,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
for (int i = 0; i < 20; i++) { for (int i = 0; i < 20; i++) {
SystemClock.sleep(5000); SystemClock.sleep(5000);
if (MedtronicUtil.getPumpStatus() != null) { if (medtronicUtil.getPumpStatus() != null) {
aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service"); aapsLogger.debug(LTag.PUMP, "Starting Medtronic-RileyLink service");
if (MedtronicUtil.getPumpStatus().setNotInPreInit()) { if (medtronicUtil.getPumpStatus().setNotInPreInit()) {
break; break;
} }
} }
@ -176,7 +184,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
medtronicUIComm = new MedtronicUIComm(aapsLogger, rxBus, getResourceHelper()); medtronicUIComm = new MedtronicUIComm(aapsLogger, rxBus, getResourceHelper(), rileyLinkUtil, medtronicUtil);
medtronicHistoryData = new MedtronicHistoryData(aapsLogger, sp, activePlugin); medtronicHistoryData = new MedtronicHistoryData(aapsLogger, sp, activePlugin);
} }
@ -201,21 +209,20 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
public void initPumpStatusData() { public void initPumpStatusData() {
this.pumpStatusLocal = new MedtronicPumpStatus(pumpDescription); medtronicUtil.setPumpStatus(medtronicPumpStatus);
MedtronicUtil.setPumpStatus(pumpStatusLocal);
pumpStatusLocal.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); medtronicPumpStatus.lastConnection = sp.getLong(RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L);
pumpStatusLocal.lastDataTime = new LocalDateTime(pumpStatusLocal.lastConnection); medtronicPumpStatus.lastDataTime = new LocalDateTime(medtronicPumpStatus.lastConnection);
pumpStatusLocal.previousConnection = pumpStatusLocal.lastConnection; medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection;
pumpStatusLocal.refreshConfiguration(); medtronicPumpStatus.refreshConfiguration();
aapsLogger.debug(LTag.PUMP, "initPumpStatusData: " + this.pumpStatusLocal); aapsLogger.debug(LTag.PUMP, "initPumpStatusData: " + this.medtronicPumpStatus);
this.pumpStatus = pumpStatusLocal; this.pumpStatus = medtronicPumpStatus;
// this is only thing that can change, by being configured // this is only thing that can change, by being configured
pumpDescription.maxTempAbsolute = (pumpStatusLocal.maxBasal != null) ? pumpStatusLocal.maxBasal : 35.0d; pumpDescription.maxTempAbsolute = (medtronicPumpStatus.maxBasal != null) ? medtronicPumpStatus.maxBasal : 35.0d;
// set first Medtronic Pump Start // set first Medtronic Pump Start
if (!sp.contains(MedtronicConst.Statistics.FirstPumpStart)) { if (!sp.contains(MedtronicConst.Statistics.FirstPumpStart)) {
@ -380,8 +387,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
public void getPumpStatus() { public void getPumpStatus() {
getMDTPumpStatus();
if (firstRun) { if (firstRun) {
initializePump(!isRefresh); initializePump(!isRefresh);
} else { } else {
@ -400,7 +405,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private boolean isPumpNotReachable() { private boolean isPumpNotReachable() {
RileyLinkServiceState rileyLinkServiceState = MedtronicUtil.getServiceState(); RileyLinkServiceState rileyLinkServiceState = rileyLinkUtil.getServiceState();
if (rileyLinkServiceState == null) { if (rileyLinkServiceState == null) {
aapsLogger.debug(LTag.PUMP, "RileyLink unreachable. RileyLinkServiceState is null."); aapsLogger.debug(LTag.PUMP, "RileyLink unreachable. RileyLinkServiceState is null.");
@ -431,12 +436,12 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (isPumpNotReachable()) { if (isPumpNotReachable()) {
aapsLogger.error("Pump unreachable."); aapsLogger.error("Pump unreachable.");
MedtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, getResourceHelper(), rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, getResourceHelper(), rxBus);
return; return;
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
if (hasTimeDateOrTimeZoneChanged) { if (hasTimeDateOrTimeZoneChanged) {
@ -492,7 +497,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
} }
if (resetTime) if (resetTime)
pumpStatusLocal.setLastCommunicationToNow(); medtronicPumpStatus.setLastCommunicationToNow();
} }
@ -526,28 +531,26 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
setRefreshButtonEnabled(false); setRefreshButtonEnabled(false);
getMDTPumpStatus();
if (isRefresh) { if (isRefresh) {
if (isPumpNotReachable()) { if (isPumpNotReachable()) {
aapsLogger.error(getLogPrefix() + "initializePump::Pump unreachable."); aapsLogger.error(getLogPrefix() + "initializePump::Pump unreachable.");
MedtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, getResourceHelper(), rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, getResourceHelper(), rxBus);
setRefreshButtonEnabled(true); setRefreshButtonEnabled(true);
return; return;
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
} }
// model (once) // model (once)
if (MedtronicUtil.getMedtronicPumpModel() == null) { if (medtronicUtil.getMedtronicPumpModel() == null) {
medtronicUIComm.executeCommand(MedtronicCommandType.PumpModel); medtronicUIComm.executeCommand(MedtronicCommandType.PumpModel);
} else { } else {
if (pumpStatusLocal.medtronicDeviceType != MedtronicUtil.getMedtronicPumpModel()) { if (medtronicPumpStatus.medtronicDeviceType != medtronicUtil.getMedtronicPumpModel()) {
aapsLogger.warn(LTag.PUMP, getLogPrefix() + "Configured pump is not the same as one detected."); aapsLogger.warn(LTag.PUMP, getLogPrefix() + "Configured pump is not the same as one detected.");
MedtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, getResourceHelper(), rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, getResourceHelper(), rxBus);
} }
} }
@ -567,7 +570,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
scheduleNextRefresh(MedtronicStatusRefreshType.BatteryStatus, 20); scheduleNextRefresh(MedtronicStatusRefreshType.BatteryStatus, 20);
// configuration (once and then if history shows config changes) // configuration (once and then if history shows config changes)
medtronicUIComm.executeCommand(MedtronicCommandType.getSettings(MedtronicUtil.getMedtronicPumpModel())); medtronicUIComm.executeCommand(MedtronicCommandType.getSettings(medtronicUtil.getMedtronicPumpModel()));
// read profile (once, later its controlled by isThisProfileSet method) // read profile (once, later its controlled by isThisProfileSet method)
getBasalProfiles(); getBasalProfiles();
@ -581,7 +584,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return; return;
} }
pumpStatusLocal.setLastCommunicationToNow(); medtronicPumpStatus.setLastCommunicationToNow();
setRefreshButtonEnabled(true); setRefreshButtonEnabled(true);
if (!isRefresh) { if (!isRefresh) {
@ -606,7 +609,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
public boolean isThisProfileSet(Profile profile) { public boolean isThisProfileSet(Profile profile) {
MedtronicPumpStatus mdtPumpStatus = getMDTPumpStatus(); MedtronicPumpStatus mdtPumpStatus = medtronicPumpStatus;
aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitalized=" + mdtPumpStatus.basalProfileStatus); aapsLogger.debug(LTag.PUMP, "isThisProfileSet: basalInitalized=" + mdtPumpStatus.basalProfileStatus);
if (!isInitialized) if (!isInitialized)
@ -623,15 +626,15 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
} }
return (getMDTPumpStatus().basalProfileStatus != BasalProfileStatus.ProfileOK) || isProfileSame(profile); return (medtronicPumpStatus.basalProfileStatus != BasalProfileStatus.ProfileOK) || isProfileSame(profile);
} }
private boolean isProfileSame(Profile profile) { private boolean isProfileSame(Profile profile) {
boolean invalid = false; boolean invalid = false;
Double[] basalsByHour = getMDTPumpStatus().basalsByHour; Double[] basalsByHour = medtronicPumpStatus.basalsByHour;
PumpType pumpType = getMDTPumpStatus().getPumpType(); PumpType pumpType = medtronicPumpStatus.getPumpType();
aapsLogger.debug(LTag.PUMP, "Current Basals (h): " aapsLogger.debug(LTag.PUMP, "Current Basals (h): "
+ (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour))); + (basalsByHour == null ? "null" : BasalProfile.getProfilesByHourToString(basalsByHour)));
@ -649,7 +652,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
int hour = basalValue.timeAsSeconds / (60 * 60); int hour = basalValue.timeAsSeconds / (60 * 60);
if (!MedtronicUtil.isSame(basalsByHour[hour], basalValueValue)) { if (!medtronicUtil.isSame(basalsByHour[hour], basalValueValue)) {
invalid = true; invalid = true;
} }
@ -671,10 +674,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
public long lastDataTime() { public long lastDataTime() {
getMDTPumpStatus(); medtronicPumpStatus;
if (pumpStatusLocal.lastConnection != 0) { if (medtronicPumpStatus.lastConnection != 0) {
return pumpStatusLocal.lastConnection; return medtronicPumpStatus.lastConnection;
} }
return System.currentTimeMillis(); return System.currentTimeMillis();
@ -683,33 +686,21 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
public double getBaseBasalRate() { public double getBaseBasalRate() {
return getMDTPumpStatus().getBasalProfileForHour(); return medtronicPumpStatus.getBasalProfileForHour();
} }
@Override @Override
public double getReservoirLevel() { public double getReservoirLevel() {
return getMDTPumpStatus().reservoirRemainingUnits; return medtronicPumpStatus.reservoirRemainingUnits;
} }
@Override @Override
public int getBatteryLevel() { public int getBatteryLevel() {
return getMDTPumpStatus().batteryRemaining; return medtronicPumpStatus.batteryRemaining;
} }
private MedtronicPumpStatus getMDTPumpStatus() {
if (pumpStatusLocal == null) {
// FIXME I don't know why this happens
aapsLogger.warn(LTag.PUMP, "!!!! Reset Pump Status Local");
pumpStatusLocal = MedtronicUtil.getPumpStatus();
}
return pumpStatusLocal;
}
protected void triggerUIChange() { protected void triggerUIChange() {
rxBus.send(new EventMedtronicPumpValuesChanged()); rxBus.send(new EventMedtronicPumpValuesChanged());
} }
@ -736,16 +727,16 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return; return;
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock); medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock);
ClockDTO clock = MedtronicUtil.getPumpTime(); ClockDTO clock = medtronicUtil.getPumpTime();
if (clock == null) { // retry if (clock == null) { // retry
medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock); medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock);
clock = MedtronicUtil.getPumpTime(); clock = medtronicUtil.getPumpTime();
} }
if (clock == null) if (clock == null)
@ -768,7 +759,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
} else { } else {
if ((clock.localDeviceTime.getYear() > 2015)) { if ((clock.localDeviceTime.getYear() > 2015)) {
aapsLogger.error("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff={}]. Doing nothing." + timeDiff); aapsLogger.error("MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff={}]. Doing nothing." + timeDiff);
sendNotification(MedtronicNotificationType.TimeChangeOver24h, getResourceHelper(), rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, getResourceHelper(), rxBus);
} }
} }
@ -787,7 +778,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
setRefreshButtonEnabled(false); setRefreshButtonEnabled(false);
MedtronicPumpStatus mdtPumpStatus = getMDTPumpStatus(); MedtronicPumpStatus mdtPumpStatus = medtronicPumpStatus;
if (detailedBolusInfo.insulin > mdtPumpStatus.reservoirRemainingUnits) { if (detailedBolusInfo.insulin > mdtPumpStatus.reservoirRemainingUnits) {
return new PumpEnactResult(getInjector()) // return new PumpEnactResult(getInjector()) //
@ -805,7 +796,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return setNotReachable(true, false); return setNotReachable(true, false);
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) {
// LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled."); // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled.");
@ -870,7 +861,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true); activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true);
// we subtract insulin, exact amount will be visible with next remainingInsulin update. // we subtract insulin, exact amount will be visible with next remainingInsulin update.
getMDTPumpStatus().reservoirRemainingUnits -= detailedBolusInfo.insulin; medtronicPumpStatus.reservoirRemainingUnits -= detailedBolusInfo.insulin;
incrementStatistics(detailedBolusInfo.isSMB ? MedtronicConst.Statistics.SMBBoluses incrementStatistics(detailedBolusInfo.isSMB ? MedtronicConst.Statistics.SMBBoluses
: MedtronicConst.Statistics.StandardBoluses); : MedtronicConst.Statistics.StandardBoluses);
@ -956,9 +947,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable)); .comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
getMDTPumpStatus();
aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute: rate: " + absoluteRate + ", duration=" + durationInMinutes); aapsLogger.info(LTag.PUMP, getLogPrefix() + "setTempBasalAbsolute: rate: " + absoluteRate + ", duration=" + durationInMinutes);
@ -976,10 +965,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (!enforceNew) { if (!enforceNew) {
if (MedtronicUtil.isSame(tbrCurrent.getInsulinRate(), absoluteRate)) { if (medtronicUtil.isSame(tbrCurrent.getInsulinRate(), absoluteRate)) {
boolean sameRate = true; boolean sameRate = true;
if (MedtronicUtil.isSame(0.0d, absoluteRate) && durationInMinutes > 0) { if (medtronicUtil.isSame(0.0d, absoluteRate) && durationInMinutes > 0) {
// if rate is 0.0 and duration>0 then the rate is not the same // if rate is 0.0 and duration>0 then the rate is not the same
sameRate = false; sameRate = false;
} }
@ -1025,9 +1014,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (response) { if (response) {
// FIXME put this into UIPostProcessor // FIXME put this into UIPostProcessor
pumpStatusLocal.tempBasalStart = new Date(); medtronicPumpStatus.tempBasalStart = new Date();
pumpStatusLocal.tempBasalAmount = absoluteRate; medtronicPumpStatus.tempBasalAmount = absoluteRate;
pumpStatusLocal.tempBasalLength = durationInMinutes; medtronicPumpStatus.tempBasalLength = durationInMinutes;
TemporaryBasal tempStart = new TemporaryBasal(getInjector()) // TemporaryBasal tempStart = new TemporaryBasal(getInjector()) //
.date(System.currentTimeMillis()) // .date(System.currentTimeMillis()) //
@ -1061,8 +1050,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew); return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew);
} else { } else {
double absoluteValue = profile.getBasal() * (percent / 100.0d); double absoluteValue = profile.getBasal() * (percent / 100.0d);
getMDTPumpStatus(); absoluteValue = medtronicPumpStatus.pumpType.determineCorrectBasalSize(absoluteValue);
absoluteValue = pumpStatusLocal.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."); 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); return setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew);
} }
@ -1097,9 +1085,9 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, -1); scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, -1);
} }
if (this.getMDTPumpStatus().basalProfileStatus != BasalProfileStatus.NotInitialized if (this.medtronicPumpStatus.basalProfileStatus != BasalProfileStatus.NotInitialized
&& medtronicHistoryData.hasBasalProfileChanged()) { && medtronicHistoryData.hasBasalProfileChanged()) {
medtronicHistoryData.processLastBasalProfileChange(getMDTPumpStatus()); medtronicHistoryData.processLastBasalProfileChange(medtronicPumpStatus);
} }
PumpDriverState previousState = this.pumpState; PumpDriverState previousState = this.pumpState;
@ -1162,7 +1150,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): targetDate: " + targetDate); aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): targetDate: " + targetDate);
} }
} else { } else {
aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - " + MedtronicUtil.gsonInstance.toJson(lastPumpHistoryEntry)); aapsLogger.debug(LTag.PUMP, getLogPrefix() + "readPumpHistoryLogic(): lastPumpHistoryEntry: not null - " + medtronicUtil.gsonInstance.toJson(lastPumpHistoryEntry));
medtronicHistoryData.setIsInInit(false); medtronicHistoryData.setIsInInit(false);
// medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntry.atechDateTime); // medtronicHistoryData.setLastHistoryRecordTime(lastPumpHistoryEntry.atechDateTime);
@ -1247,7 +1235,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
switch (refreshType) { switch (refreshType) {
case RemainingInsulin: { case RemainingInsulin: {
double remaining = pumpStatusLocal.reservoirRemainingUnits; double remaining = medtronicPumpStatus.reservoirRemainingUnits;
int min; int min;
if (remaining > 50) if (remaining > 50)
min = 4 * 60; min = 4 * 60;
@ -1343,7 +1331,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable)); .comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
setRefreshButtonEnabled(false); setRefreshButtonEnabled(false);
TempBasalPair tbrCurrent = readTBR(); TempBasalPair tbrCurrent = readTBR();
@ -1389,17 +1377,17 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@NonNull @Override @NonNull @Override
public ManufacturerType manufacturer() { public ManufacturerType manufacturer() {
return getMDTPumpStatus().pumpType.getManufacturer(); return medtronicPumpStatus.pumpType.getManufacturer();
} }
@NonNull @Override @NonNull @Override
public PumpType model() { public PumpType model() {
return getMDTPumpStatus().pumpType; return medtronicPumpStatus.pumpType;
} }
@NonNull @Override @NonNull @Override
public String serialNumber() { public String serialNumber() {
return getMDTPumpStatus().serialNumber; return medtronicPumpStatus.serialNumber;
} }
@NonNull @Override @NonNull @Override
@ -1426,7 +1414,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
.comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable)); .comment(getResourceHelper().gs(R.string.medtronic_pump_status_pump_unreachable));
} }
MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus); medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus);
BasalProfile basalProfile = convertProfileToMedtronicProfile(profile); BasalProfile basalProfile = convertProfileToMedtronicProfile(profile);
@ -1459,7 +1447,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
MedtronicPumpStatus pumpStatus = getMDTPumpStatus(); MedtronicPumpStatus pumpStatus = medtronicPumpStatus;
if (pumpStatus.maxBasal == null) if (pumpStatus.maxBasal == null)
return null; return null;
@ -1480,7 +1468,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@NonNull @NonNull
private BasalProfile convertProfileToMedtronicProfile(Profile profile) { private BasalProfile convertProfileToMedtronicProfile(Profile profile) {
MedtronicPumpStatus pumpStatus = getMDTPumpStatus(); MedtronicPumpStatus pumpStatus = medtronicPumpStatus;
PumpType pumpType = pumpStatus.pumpType; PumpType pumpType = pumpStatus.pumpType;
@ -1536,7 +1524,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
switch (mcat) { switch (mcat) {
case WakeUpAndTune: { case WakeUpAndTune: {
if (MedtronicUtil.getPumpStatus().verifyConfiguration()) { if (medtronicUtil.getPumpStatus().verifyConfiguration()) {
ServiceTaskExecutor.startTask(new WakeAndTuneTask()); ServiceTaskExecutor.startTask(new WakeAndTuneTask());
} else { } else {
Intent i = new Intent(context, ErrorHelperActivity.class); Intent i = new Intent(context, ErrorHelperActivity.class);

View file

@ -4,7 +4,6 @@ import android.os.SystemClock;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar; import java.util.Calendar;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
@ -76,7 +75,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
medtronicCommunicationManager = this; medtronicCommunicationManager = this;
this.medtronicConverter = new MedtronicConverter(); this.medtronicConverter = new MedtronicConverter();
this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder(); this.pumpHistoryDecoder = new MedtronicPumpHistoryDecoder();
MedtronicUtil.getPumpStatus().previousConnection = SP.getLong( MedtronicUtil.getInstance().getPumpStatus().previousConnection = SP.getLong(
RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L);
} }
@ -88,7 +87,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
@Override @Override
protected void configurePumpSpecificSettings() { protected void configurePumpSpecificSettings() {
pumpStatus = MedtronicUtil.getPumpStatus(); pumpStatus = MedtronicUtil.getInstance().getPumpStatus();
} }
@ -117,10 +116,10 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
*/ */
public boolean isDeviceReachable(boolean canPreventTuneUp) { public boolean isDeviceReachable(boolean canPreventTuneUp) {
PumpDeviceState state = MedtronicUtil.getPumpDeviceState(); PumpDeviceState state = MedtronicUtil.getInstance().getPumpDeviceState();
if (state != PumpDeviceState.PumpUnreachable) if (state != PumpDeviceState.PumpUnreachable)
MedtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp);
for (int retry = 0; retry < 5; retry++) { for (int retry = 0; retry < 5; retry++) {
@ -137,11 +136,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
if (state != PumpDeviceState.PumpUnreachable) if (state != PumpDeviceState.PumpUnreachable)
MedtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.PumpUnreachable);
if (!canPreventTuneUp) { if (!canPreventTuneUp) {
long diff = System.currentTimeMillis() - MedtronicUtil.getPumpStatus().lastConnection; long diff = System.currentTimeMillis() - MedtronicUtil.getInstance().getPumpStatus().lastConnection;
if (diff > RILEYLINK_TIMEOUT) { if (diff > RILEYLINK_TIMEOUT) {
ServiceTaskExecutor.startTask(new WakeAndTuneTask()); ServiceTaskExecutor.startTask(new WakeAndTuneTask());
@ -154,7 +153,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
private boolean connectToDevice() { private boolean connectToDevice() {
PumpDeviceState state = MedtronicUtil.getPumpDeviceState(); PumpDeviceState state = MedtronicUtil.getInstance().getPumpDeviceState();
byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple byte[] pumpMsgContent = createPumpMessageContent(RLMessageType.ReadSimpleData); // simple
RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200, RFSpyResponse rfSpyResponse = rfspy.transmitThenReceive(new RadioPacket(pumpMsgContent), (byte) 0, (byte) 200,
@ -187,8 +186,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
MedtronicDeviceType pumpModel = (MedtronicDeviceType) dataResponse; MedtronicDeviceType pumpModel = (MedtronicDeviceType) dataResponse;
boolean valid = (pumpModel != MedtronicDeviceType.Unknown_Device); boolean valid = (pumpModel != MedtronicDeviceType.Unknown_Device);
if (MedtronicUtil.getMedtronicPumpModel() == null && valid) { if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null && valid) {
MedtronicUtil.setMedtronicPumpModel(pumpModel); MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel);
} }
if (isLogEnabled()) if (isLogEnabled())
@ -197,9 +196,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (valid) { if (valid) {
if (state == PumpDeviceState.PumpUnreachable) if (state == PumpDeviceState.PumpUnreachable)
MedtronicUtil.setPumpDeviceState(PumpDeviceState.WakingUp); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.WakingUp);
else else
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
rememberLastGoodDeviceCommunicationTime(); rememberLastGoodDeviceCommunicationTime();
@ -207,7 +206,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} else { } else {
if (state != PumpDeviceState.PumpUnreachable) if (state != PumpDeviceState.PumpUnreachable)
MedtronicUtil.setPumpDeviceState(PumpDeviceState.PumpUnreachable); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.PumpUnreachable);
} }
} }
@ -287,7 +286,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
for (List<Byte> frame : frames) { for (List<Byte> frame : frames) {
byte[] frameData = MedtronicUtil.createByteArray(frame); byte[] frameData = MedtronicUtil.getInstance().createByteArray(frame);
// LOG.debug("Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData)); // LOG.debug("Frame {} data:\n{}", frameNr, ByteUtil.getCompactString(frameData));
@ -326,9 +325,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
wakeUp(receiverDeviceAwakeForMinutes, false); wakeUp(receiverDeviceAwakeForMinutes, false);
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("Current command: " + MedtronicUtil.getCurrentCommand()); LOG.debug("Current command: " + MedtronicUtil.getInstance().getCurrentCommand());
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Active); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active);
boolean doneWithError = false; boolean doneWithError = false;
for (int pageNumber = 0; pageNumber < 5; pageNumber++) { for (int pageNumber = 0; pageNumber < 5; pageNumber++) {
@ -346,7 +345,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
PumpMessage firstResponse = null; PumpMessage firstResponse = null;
boolean failed = false; boolean failed = false;
MedtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null); MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, null);
for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries < MAX_COMMAND_TRIES; retries++) {
@ -362,7 +361,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
if (failed) { if (failed) {
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
} }
@ -391,7 +390,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
rawHistoryPage.appendData(currentResponse.getFrameData()); rawHistoryPage.appendData(currentResponse.getFrameData());
// RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) * // RileyLinkMedtronicService.getInstance().announceProgress(((100 / 16) *
// currentResponse.getFrameNumber() + 1)); // currentResponse.getFrameNumber() + 1));
MedtronicUtil.setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber, MedtronicUtil.getInstance().setCurrentCommand(MedtronicCommandType.GetHistoryData, pageNumber,
currentResponse.getFrameNumber()); currentResponse.getFrameNumber());
if (isLogEnabled()) if (isLogEnabled())
@ -463,7 +462,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
if (doneWithError) { if (doneWithError) {
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
} }
@ -481,13 +480,13 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
LOG.debug("getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished()); LOG.debug("getPumpHistory: Search status: Search finished: {}", pumpTotalResult.isSearchFinished());
if (pumpTotalResult.isSearchFinished()) { if (pumpTotalResult.isSearchFinished()) {
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
} }
} }
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return pumpTotalResult; return pumpTotalResult;
@ -503,11 +502,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public byte[] createPumpMessageContent(RLMessageType type) { public byte[] createPumpMessageContent(RLMessageType type) {
switch (type) { switch (type) {
case PowerOn: case PowerOn:
return MedtronicUtil.buildCommandPayload(MedtronicCommandType.RFPowerOn, // return MedtronicUtil.getInstance().buildCommandPayload(MedtronicCommandType.RFPowerOn, //
new byte[]{2, 1, (byte) receiverDeviceAwakeForMinutes}); // maybe this is better FIXME new byte[]{2, 1, (byte) receiverDeviceAwakeForMinutes}); // maybe this is better FIXME
case ReadSimpleData: case ReadSimpleData:
return MedtronicUtil.buildCommandPayload(MedtronicCommandType.PumpModel, null); return MedtronicUtil.getInstance().buildCommandPayload(MedtronicCommandType.PumpModel, null);
} }
return new byte[0]; return new byte[0];
} }
@ -551,7 +550,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (doWakeUpBeforeCommand) if (doWakeUpBeforeCommand)
wakeUp(receiverDeviceAwakeForMinutes, false); wakeUp(receiverDeviceAwakeForMinutes, false);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Active); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active);
// create message // create message
PumpMessage msg; PumpMessage msg;
@ -564,7 +563,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
// send and wait for response // send and wait for response
PumpMessage response = sendAndListen(msg, timeoutMs); PumpMessage response = sendAndListen(msg, timeoutMs);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return response; return response;
} }
@ -693,9 +692,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("getDataFromPump: {}", commandType); LOG.debug("getDataFromPump: {}", commandType);
MedtronicUtil.setCurrentCommand(commandType); MedtronicUtil.getInstance().setCurrentCommand(commandType);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Active); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Active);
for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) {
@ -753,8 +752,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("Converted response for {} is {}.", commandType.name(), basalProfile); LOG.debug("Converted response for {} is {}.", commandType.name(), basalProfile);
MedtronicUtil.setCurrentCommand(null); MedtronicUtil.getInstance().setCurrentCommand(null);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return basalProfile; return basalProfile;
} }
@ -765,8 +764,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
} }
LOG.warn("Error reading profile in max retries."); LOG.warn("Error reading profile in max retries.");
MedtronicUtil.setCurrentCommand(null); MedtronicUtil.getInstance().setCurrentCommand(null);
MedtronicUtil.setPumpDeviceState(PumpDeviceState.Sleeping); MedtronicUtil.getInstance().setPumpDeviceState(PumpDeviceState.Sleeping);
return null; return null;
@ -825,7 +824,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public Map<String, PumpSettingDTO> getPumpSettings() { public Map<String, PumpSettingDTO> getPumpSettings() {
Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.getSettings(MedtronicUtil Object responseObject = sendAndGetResponseWithCheck(MedtronicCommandType.getSettings(MedtronicUtil.getInstance()
.getMedtronicPumpModel())); .getMedtronicPumpModel()));
return responseObject == null ? null : (Map<String, PumpSettingDTO>) responseObject; return responseObject == null ? null : (Map<String, PumpSettingDTO>) responseObject;
@ -837,7 +836,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (isLogEnabled()) if (isLogEnabled())
LOG.info("setBolus: " + units); LOG.info("setBolus: " + units);
return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getBolusStrokes(units)); return setCommand(MedtronicCommandType.SetBolus, MedtronicUtil.getInstance().getBolusStrokes(units));
} }
@ -866,7 +865,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
data[i + 1] = (byte) gc.get(Calendar.MINUTE); data[i + 1] = (byte) gc.get(Calendar.MINUTE);
data[i + 2] = (byte) gc.get(Calendar.SECOND); data[i + 2] = (byte) gc.get(Calendar.SECOND);
byte[] yearByte = MedtronicUtil.getByteArrayFromUnsignedShort(gc.get(Calendar.YEAR), true); byte[] yearByte = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(gc.get(Calendar.YEAR), true);
data[i + 3] = yearByte[0]; data[i + 3] = yearByte[0];
data[i + 4] = yearByte[1]; data[i + 4] = yearByte[1];
@ -931,7 +930,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
public Boolean setBasalProfile(BasalProfile basalProfile) { public Boolean setBasalProfile(BasalProfile basalProfile) {
List<List<Byte>> basalProfileFrames = MedtronicUtil.getBasalProfileFrames(basalProfile.getRawData()); List<List<Byte>> basalProfileFrames = MedtronicUtil.getInstance().getBasalProfileFrames(basalProfile.getRawData());
for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) { for (int retries = 0; retries <= MAX_COMMAND_TRIES; retries++) {

View file

@ -44,7 +44,7 @@ public class MedtronicConverter {
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("Raw response before convert: " + ByteUtil.shortHexString(rawContent)); LOG.debug("Raw response before convert: " + ByteUtil.shortHexString(rawContent));
this.pumpModel = MedtronicUtil.getMedtronicPumpModel(); this.pumpModel = MedtronicUtil.getInstance().getMedtronicPumpModel();
switch (commandType) { switch (commandType) {
@ -117,8 +117,8 @@ public class MedtronicConverter {
LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name()); LOG.debug("PumpModel: [raw={}, resolved={}]", rawModel, pumpModel.name());
if (pumpModel != MedtronicDeviceType.Unknown_Device) { if (pumpModel != MedtronicDeviceType.Unknown_Device) {
if (!MedtronicUtil.isModelSet()) { if (!MedtronicUtil.getInstance().isModelSet()) {
MedtronicUtil.setMedtronicPumpModel(pumpModel); MedtronicUtil.getInstance().setMedtronicPumpModel(pumpModel);
} }
} }
@ -157,7 +157,7 @@ public class MedtronicConverter {
protected Float decodeRemainingInsulin(byte[] rawData) { protected Float decodeRemainingInsulin(byte[] rawData) {
int startIdx = 0; int startIdx = 0;
this.pumpModel = MedtronicUtil.getMedtronicPumpModel(); this.pumpModel = MedtronicUtil.getInstance().getMedtronicPumpModel();
int strokes = pumpModel == null ? 10 : pumpModel.getBolusStrokes(); int strokes = pumpModel == null ? 10 : pumpModel.getBolusStrokes();

View file

@ -62,7 +62,7 @@ public abstract class MedtronicHistoryDecoder<T extends MedtronicHistoryEntry> i
// return byteList; // return byteList;
// } // }
if (MedtronicUtil.getMedtronicPumpModel() == null) { if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null) {
LOG.error("Device Type is not defined."); LOG.error("Device Type is not defined.");
return byteList; return byteList;
} }

View file

@ -58,7 +58,7 @@ public class RawHistoryPage {
LOG.error("Stored CRC ({}) is different than calculated ({}), but ignored for now.", crcStored, LOG.error("Stored CRC ({}) is different than calculated ({}), but ignored for now.", crcStored,
crcCalculated); crcCalculated);
} else { } else {
if (MedtronicUtil.isLowLevelDebug()) if (MedtronicUtil.getInstance().isLowLevelDebug())
LOG.debug("CRC ok."); LOG.debug("CRC ok.");
} }

View file

@ -51,7 +51,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
int counter = 0; int counter = 0;
int record = 0; int record = 0;
boolean incompletePacket = false; boolean incompletePacket = false;
deviceType = MedtronicUtil.getMedtronicPumpModel(); deviceType = MedtronicUtil.getInstance().getMedtronicPumpModel();
List<PumpHistoryEntry> outList = new ArrayList<PumpHistoryEntry>(); List<PumpHistoryEntry> outList = new ArrayList<PumpHistoryEntry>();
String skipped = null; String skipped = null;
@ -408,7 +408,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
Float rate = null; Float rate = null;
int index = entry.getHead()[0]; int index = entry.getHead()[0];
if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getMedtronicPumpModel(), if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getInstance().getMedtronicPumpModel(),
MedtronicDeviceType.Medtronic_523andHigher)) { MedtronicDeviceType.Medtronic_523andHigher)) {
rate = body[1] * 0.025f; rate = body[1] * 0.025f;
} }
@ -435,7 +435,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
float bolusStrokes = 10.0f; float bolusStrokes = 10.0f;
if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getMedtronicPumpModel(), if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getInstance().getMedtronicPumpModel(),
MedtronicDeviceType.Medtronic_523andHigher)) { MedtronicDeviceType.Medtronic_523andHigher)) {
// https://github.com/ps2/minimed_rf/blob/master/lib/minimed_rf/log_entries/bolus_wizard.rb#L102 // https://github.com/ps2/minimed_rf/blob/master/lib/minimed_rf/log_entries/bolus_wizard.rb#L102
bolusStrokes = 40.0f; bolusStrokes = 40.0f;
@ -570,7 +570,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
byte[] data = entry.getHead(); byte[] data = entry.getHead();
if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getMedtronicPumpModel(), if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getInstance().getMedtronicPumpModel(),
MedtronicDeviceType.Medtronic_523andHigher)) { MedtronicDeviceType.Medtronic_523andHigher)) {
bolus.setRequestedAmount(ByteUtil.toInt(data[0], data[1]) / 40.0d); bolus.setRequestedAmount(ByteUtil.toInt(data[0], data[1]) / 40.0d);
bolus.setDeliveredAmount(ByteUtil.toInt(data[2], data[3]) / 40.0d); bolus.setDeliveredAmount(ByteUtil.toInt(data[2], data[3]) / 40.0d);

View file

@ -380,7 +380,7 @@ public enum PumpHistoryEntryType // implements CodeEnum
int size = defaultValue; int size = defaultValue;
for (SpecialRule rule : rules) { for (SpecialRule rule : rules) {
if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getMedtronicPumpModel(), rule.deviceType)) { if (MedtronicDeviceType.isSameDevice(MedtronicUtil.getInstance().getMedtronicPumpModel(), rule.deviceType)) {
size = rule.size; size = rule.size;
break; break;
} }

View file

@ -24,7 +24,7 @@ public class CarelinkLongMessageBody extends MessageBody {
public CarelinkLongMessageBody(List<Byte> payload) { public CarelinkLongMessageBody(List<Byte> payload) {
init(MedtronicUtil.createByteArray(payload)); init(MedtronicUtil.getInstance().createByteArray(payload));
} }

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui;
import org.jetbrains.annotations.NotNull;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -15,7 +17,9 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
*/ */
public class MedtronicUIComm { public class MedtronicUIComm {
private final AAPSLogger aapsLogger; @NotNull private final AAPSLogger aapsLogger;
@NotNull private final RileyLinkUtil rileyLinkUtil;
@NotNull private final MedtronicUtil medtronicUtil;
MedtronicCommunicationManager mcmInstance = null; MedtronicCommunicationManager mcmInstance = null;
MedtronicUIPostprocessor uiPostprocessor; MedtronicUIPostprocessor uiPostprocessor;
@ -23,11 +27,15 @@ public class MedtronicUIComm {
public MedtronicUIComm( public MedtronicUIComm(
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
ResourceHelper resourceHelper ResourceHelper resourceHelper,
RileyLinkUtil rileyLinkUtil,
MedtronicUtil medtronicUtil
) { ) {
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rileyLinkUtil = rileyLinkUtil;
this.medtronicUtil = medtronicUtil;
uiPostprocessor = new MedtronicUIPostprocessor(aapsLogger, rxBus, resourceHelper); uiPostprocessor = new MedtronicUIPostprocessor(aapsLogger, rxBus, resourceHelper, medtronicUtil);
} }
@ -46,7 +54,7 @@ public class MedtronicUIComm {
MedtronicUITask task = new MedtronicUITask(commandType, parameters); MedtronicUITask task = new MedtronicUITask(commandType, parameters);
MedtronicUtil.setCurrentCommand(commandType); medtronicUtil.setCurrentCommand(commandType);
// new Thread(() -> { // new Thread(() -> {
// LOG.warn("@@@ Start Thread"); // LOG.warn("@@@ Start Thread");
@ -108,6 +116,6 @@ public class MedtronicUIComm {
public void startTunning() { public void startTunning() {
RileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump); rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump);
} }
} }

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui; package info.nightscout.androidaps.plugins.pump.medtronic.comm.ui;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.joda.time.Duration; import org.joda.time.Duration;
@ -20,7 +21,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpSta
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.sendNotification;
/** /**
* Created by andy on 6/15/18. * Created by andy on 6/15/18.
@ -28,20 +28,16 @@ import static info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUt
class MedtronicUIPostprocessor { class MedtronicUIPostprocessor {
private final AAPSLogger aapsLogger; @NotNull private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; @NotNull private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper; @NotNull private final ResourceHelper resourceHelper;
@NotNull private final MedtronicUtil medtronicUtil;
public MedtronicUIPostprocessor(AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, MedtronicUtil medtronicUtil) {
private MedtronicPumpStatus pumpStatus;
public MedtronicUIPostprocessor(AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper) {
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus; this.rxBus = rxBus;
this.resourceHelper = resourceHelper; this.resourceHelper = resourceHelper;
pumpStatus = MedtronicUtil.getPumpStatus(); this.medtronicUtil = medtronicUtil;
} }
@ -57,7 +53,7 @@ class MedtronicUIPostprocessor {
if (response) { if (response) {
BasalProfile basalProfile = (BasalProfile) uiTask.getParameter(0); BasalProfile basalProfile = (BasalProfile) uiTask.getParameter(0);
pumpStatus.basalsByHour = basalProfile.getProfilesByHour(); medtronicUtil.getPumpStatus().basalsByHour = basalProfile.getProfilesByHour();
} }
} }
break; break;
@ -69,8 +65,8 @@ class MedtronicUIPostprocessor {
Double[] profilesByHour = basalProfile.getProfilesByHour(); Double[] profilesByHour = basalProfile.getProfilesByHour();
if (profilesByHour != null) { if (profilesByHour != null) {
pumpStatus.basalsByHour = profilesByHour; medtronicUtil.getPumpStatus().basalsByHour = profilesByHour;
pumpStatus.basalProfileStatus = BasalProfileStatus.ProfileOK; medtronicUtil.getPumpStatus().basalProfileStatus = BasalProfileStatus.ProfileOK;
} else { } else {
uiTask.responseType = MedtronicUIResponseType.Error; uiTask.responseType = MedtronicUIResponseType.Error;
uiTask.errorDescription = "No profile found."; uiTask.errorDescription = "No profile found.";
@ -85,20 +81,20 @@ class MedtronicUIPostprocessor {
break; break;
case SetBolus: { case SetBolus: {
pumpStatus.lastBolusAmount = uiTask.getDoubleFromParameters(0); medtronicUtil.getPumpStatus().lastBolusAmount = uiTask.getDoubleFromParameters(0);
pumpStatus.lastBolusTime = new Date(); medtronicUtil.getPumpStatus().lastBolusTime = new Date();
} }
break; break;
case GetRemainingInsulin: { case GetRemainingInsulin: {
pumpStatus.reservoirRemainingUnits = (Float) uiTask.returnData; medtronicUtil.getPumpStatus().reservoirRemainingUnits = (Float) uiTask.returnData;
} }
break; break;
case CancelTBR: { case CancelTBR: {
pumpStatus.tempBasalStart = null; medtronicUtil.getPumpStatus().tempBasalStart = null;
pumpStatus.tempBasalAmount = null; medtronicUtil.getPumpStatus().tempBasalAmount = null;
pumpStatus.tempBasalLength = null; medtronicUtil.getPumpStatus().tempBasalLength = null;
} }
break; break;
@ -113,7 +109,7 @@ class MedtronicUIPostprocessor {
aapsLogger.debug(LTag.PUMP, "New time was {} set.", response ? "" : "NOT"); aapsLogger.debug(LTag.PUMP, "New time was {} set.", response ? "" : "NOT");
if (response) { if (response) {
MedtronicUtil.getPumpTime().timeDifference = 0; medtronicUtil.getPumpTime().timeDifference = 0;
} }
} }
break; break;
@ -122,10 +118,10 @@ class MedtronicUIPostprocessor {
case GetBatteryStatus: { case GetBatteryStatus: {
BatteryStatusDTO batteryStatusDTO = (BatteryStatusDTO) uiTask.returnData; BatteryStatusDTO batteryStatusDTO = (BatteryStatusDTO) uiTask.returnData;
pumpStatus.batteryRemaining = batteryStatusDTO.getCalculatedPercent(pumpStatus.batteryType); medtronicUtil.getPumpStatus().batteryRemaining = batteryStatusDTO.getCalculatedPercent(medtronicUtil.getPumpStatus().batteryType);
if (batteryStatusDTO.voltage != null) { if (batteryStatusDTO.voltage != null) {
pumpStatus.batteryVoltage = batteryStatusDTO.voltage; medtronicUtil.getPumpStatus().batteryVoltage = batteryStatusDTO.voltage;
} }
aapsLogger.debug(LTag.PUMP, "BatteryStatus: {}", batteryStatusDTO.toString()); aapsLogger.debug(LTag.PUMP, "BatteryStatus: {}", batteryStatusDTO.toString());
@ -134,9 +130,9 @@ class MedtronicUIPostprocessor {
break; break;
case PumpModel: { case PumpModel: {
if (pumpStatus.medtronicDeviceType != MedtronicUtil.getMedtronicPumpModel()) { if (medtronicUtil.getPumpStatus().medtronicDeviceType != medtronicUtil.getMedtronicPumpModel()) {
aapsLogger.warn(LTag.PUMP, "Configured pump is different then pump detected !"); aapsLogger.warn(LTag.PUMP, "Configured pump is different then pump detected !");
sendNotification(MedtronicNotificationType.PumpTypeNotSame, resourceHelper, rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, resourceHelper, rxBus);
} }
} }
break; break;
@ -166,7 +162,7 @@ class MedtronicUIPostprocessor {
clockDTO.timeDifference = (int) dur.getStandardSeconds(); clockDTO.timeDifference = (int) dur.getStandardSeconds();
MedtronicUtil.setPumpTime(clockDTO); medtronicUtil.setPumpTime(clockDTO);
aapsLogger.debug(LTag.PUMP, "Pump Time: " + clockDTO.localDeviceTime + ", DeviceTime=" + clockDTO.pumpTime + // aapsLogger.debug(LTag.PUMP, "Pump Time: " + clockDTO.localDeviceTime + ", DeviceTime=" + clockDTO.pumpTime + //
", diff: " + dur.getStandardSeconds() + " s"); ", diff: " + dur.getStandardSeconds() + " s");
@ -190,29 +186,27 @@ class MedtronicUIPostprocessor {
Map<String, PumpSettingDTO> settings = (Map<String, PumpSettingDTO>) uiTask.returnData; Map<String, PumpSettingDTO> settings = (Map<String, PumpSettingDTO>) uiTask.returnData;
MedtronicUtil.setSettings(settings); medtronicUtil.setSettings(settings);
PumpSettingDTO checkValue = null; PumpSettingDTO checkValue = null;
if (pumpStatus == null) { if (medtronicUtil.getPumpStatus() == null) {
aapsLogger.debug(LTag.PUMP, "Pump Status: was null"); aapsLogger.debug(LTag.PUMP, "Pump Status: was null");
pumpStatus = MedtronicUtil.getPumpStatus(); }
aapsLogger.debug(LTag.PUMP, "Pump Status: " + this.pumpStatus);
}
this.pumpStatus.verifyConfiguration(); medtronicUtil.getPumpStatus().verifyConfiguration();
// check profile // check profile
if (!"Yes".equals(settings.get("PCFG_BASAL_PROFILES_ENABLED").value)) { if (!"Yes".equals(settings.get("PCFG_BASAL_PROFILES_ENABLED").value)) {
aapsLogger.error(LTag.PUMP, "Basal profiles are not enabled on pump."); aapsLogger.error(LTag.PUMP, "Basal profiles are not enabled on pump.");
sendNotification(MedtronicNotificationType.PumpBasalProfilesNotEnabled, resourceHelper, rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpBasalProfilesNotEnabled, resourceHelper, rxBus);
} else { } else {
checkValue = settings.get("PCFG_ACTIVE_BASAL_PROFILE"); checkValue = settings.get("PCFG_ACTIVE_BASAL_PROFILE");
if (!"STD".equals(checkValue.value)) { if (!"STD".equals(checkValue.value)) {
aapsLogger.error("Basal profile set on pump is incorrect (must be STD)."); aapsLogger.error("Basal profile set on pump is incorrect (must be STD).");
sendNotification(MedtronicNotificationType.PumpIncorrectBasalProfileSelected, resourceHelper, rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpIncorrectBasalProfileSelected, resourceHelper, rxBus);
} }
} }
@ -222,23 +216,23 @@ class MedtronicUIPostprocessor {
if (!"Units".equals(checkValue.value)) { if (!"Units".equals(checkValue.value)) {
aapsLogger.error("Wrong TBR type set on pump (must be Absolute)."); aapsLogger.error("Wrong TBR type set on pump (must be Absolute).");
sendNotification(MedtronicNotificationType.PumpWrongTBRTypeSet, resourceHelper, rxBus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongTBRTypeSet, resourceHelper, rxBus);
} }
// MAXes // MAXes
checkValue = settings.get("PCFG_MAX_BOLUS"); checkValue = settings.get("PCFG_MAX_BOLUS");
if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), pumpStatus.maxBolus)) { if (!medtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicUtil.getPumpStatus().maxBolus)) {
aapsLogger.error("Wrong Max Bolus set on Pump (current={}, required={}).", checkValue.value, pumpStatus.maxBolus); aapsLogger.error("Wrong Max Bolus set on Pump (current={}, required={}).", checkValue.value, medtronicUtil.getPumpStatus().maxBolus);
sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, pumpStatus.maxBolus); medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, medtronicUtil.getPumpStatus().maxBolus);
} }
checkValue = settings.get("PCFG_MAX_BASAL"); checkValue = settings.get("PCFG_MAX_BASAL");
if (!MedtronicUtil.isSame(Double.parseDouble(checkValue.value), pumpStatus.maxBasal)) { if (!medtronicUtil.isSame(Double.parseDouble(checkValue.value), medtronicUtil.getPumpStatus().maxBasal)) {
aapsLogger.error("Wrong Max Basal set on Pump (current={}, required={}).", checkValue.value, pumpStatus.maxBasal); aapsLogger.error("Wrong Max Basal set on Pump (current={}, required={}).", checkValue.value, medtronicUtil.getPumpStatus().maxBasal);
sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, pumpStatus.maxBasal); medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, medtronicUtil.getPumpStatus().maxBasal);
} }
} }

View file

@ -70,7 +70,7 @@ public class MedtronicUITask {
case GetRealTimeClock: { case GetRealTimeClock: {
returnData = communicationManager.getPumpTime(); returnData = communicationManager.getPumpTime();
MedtronicUtil.setPumpTime(null); MedtronicUtil.getInstance().setPumpTime(null);
} }
break; break;
@ -200,10 +200,10 @@ public class MedtronicUITask {
errorDescription)); errorDescription));
} else { } else {
RxBus.Companion.getINSTANCE().send(new EventMedtronicPumpValuesChanged()); RxBus.Companion.getINSTANCE().send(new EventMedtronicPumpValuesChanged());
MedtronicUtil.getPumpStatus().setLastCommunicationToNow(); MedtronicUtil.getInstance().getPumpStatus().setLastCommunicationToNow();
} }
MedtronicUtil.setCurrentCommand(null); MedtronicUtil.getInstance().setCurrentCommand(null);
} }

View file

@ -69,7 +69,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class MedtronicHistoryData { public class MedtronicHistoryData {
private static AAPSLogger aapsLogger; private AAPSLogger aapsLogger;
private SP sp; private SP sp;
private ActivePluginProvider activePlugin; private ActivePluginProvider activePlugin;
@ -97,20 +97,12 @@ public class MedtronicHistoryData {
public MedtronicHistoryData(AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin) { public MedtronicHistoryData(AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin) {
this.allHistory = new ArrayList<>(); this.allHistory = new ArrayList<>();
this.gson = MedtronicUtil.gsonInstance; this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
this.gsonCore = MedtronicUtil.getGsonInstanceCore(); this.gsonCore = new GsonBuilder().create();
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.sp = sp; this.sp = sp;
this.activePlugin = activePlugin; this.activePlugin = activePlugin;
if (this.gson == null) {
this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
}
if (this.gsonCore == null) {
this.gsonCore = new GsonBuilder().create();
}
} }
@ -138,7 +130,7 @@ public class MedtronicHistoryData {
} }
private static void showLogs(String header, String data) { private void showLogs(String header, String data) {
if (header != null) { if (header != null) {
aapsLogger.debug(LTag.PUMP, header); aapsLogger.debug(LTag.PUMP, header);
} }
@ -321,7 +313,7 @@ public class MedtronicHistoryData {
List<PumpHistoryEntry> items = getDataForPumpSuspends(); List<PumpHistoryEntry> items = getDataForPumpSuspends();
showLogs("isPumpSuspended: ", MedtronicUtil.gsonInstance.toJson(items)); showLogs("isPumpSuspended: ", gson.toJson(items));
if (isCollectionNotEmpty(items)) { if (isCollectionNotEmpty(items)) {
@ -432,7 +424,7 @@ public class MedtronicHistoryData {
} }
} }
pumpTime = MedtronicUtil.getPumpTime(); pumpTime = MedtronicUtil.getInstance().getPumpTime();
// Bolus // Bolus
List<PumpHistoryEntry> treatments = getFilteredItems(PumpHistoryEntryType.Bolus); List<PumpHistoryEntry> treatments = getFilteredItems(PumpHistoryEntryType.Bolus);
@ -595,8 +587,6 @@ public class MedtronicHistoryData {
long oldestTimestamp = getOldestTimestamp(entryList); long oldestTimestamp = getOldestTimestamp(entryList);
Gson gson = MedtronicUtil.getGsonInstance();
List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus); List<? extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus);
if (doubleBolusDebug) if (doubleBolusDebug)
@ -976,7 +966,7 @@ public class MedtronicHistoryData {
treatment.pumpId = bolus.getPumpId(); treatment.pumpId = bolus.getPumpId();
treatment.insulin = bolusDTO.getDeliveredAmount(); treatment.insulin = bolusDTO.getDeliveredAmount();
TreatmentService.UpdateReturn updateReturn = ((TreatmentsPlugin)activePlugin.getActiveTreatments()).getService().createOrUpdateMedtronic(treatment, false); TreatmentService.UpdateReturn updateReturn = ((TreatmentsPlugin) activePlugin.getActiveTreatments()).getService().createOrUpdateMedtronic(treatment, false);
if (doubleBolusDebug) if (doubleBolusDebug)
aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn); aapsLogger.debug(LTag.PUMP, "DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn);
@ -1370,11 +1360,11 @@ public class MedtronicHistoryData {
private PumpHistoryEntryType getTDDType() { private PumpHistoryEntryType getTDDType() {
if (MedtronicUtil.getMedtronicPumpModel() == null) { if (MedtronicUtil.getInstance().getMedtronicPumpModel() == null) {
return PumpHistoryEntryType.EndResultTotals; return PumpHistoryEntryType.EndResultTotals;
} }
switch (MedtronicUtil.getMedtronicPumpModel()) { switch (MedtronicUtil.getInstance().getMedtronicPumpModel()) {
case Medtronic_515: case Medtronic_515:
case Medtronic_715: case Medtronic_715:

View file

@ -73,7 +73,7 @@ public class BasalProfile {
// if we have just one entry through all day it looks like just length 1 // if we have just one entry through all day it looks like just length 1
if (data.length == 1) { if (data.length == 1) {
data = MedtronicUtil.createByteArray(data[0], (byte) 0, (byte) 0); data = MedtronicUtil.getInstance().createByteArray(data[0], (byte) 0, (byte) 0);
} }
if (data.length == MAX_RAW_DATA_SIZE) { if (data.length == MAX_RAW_DATA_SIZE) {
@ -230,7 +230,7 @@ public class BasalProfile {
if ((mRawData[i] == 0) && (mRawData[i + 1] == 0) && (mRawData[i + 2] == 0x3f)) if ((mRawData[i] == 0) && (mRawData[i + 1] == 0) && (mRawData[i + 2] == 0x3f))
break; break;
r = MedtronicUtil.makeUnsignedShort(mRawData[i + 1], mRawData[i]); // readUnsignedByte(mRawData[i]); r = MedtronicUtil.getInstance().makeUnsignedShort(mRawData[i + 1], mRawData[i]); // readUnsignedByte(mRawData[i]);
st = readUnsignedByte(mRawData[i + 2]); st = readUnsignedByte(mRawData[i + 2]);
try { try {
@ -265,14 +265,14 @@ public class BasalProfile {
for (BasalProfileEntry profileEntry : listEntries) { for (BasalProfileEntry profileEntry : listEntries) {
byte[] strokes = MedtronicUtil.getBasalStrokes(profileEntry.rate, true); byte[] strokes = MedtronicUtil.getInstance().getBasalStrokes(profileEntry.rate, true);
outData.add(profileEntry.rate_raw[0]); outData.add(profileEntry.rate_raw[0]);
outData.add(profileEntry.rate_raw[1]); outData.add(profileEntry.rate_raw[1]);
outData.add(profileEntry.startTime_raw); outData.add(profileEntry.startTime_raw);
} }
this.setRawData(MedtronicUtil.createByteArray(outData)); this.setRawData(MedtronicUtil.getInstance().createByteArray(outData));
// return this.mRawData; // return this.mRawData;
} }
@ -305,7 +305,7 @@ public class BasalProfile {
Double[] basalByHour = new Double[24]; Double[] basalByHour = new Double[24];
PumpType pumpType = MedtronicUtil.getPumpStatus().pumpType; PumpType pumpType = MedtronicUtil.getInstance().getPumpStatus().pumpType;
for (int i = 0; i < entries.size(); i++) { for (int i = 0; i < entries.size(); i++) {
BasalProfileEntry current = entries.get(i); BasalProfileEntry current = entries.get(i);

View file

@ -25,14 +25,14 @@ public class BasalProfileEntry {
public BasalProfileEntry() { public BasalProfileEntry() {
rate = -9.999E6; rate = -9.999E6;
rate_raw = MedtronicUtil.getByteArrayFromUnsignedShort(0xFF, true); rate_raw = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(0xFF, true);
startTime = new LocalTime(0); startTime = new LocalTime(0);
startTime_raw = (byte)0xFF; startTime_raw = (byte)0xFF;
} }
public BasalProfileEntry(double rate, int hour, int minutes) { public BasalProfileEntry(double rate, int hour, int minutes) {
byte[] data = MedtronicUtil.getBasalStrokes(rate, true); byte[] data = MedtronicUtil.getInstance().getBasalStrokes(rate, true);
rate_raw = new byte[2]; rate_raw = new byte[2];
rate_raw[0] = data[1]; rate_raw[0] = data[1];
@ -52,7 +52,7 @@ public class BasalProfileEntry {
public BasalProfileEntry(int rateStrokes, int startTimeInterval) { public BasalProfileEntry(int rateStrokes, int startTimeInterval) {
// rateByte is insulin delivery rate, U/hr, in 0.025 U increments // rateByte is insulin delivery rate, U/hr, in 0.025 U increments
// startTimeByte is time-of-day, in 30 minute increments // startTimeByte is time-of-day, in 30 minute increments
rate_raw = MedtronicUtil.getByteArrayFromUnsignedShort(rateStrokes, true); rate_raw = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(rateStrokes, true);
rate = rateStrokes * 0.025; rate = rateStrokes * 0.025;
startTime_raw = (byte)startTimeInterval; startTime_raw = (byte)startTimeInterval;
@ -71,7 +71,7 @@ public class BasalProfileEntry {
public BasalProfileEntry(byte rateByte, int startTimeByte) { public BasalProfileEntry(byte rateByte, int startTimeByte) {
// rateByte is insulin delivery rate, U/hr, in 0.025 U increments // rateByte is insulin delivery rate, U/hr, in 0.025 U increments
// startTimeByte is time-of-day, in 30 minute increments // startTimeByte is time-of-day, in 30 minute increments
rate_raw = MedtronicUtil.getByteArrayFromUnsignedShort(rateByte, true); rate_raw = MedtronicUtil.getInstance().getByteArrayFromUnsignedShort(rateByte, true);
rate = rateByte * 0.025; rate = rateByte * 0.025;
startTime_raw = (byte)startTimeByte; startTime_raw = (byte)startTimeByte;
startTime = new LocalTime(startTimeByte / 2, (startTimeByte % 2) * 30); startTime = new LocalTime(startTimeByte / 2, (startTimeByte % 2) * 30);

View file

@ -56,7 +56,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo
if (isPercent) { if (isPercent) {
insulinRate = response[1]; insulinRate = response[1];
} else { } else {
int strokes = MedtronicUtil.makeUnsignedShort(response[2], response[3]); int strokes = MedtronicUtil.getInstance().makeUnsignedShort(response[2], response[3]);
insulinRate = strokes / 40.0d; insulinRate = strokes / 40.0d;
} }
@ -64,7 +64,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo
if (response.length<6) { if (response.length<6) {
durationMinutes = ByteUtil.asUINT8(response[4]); durationMinutes = ByteUtil.asUINT8(response[4]);
} else { } else {
durationMinutes = MedtronicUtil.makeUnsignedShort(response[4], response[5]); durationMinutes = MedtronicUtil.getInstance().makeUnsignedShort(response[4], response[5]);
} }
LOG.warn("TempBasalPair (with {} byte response): {}", response.length, toString()); LOG.warn("TempBasalPair (with {} byte response): {}", response.length, toString());
@ -83,8 +83,8 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo
list.add((byte) 5); list.add((byte) 5);
byte[] insulinRate = MedtronicUtil.getBasalStrokes(this.insulinRate, true); byte[] insulinRate = MedtronicUtil.getInstance().getBasalStrokes(this.insulinRate, true);
byte timeMin = (byte) MedtronicUtil.getIntervalFromMinutes(durationMinutes); byte timeMin = (byte) MedtronicUtil.getInstance().getIntervalFromMinutes(durationMinutes);
// list.add((byte) 0); // ? // list.add((byte) 0); // ?
@ -107,11 +107,11 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo
list.add(insulinRate[1]); list.add(insulinRate[1]);
return MedtronicUtil.createByteArray(list); return MedtronicUtil.getInstance().createByteArray(list);
} }
public boolean isCancelTBR() { public boolean isCancelTBR() {
return (MedtronicUtil.isSame(insulinRate, 0.0d) && durationMinutes == 0); return (MedtronicUtil.getInstance().isSame(insulinRate, 0.0d) && durationMinutes == 0);
} }

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.medtronic.defs; package info.nightscout.androidaps.plugins.pump.medtronic.defs;
import androidx.annotation.StringRes;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -19,30 +21,14 @@ public enum BatteryType {
NiMH(R.string.key_medtronic_pump_battery_nimh, 1.10d, 1.40d) // NiMH(R.string.key_medtronic_pump_battery_nimh, 1.10d, 1.40d) //
; ;
private final String description; public final @StringRes int description;
public double lowVoltage; public final double lowVoltage;
public double highVoltage; public final double highVoltage;
static Map<String, BatteryType> mapByDescription;
static {
mapByDescription = new HashMap<>();
for (BatteryType value : values()) {
mapByDescription.put(value.description, value);
}
}
BatteryType(int resId, double lowVoltage, double highVoltage) { BatteryType(int resId, double lowVoltage, double highVoltage) {
this.description = MainApp.gs(resId); this.description = resId;
this.lowVoltage = lowVoltage; this.lowVoltage = lowVoltage;
this.highVoltage = highVoltage; this.highVoltage = highVoltage;
} }
public static BatteryType getByDescription(String batteryTypeStr) {
if (mapByDescription.containsKey(batteryTypeStr)) {
return mapByDescription.get(batteryTypeStr);
}
return BatteryType.None;
}
} }

View file

@ -32,7 +32,7 @@ public enum MedtronicStatusRefreshType {
public MedtronicCommandType getCommandType() { public MedtronicCommandType getCommandType() {
if (this == Configuration) { if (this == Configuration) {
return MedtronicCommandType.getSettings(MedtronicUtil.getMedtronicPumpModel()); return MedtronicCommandType.getSettings(MedtronicUtil.getInstance().getMedtronicPumpModel());
} else } else
return commandType; return commandType;
} }

View file

@ -1,8 +1,6 @@
package info.nightscout.androidaps.plugins.pump.medtronic.driver; package info.nightscout.androidaps.plugins.pump.medtronic.driver;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
@ -10,11 +8,14 @@ import java.util.GregorianCalendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; 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.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
@ -31,14 +32,17 @@ 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.MedtronicConst;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
/** /**
* Created by andy on 4/28/18. * Created by andy on 4/28/18.
*/ */
@Singleton
public class MedtronicPumpStatus extends PumpStatus { public class MedtronicPumpStatus extends PumpStatus {
private static Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMP); private final AAPSLogger aapsLogger;
private final ResourceHelper resourceHelper;
public String errorDescription = null; public String errorDescription = null;
public String serialNumber; public String serialNumber;
@ -81,8 +85,15 @@ public class MedtronicPumpStatus extends PumpStatus {
public BatteryType batteryType = BatteryType.None; public BatteryType batteryType = BatteryType.None;
public MedtronicPumpStatus(PumpDescription pumpDescription) { @Inject
public MedtronicPumpStatus(
AAPSLogger aapsLogger,
ResourceHelper resourceHelper,
PumpDescription pumpDescription
) {
super(pumpDescription); super(pumpDescription);
this.aapsLogger = aapsLogger;
this.resourceHelper = resourceHelper;
} }
@ -211,7 +222,7 @@ public class MedtronicPumpStatus extends PumpStatus {
: RileyLinkTargetFrequency.Medtronic_WorldWide; : RileyLinkTargetFrequency.Medtronic_WorldWide;
if (targetFrequency != newTargetFrequency) { if (targetFrequency != newTargetFrequency) {
RileyLinkUtil.setRileyLinkTargetFrequency(newTargetFrequency); RileyLinkUtil.getInstance().setRileyLinkTargetFrequency(newTargetFrequency);
targetFrequency = newTargetFrequency; targetFrequency = newTargetFrequency;
targetFrequencyChanged = true; targetFrequencyChanged = true;
} }
@ -222,15 +233,13 @@ public class MedtronicPumpStatus extends PumpStatus {
String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null); String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null);
if (rileyLinkAddress == null) { if (rileyLinkAddress == null) {
if (isLogEnabled()) aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: null");
LOG.debug("RileyLink address invalid: null");
this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid); this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid);
return false; return false;
} else { } else {
if (!rileyLinkAddress.matches(regexMac)) { if (!rileyLinkAddress.matches(regexMac)) {
this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid); this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid);
if (isLogEnabled()) aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: {}", rileyLinkAddress);
LOG.debug("RileyLink address invalid: {}", rileyLinkAddress);
} else { } else {
if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { if (!rileyLinkAddress.equals(this.rileyLinkAddress)) {
this.rileyLinkAddress = rileyLinkAddress; this.rileyLinkAddress = rileyLinkAddress;
@ -276,11 +285,11 @@ public class MedtronicPumpStatus extends PumpStatus {
if (batteryTypeStr == null) if (batteryTypeStr == null)
return false; return false;
BatteryType batteryType = BatteryType.getByDescription(batteryTypeStr); BatteryType batteryType = getBatteryTypeByDescription(batteryTypeStr);
if (this.batteryType != batteryType) { if (this.batteryType != batteryType) {
this.batteryType = batteryType; this.batteryType = batteryType;
MedtronicUtil.setBatteryType(this.batteryType); MedtronicUtil.getInstance().setBatteryType(this.batteryType);
} }
String bolusDebugEnabled = SP.getString(MedtronicConst.Prefs.BolusDebugEnabled, null); String bolusDebugEnabled = SP.getString(MedtronicConst.Prefs.BolusDebugEnabled, null);
@ -295,7 +304,7 @@ public class MedtronicPumpStatus extends PumpStatus {
} catch (Exception ex) { } catch (Exception ex) {
this.errorDescription = ex.getMessage(); this.errorDescription = ex.getMessage();
LOG.error("Error on Verification: " + ex.getMessage(), ex); aapsLogger.error(LTag.PUMP, "Error on Verification: " + ex.getMessage(), ex);
return false; return false;
} }
} }
@ -303,20 +312,20 @@ public class MedtronicPumpStatus extends PumpStatus {
private boolean reconfigureService() { private boolean reconfigureService() {
if (!inPreInit && MedtronicUtil.getMedtronicService() != null) { if (!inPreInit && MedtronicUtil.getInstance().getMedtronicService() != null) {
if (serialChanged) { if (serialChanged) {
MedtronicUtil.getMedtronicService().setPumpIDString(this.serialNumber); // short operation MedtronicUtil.getInstance().getMedtronicService().setPumpIDString(this.serialNumber); // short operation
serialChanged = false; serialChanged = false;
} }
if (rileyLinkAddressChanged) { if (rileyLinkAddressChanged) {
MedtronicUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); RileyLinkUtil.getInstance().sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet);
rileyLinkAddressChanged = false; rileyLinkAddressChanged = false;
} }
if (encodingChanged) { if (encodingChanged) {
RileyLinkUtil.getRileyLinkService().changeRileyLinkEncoding(encodingType); RileyLinkUtil.getInstance().getRileyLinkService().changeRileyLinkEncoding(encodingType);
encodingChanged = false; encodingChanged = false;
} }
} }
@ -340,7 +349,7 @@ public class MedtronicPumpStatus extends PumpStatus {
try { try {
val = Double.parseDouble(value); val = Double.parseDouble(value);
} catch (Exception ex) { } catch (Exception ex) {
LOG.error("Error parsing setting: {}, value found {}", key, value); aapsLogger.error("Error parsing setting: {}, value found {}", key, value);
val = defaultValueDouble; val = defaultValueDouble;
} }
@ -384,8 +393,20 @@ public class MedtronicPumpStatus extends PumpStatus {
return 0; return 0;
} }
private boolean isLogEnabled() { // Battery type
return L.isEnabled(L.PUMP); Map<String, BatteryType> mapByDescription;
public BatteryType getBatteryTypeByDescription(String batteryTypeStr) {
if (mapByDescription == null) {
mapByDescription = new HashMap<>();
for (BatteryType value : BatteryType.values()) {
mapByDescription.put(MainApp.gs(value.description), value);
}
}
if (mapByDescription.containsKey(batteryTypeStr)) {
return mapByDescription.get(batteryTypeStr);
}
return BatteryType.None;
} }
} }

View file

@ -36,11 +36,10 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
*/ */
public class RileyLinkMedtronicService extends RileyLinkService { public class RileyLinkMedtronicService extends RileyLinkService {
//@Inject AAPSLogger aapsLogger;
//@Inject Context context;
@Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject MedtronicPumpPlugin medtronicPumpPlugin;
//@Inject SP sp; @Inject MedtronicUtil medtronicUtil;
@Deprecated // TEDO remove this reference
private static RileyLinkMedtronicService instance; private static RileyLinkMedtronicService instance;
private static ServiceTask currentTask = null; private static ServiceTask currentTask = null;
@ -87,8 +86,8 @@ public class RileyLinkMedtronicService extends RileyLinkService {
rileyLinkServiceData = new RileyLinkServiceData(RileyLinkTargetDevice.MedtronicPump); rileyLinkServiceData = new RileyLinkServiceData(RileyLinkTargetDevice.MedtronicPump);
RileyLinkUtil.setRileyLinkServiceData(rileyLinkServiceData); rileyLinkUtil.setRileyLinkServiceData(rileyLinkServiceData);
RileyLinkUtil.setTargetDevice(RileyLinkTargetDevice.MedtronicPump); rileyLinkUtil.setTargetDevice(RileyLinkTargetDevice.MedtronicPump);
setPumpIDString(sp.getString(MedtronicConst.Prefs.PumpSerial, "000000")); setPumpIDString(sp.getString(MedtronicConst.Prefs.PumpSerial, "000000"));
@ -99,13 +98,13 @@ public class RileyLinkMedtronicService extends RileyLinkService {
rfspy = new RFSpy(rileyLinkBLE); rfspy = new RFSpy(rileyLinkBLE);
rfspy.startReader(); rfspy.startReader();
RileyLinkUtil.setRileyLinkBLE(rileyLinkBLE); rileyLinkUtil.setRileyLinkBLE(rileyLinkBLE);
// init rileyLinkCommunicationManager // init rileyLinkCommunicationManager
medtronicCommunicationManager = new MedtronicCommunicationManager(rfspy); medtronicCommunicationManager = new MedtronicCommunicationManager(rfspy);
aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed"); aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly constructed");
MedtronicUtil.setMedtronicService(this); medtronicUtil.setMedtronicService(this);
pumpStatus = (MedtronicPumpStatus) medtronicPumpPlugin.getPumpStatusData(); pumpStatus = (MedtronicPumpStatus) medtronicPumpPlugin.getPumpStatusData();
} }
@ -153,13 +152,13 @@ public class RileyLinkMedtronicService extends RileyLinkService {
rileyLinkServiceData.setPumpID(pumpID, pumpIDBytes); rileyLinkServiceData.setPumpID(pumpID, pumpIDBytes);
if (oldId != null && !oldId.equals(pumpID)) { if (oldId != null && !oldId.equals(pumpID)) {
MedtronicUtil.setMedtronicPumpModel(null); // if we change pumpId, model probably changed too medtronicUtil.setMedtronicPumpModel(null); // if we change pumpId, model probably changed too
} }
return; return;
} }
MedtronicUtil.setPumpDeviceState(PumpDeviceState.InvalidConfiguration); medtronicUtil.setPumpDeviceState(PumpDeviceState.InvalidConfiguration);
// LOG.info("setPumpIDString: saved pumpID " + idString); // LOG.info("setPumpIDString: saved pumpID " + idString);
} }
@ -177,7 +176,7 @@ public class RileyLinkMedtronicService extends RileyLinkService {
// PumpInterface - REMOVE // PumpInterface - REMOVE
public boolean isInitialized() { public boolean isInitialized() {
return RileyLinkServiceState.isReady(RileyLinkUtil.getRileyLinkServiceData().serviceState); return RileyLinkServiceState.isReady(rileyLinkUtil.getRileyLinkServiceData().serviceState);
} }

View file

@ -1,10 +1,12 @@
package info.nightscout.androidaps.plugins.pump.medtronic.util; package info.nightscout.androidaps.plugins.pump.medtronic.util;
import android.content.Context;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import org.jetbrains.annotations.NotNull;
import org.joda.time.LocalTime; import org.joda.time.LocalTime;
import org.slf4j.Logger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@ -12,10 +14,12 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -42,37 +46,64 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
* Created by andy on 5/9/18. * Created by andy on 5/9/18.
*/ */
public class MedtronicUtil extends RileyLinkUtil { @Singleton
public class MedtronicUtil {
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); private int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS]
static int ENVELOPE_SIZE = 4; // 0xA7 S1 S2 S3 CMD PARAM_COUNT [PARAMS] int CRC_SIZE = 1;
static int CRC_SIZE = 1; private boolean lowLevelDebug = true;
private static boolean lowLevelDebug = true; private PumpDeviceState pumpDeviceState;
private static PumpDeviceState pumpDeviceState; private MedtronicDeviceType medtronicPumpModel;
private static MedtronicDeviceType medtronicPumpModel; private RileyLinkMedtronicService medtronicService;
private static RileyLinkMedtronicService medtronicService; @Deprecated // TODO remove this reference
private static MedtronicPumpStatus medtronicPumpStatus; private MedtronicPumpStatus medtronicPumpStatus;
private static MedtronicCommandType currentCommand; private MedtronicCommandType currentCommand;
private static Map<String, PumpSettingDTO> settings; private Map<String, PumpSettingDTO> settings;
private static int BIG_FRAME_LENGTH = 65; private int BIG_FRAME_LENGTH = 65;
private static int doneBit = 1 << 7; private int doneBit = 1 << 7;
private static ClockDTO pumpTime; private ClockDTO pumpTime;
public static Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); public Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
public static Gson gsonInstanceCore = new GsonBuilder().create(); public Gson gsonInstanceCore = new GsonBuilder().create();
private static BatteryType batteryType = BatteryType.None; private BatteryType batteryType = BatteryType.None;
@NotNull private final AAPSLogger aapsLogger;
@NotNull private final RxBusWrapper rxBus;
@NotNull private final RileyLinkUtil rileyLinkUtil;
public static Gson getGsonInstance() { @Inject
public MedtronicUtil(
Context context,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
RileyLinkUtil rileyLinkUtil
) {
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 Gson getGsonInstance() {
return gsonInstance; return gsonInstance;
} }
public static Gson getGsonInstanceCore() { public Gson getGsonInstanceCore() {
return gsonInstanceCore; return gsonInstanceCore;
} }
public static LocalTime getTimeFrom30MinInterval(int interval) { public LocalTime getTimeFrom30MinInterval(int interval) {
if (interval % 2 == 0) { if (interval % 2 == 0) {
return new LocalTime(interval / 2, 0); return new LocalTime(interval / 2, 0);
} else { } else {
@ -81,23 +112,23 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static int getIntervalFromMinutes(int minutes) { public int getIntervalFromMinutes(int minutes) {
return minutes / 30; return minutes / 30;
} }
public static int makeUnsignedShort(int b2, int b1) { public int makeUnsignedShort(int b2, int b1) {
int k = (b2 & 0xff) << 8 | b1 & 0xff; int k = (b2 & 0xff) << 8 | b1 & 0xff;
return k; return k;
} }
public static boolean isMedtronicPump() { public boolean isMedtronicPump() {
return MedtronicPumpPlugin.getPlugin().isEnabled(PluginType.PUMP); return MedtronicPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
//return ConfigBuilderPlugin.getPlugin().getActivePump().deviceID().equals("Medtronic"); //return ConfigBuilderPlugin.getPlugin().getActivePump().deviceID().equals("Medtronic");
} }
public static byte[] getByteArrayFromUnsignedShort(int shortValue, boolean returnFixedSize) { public byte[] getByteArrayFromUnsignedShort(int shortValue, boolean returnFixedSize) {
byte highByte = (byte) (shortValue >> 8 & 0xFF); byte highByte = (byte) (shortValue >> 8 & 0xFF);
byte lowByte = (byte) (shortValue & 0xFF); byte lowByte = (byte) (shortValue & 0xFF);
@ -110,12 +141,12 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static byte[] createByteArray(byte... data) { public byte[] createByteArray(byte... data) {
return data; return data;
} }
public static byte[] createByteArray(List<Byte> data) { public byte[] createByteArray(List<Byte> data) {
byte[] array = new byte[data.size()]; byte[] array = new byte[data.size()];
@ -127,32 +158,32 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static double decodeBasalInsulin(int i, int j) { public double decodeBasalInsulin(int i, int j) {
return decodeBasalInsulin(makeUnsignedShort(i, j)); return decodeBasalInsulin(makeUnsignedShort(i, j));
} }
public static double decodeBasalInsulin(int i) { public double decodeBasalInsulin(int i) {
return (double) i / 40.0d; return (double) i / 40.0d;
} }
public static byte[] getBasalStrokes(double amount) { public byte[] getBasalStrokes(double amount) {
return getBasalStrokes(amount, false); return getBasalStrokes(amount, false);
} }
public static byte[] getBasalStrokes(double amount, boolean returnFixedSize) { public byte[] getBasalStrokes(double amount, boolean returnFixedSize) {
return getStrokes(amount, 40, returnFixedSize); return getStrokes(amount, 40, returnFixedSize);
} }
public static int getBasalStrokesInt(double amount) { public int getBasalStrokesInt(double amount) {
return getStrokesInt(amount, 40); return getStrokesInt(amount, 40);
} }
public static byte[] getBolusStrokes(double amount) { public byte[] getBolusStrokes(double amount) {
int strokesPerUnit = medtronicPumpModel.getBolusStrokes(); int strokesPerUnit = medtronicPumpModel.getBolusStrokes();
@ -184,13 +215,13 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static byte[] createCommandBody(byte[] input) { public byte[] createCommandBody(byte[] input) {
return ByteUtil.concat((byte) input.length, input); return ByteUtil.concat((byte) input.length, input);
} }
public static byte[] getStrokes(double amount, int strokesPerUnit, boolean returnFixedSize) { public byte[] getStrokes(double amount, int strokesPerUnit, boolean returnFixedSize) {
int strokes = getStrokesInt(amount, strokesPerUnit); int strokes = getStrokesInt(amount, strokesPerUnit);
@ -199,7 +230,7 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static int getStrokesInt(double amount, int strokesPerUnit) { public int getStrokesInt(double amount, int strokesPerUnit) {
int length = 1; int length = 1;
int scrollRate = 1; int scrollRate = 1;
@ -223,7 +254,7 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static void sendNotification(MedtronicNotificationType notificationType, ResourceHelper resourceHelper, RxBusWrapper rxBus) { public void sendNotification(MedtronicNotificationType notificationType, ResourceHelper resourceHelper, RxBusWrapper rxBus) {
Notification notification = new Notification( // Notification notification = new Notification( //
notificationType.getNotificationType(), // notificationType.getNotificationType(), //
resourceHelper.gs(notificationType.getResourceId()), // resourceHelper.gs(notificationType.getResourceId()), //
@ -232,7 +263,7 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static void sendNotification(MedtronicNotificationType notificationType, ResourceHelper resourceHelper, RxBusWrapper rxBus, Object... parameters) { public void sendNotification(MedtronicNotificationType notificationType, ResourceHelper resourceHelper, RxBusWrapper rxBus, Object... parameters) {
Notification notification = new Notification( // Notification notification = new Notification( //
notificationType.getNotificationType(), // notificationType.getNotificationType(), //
resourceHelper.gs(notificationType.getResourceId(), parameters), // resourceHelper.gs(notificationType.getResourceId(), parameters), //
@ -241,22 +272,22 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static void dismissNotification(MedtronicNotificationType notificationType, RxBusWrapper rxBus) { public void dismissNotification(MedtronicNotificationType notificationType, RxBusWrapper rxBus) {
rxBus.send(new EventDismissNotification(notificationType.getNotificationType())); rxBus.send(new EventDismissNotification(notificationType.getNotificationType()));
} }
// public static byte[] buildCommandPayload(MessageType commandType, byte[] parameters) { // public byte[] buildCommandPayload(MessageType commandType, byte[] parameters) {
// return buildCommandPayload(commandType.getValue(), parameters); // return buildCommandPayload(commandType.getValue(), parameters);
// } // }
public static byte[] buildCommandPayload(MedtronicCommandType commandType, byte[] parameters) { public byte[] buildCommandPayload(MedtronicCommandType commandType, byte[] parameters) {
return buildCommandPayload((byte) commandType.commandCode, parameters); return buildCommandPayload((byte) commandType.commandCode, parameters);
} }
public static byte[] buildCommandPayload(byte commandType, byte[] parameters) { public byte[] buildCommandPayload(byte commandType, byte[] parameters) {
// A7 31 65 51 C0 00 52 // A7 31 65 51 C0 00 52
byte commandLength = (byte) (parameters == null ? 2 : 2 + parameters.length); byte commandLength = (byte) (parameters == null ? 2 : 2 + parameters.length);
@ -264,7 +295,7 @@ public class MedtronicUtil extends RileyLinkUtil {
ByteBuffer sendPayloadBuffer = ByteBuffer.allocate(ENVELOPE_SIZE + commandLength); // + CRC_SIZE ByteBuffer sendPayloadBuffer = ByteBuffer.allocate(ENVELOPE_SIZE + commandLength); // + CRC_SIZE
sendPayloadBuffer.order(ByteOrder.BIG_ENDIAN); sendPayloadBuffer.order(ByteOrder.BIG_ENDIAN);
byte[] serialNumberBCD = RileyLinkUtil.getRileyLinkServiceData().pumpIDBytes; byte[] serialNumberBCD = rileyLinkUtil.getRileyLinkServiceData().pumpIDBytes;
sendPayloadBuffer.put((byte) 0xA7); sendPayloadBuffer.put((byte) 0xA7);
sendPayloadBuffer.put(serialNumberBCD[0]); sendPayloadBuffer.put(serialNumberBCD[0]);
@ -285,8 +316,7 @@ public class MedtronicUtil extends RileyLinkUtil {
byte[] payload = sendPayloadBuffer.array(); byte[] payload = sendPayloadBuffer.array();
if (L.isEnabled(L.PUMPCOMM)) aapsLogger.debug(LTag.PUMPBTCOMM, "buildCommandPayload [{}]", ByteUtil.shortHexString(payload));
LOG.debug("buildCommandPayload [{}]", ByteUtil.shortHexString(payload));
// int crc = computeCRC8WithPolynomial(payload, 0, payload.length - 1); // int crc = computeCRC8WithPolynomial(payload, 0, payload.length - 1);
@ -300,7 +330,7 @@ public class MedtronicUtil extends RileyLinkUtil {
// Note: at the moment supported only for 24 items, if you will use it for more than // Note: at the moment supported only for 24 items, if you will use it for more than
// that you will need to add // that you will need to add
public static List<List<Byte>> getBasalProfileFrames(byte[] data) { public List<List<Byte>> getBasalProfileFrames(byte[] data) {
boolean done = false; boolean done = false;
int start = 0; int start = 0;
@ -372,7 +402,7 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
private static void checkAndAppenLastFrame(List<Byte> frameData) { private void checkAndAppenLastFrame(List<Byte> frameData) {
if (frameData.size() == BIG_FRAME_LENGTH) if (frameData.size() == BIG_FRAME_LENGTH)
return; return;
@ -385,7 +415,7 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
private static boolean isEmptyFrame(List<Byte> frameData) { private boolean isEmptyFrame(List<Byte> frameData) {
for (Byte frameDateEntry : frameData) { for (Byte frameDateEntry : frameData) {
if (frameDateEntry != 0x00) { if (frameDateEntry != 0x00) {
@ -397,132 +427,133 @@ public class MedtronicUtil extends RileyLinkUtil {
} }
public static boolean isLowLevelDebug() { public boolean isLowLevelDebug() {
return lowLevelDebug; return lowLevelDebug;
} }
public static void setLowLevelDebug(boolean lowLevelDebug) { public void setLowLevelDebug(boolean lowLevelDebug) {
MedtronicUtil.lowLevelDebug = lowLevelDebug; this.lowLevelDebug = lowLevelDebug;
} }
public static PumpDeviceState getPumpDeviceState() { public PumpDeviceState getPumpDeviceState() {
return pumpDeviceState; return pumpDeviceState;
} }
public static void setPumpDeviceState(PumpDeviceState pumpDeviceState) { public void setPumpDeviceState(PumpDeviceState pumpDeviceState) {
MedtronicUtil.pumpDeviceState = pumpDeviceState; this.pumpDeviceState = pumpDeviceState;
historyRileyLink.add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.MedtronicPump)); rileyLinkUtil.historyRileyLink.add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.MedtronicPump));
RxBus.Companion.getINSTANCE().send(new EventMedtronicDeviceStatusChange(pumpDeviceState)); rxBus.send(new EventMedtronicDeviceStatusChange(pumpDeviceState));
} }
public static boolean isModelSet() { public boolean isModelSet() {
return MedtronicUtil.medtronicPumpModel != null; return medtronicPumpModel != null;
} }
public static MedtronicDeviceType getMedtronicPumpModel() { public MedtronicDeviceType getMedtronicPumpModel() {
return MedtronicUtil.medtronicPumpModel; return medtronicPumpModel;
} }
public static void setMedtronicPumpModel(MedtronicDeviceType medtronicPumpModel) { public void setMedtronicPumpModel(MedtronicDeviceType medtronicPumpModel) {
MedtronicUtil.medtronicPumpModel = medtronicPumpModel; this.medtronicPumpModel = medtronicPumpModel;
} }
public static MedtronicCommunicationManager getMedtronicCommunicationManager() { public MedtronicCommunicationManager getMedtronicCommunicationManager() {
return (MedtronicCommunicationManager) RileyLinkUtil.rileyLinkCommunicationManager; return (MedtronicCommunicationManager) rileyLinkUtil.rileyLinkCommunicationManager;
} }
public static RileyLinkMedtronicService getMedtronicService() { public RileyLinkMedtronicService getMedtronicService() {
return MedtronicUtil.medtronicService; return medtronicService;
} }
public static void setMedtronicService(RileyLinkMedtronicService medtronicService) { public void setMedtronicService(RileyLinkMedtronicService medtronicService) {
MedtronicUtil.medtronicService = medtronicService; this.medtronicService = medtronicService;
} }
public static MedtronicPumpStatus getPumpStatus() { @Deprecated // TODO use singleton
return MedtronicUtil.medtronicPumpStatus; public MedtronicPumpStatus getPumpStatus() {
return medtronicPumpStatus;
}
@Deprecated // TODO use singleton
public void setPumpStatus(MedtronicPumpStatus medtronicPumpStatus) {
this.medtronicPumpStatus = medtronicPumpStatus;
} }
public static void setPumpStatus(MedtronicPumpStatus medtronicPumpStatus) { public MedtronicCommandType getCurrentCommand() {
MedtronicUtil.medtronicPumpStatus = medtronicPumpStatus; return this.currentCommand;
} }
public static MedtronicCommandType getCurrentCommand() { public void setCurrentCommand(MedtronicCommandType currentCommand) {
return MedtronicUtil.currentCommand; this.currentCommand = currentCommand;
}
public static void setCurrentCommand(MedtronicCommandType currentCommand) {
MedtronicUtil.currentCommand = currentCommand;
if (currentCommand != null) if (currentCommand != null)
historyRileyLink.add(new RLHistoryItem(currentCommand)); rileyLinkUtil.historyRileyLink.add(new RLHistoryItem(currentCommand));
} }
public static int pageNumber; public int pageNumber;
public static Integer frameNumber; public Integer frameNumber;
public static void setCurrentCommand(MedtronicCommandType currentCommand, int pageNumber_, Integer frameNumber_) { public void setCurrentCommand(MedtronicCommandType currentCommand, int pageNumber_, Integer frameNumber_) {
pageNumber = pageNumber_; pageNumber = pageNumber_;
frameNumber = frameNumber_; frameNumber = frameNumber_;
if (MedtronicUtil.currentCommand != currentCommand) { if (this.currentCommand != currentCommand) {
setCurrentCommand(currentCommand); setCurrentCommand(currentCommand);
} }
RxBus.Companion.getINSTANCE().send(new EventMedtronicDeviceStatusChange(pumpDeviceState)); rxBus.send(new EventMedtronicDeviceStatusChange(pumpDeviceState));
} }
public static boolean isSame(Double d1, Double d2) { public boolean isSame(Double d1, Double d2) {
double diff = d1 - d2; double diff = d1 - d2;
return (Math.abs(diff) <= 0.000001); return (Math.abs(diff) <= 0.000001);
} }
public static Map<String, PumpSettingDTO> getSettings() { public Map<String, PumpSettingDTO> getSettings() {
return settings; return settings;
} }
public static void setSettings(Map<String, PumpSettingDTO> settings) { public void setSettings(Map<String, PumpSettingDTO> settings) {
MedtronicUtil.settings = settings; this.settings = settings;
} }
public static void setPumpTime(ClockDTO pumpTime) { public void setPumpTime(ClockDTO pumpTime) {
MedtronicUtil.pumpTime = pumpTime; this.pumpTime = pumpTime;
} }
public static ClockDTO getPumpTime() { public ClockDTO getPumpTime() {
return MedtronicUtil.pumpTime; return this.pumpTime;
} }
public static void setBatteryType(BatteryType batteryType) { public void setBatteryType(BatteryType batteryType) {
MedtronicUtil.batteryType = batteryType; this.batteryType = batteryType;
} }
public static BatteryType getBatteryType() { public BatteryType getBatteryType() {
return MedtronicUtil.batteryType; return this.batteryType;
} }

View file

@ -265,9 +265,9 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
if (treatment != null) { if (treatment != null) {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicUtil.isMedtronicPump()); log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicUtil.getInstance().isMedtronicPump());
if (!MedtronicUtil.isMedtronicPump()) if (!MedtronicUtil.getInstance().isMedtronicPump())
createOrUpdate(treatment); createOrUpdate(treatment);
else else
createOrUpdateMedtronic(treatment, true); createOrUpdateMedtronic(treatment, true);

View file

@ -8,6 +8,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.GsonBuilder;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -56,7 +57,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
@ -300,13 +300,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
synchronized (treatments) { synchronized (treatments) {
getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + MedtronicUtil.getGsonInstanceCore().toJson(treatments)); getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().create().toJson(treatments));
for (Treatment t : treatments) { for (Treatment t : treatments) {
if (t.date <= time && t.date >= fromTimestamp) if (t.date <= time && t.date >= fromTimestamp)
in5minback.add(t); in5minback.add(t);
} }
getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + MedtronicUtil.getGsonInstanceCore().toJson(in5minback)); getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().create().toJson(in5minback));
return in5minback; return in5minback;
} }
} }
@ -452,7 +452,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
TemporaryBasal runningTBR = getTempBasalFromHistory(i); TemporaryBasal runningTBR = getTempBasalFromHistory(i);
double running = basal; double running = basal;
if (runningTBR != null) { if (runningTBR != null) {
running = runningTBR.tempBasalConvertedToAbsolute(i, profile); running = runningTBR.tempBasalConvertedToAbsolute(i, profile);
} }
Treatment treatment = new Treatment(getInjector()); Treatment treatment = new Treatment(getInjector());
treatment.date = i; treatment.date = i;

View file

@ -15,13 +15,12 @@ import javax.inject.Inject
class TimeDateOrTZChangeReceiver : DaggerBroadcastReceiver() { class TimeDateOrTZChangeReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
var gson: Gson val gson: Gson = Gson()
private var isDST = false private var isDST = false
init { init {
isDST = calculateDST() isDST = calculateDST()
gson = Gson()
} }
private fun calculateDST(): Boolean { private fun calculateDST(): Boolean {
@ -38,10 +37,6 @@ class TimeDateOrTZChangeReceiver : DaggerBroadcastReceiver() {
super.onReceive(context, intent) super.onReceive(context, intent)
val action = intent.action val action = intent.action
val activePump: PumpInterface = activePlugin.activePump val activePump: PumpInterface = activePlugin.activePump
if (activePump == null) {
aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Time and/or TimeZone changed. [action={}]. Pump is null, exiting.", action)
return
}
aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Date, Time and/or TimeZone changed. [action={}]", action) aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Date, Time and/or TimeZone changed. [action={}]", action)
aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Intent::{}", gson.toJson(intent)) aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Intent::{}", gson.toJson(intent))

View file

@ -2,7 +2,7 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="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">
<ScrollView <ScrollView
android:layout_width="match_parent" android:layout_width="match_parent"

View file

@ -2,7 +2,7 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistory"> tools:context=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment">
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"