Replace PodState with PodStateManager

This commit is contained in:
Bart Sopers 2020-08-08 18:06:14 +02:00
parent 337c61d500
commit b50670cceb
36 changed files with 550 additions and 979 deletions

View file

@ -3,7 +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.omnipod.comm.OmnipodCommunicationManager import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager
import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.PodHistoryActivity import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.PodHistoryActivity
import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.PodManagementActivity import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.PodManagementActivity
import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.initpod.InitActionFragment import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.initpod.InitActionFragment
@ -35,7 +35,7 @@ abstract class OmnipodModule {
// Data // Data
@ContributesAndroidInjector abstract fun omnipodUITaskProvider(): OmnipodUITask @ContributesAndroidInjector abstract fun omnipodUITaskProvider(): OmnipodUITask
@ContributesAndroidInjector abstract fun initPodRefreshAction(): InitPodRefreshAction @ContributesAndroidInjector abstract fun initPodRefreshAction(): InitPodRefreshAction
@ContributesAndroidInjector abstract fun podSessionState(): PodSessionState @ContributesAndroidInjector abstract fun podStateManager(): PodStateManager
@ContributesAndroidInjector abstract fun initPodTask() : InitPodTask @ContributesAndroidInjector abstract fun initPodTask() : InitPodTask
@ContributesAndroidInjector abstract fun initAapsPodStateManager() : AapsPodStateManager @ContributesAndroidInjector abstract fun initAapsPodStateManager() : AapsPodStateManager

View file

@ -263,20 +263,17 @@ class OmnipodFragment : DaggerFragment() {
omnipodPumpStatus.podAvailable = false omnipodPumpStatus.podAvailable = false
omnipodPumpStatus.podNumber == null omnipodPumpStatus.podNumber == null
} else if (driverState == OmnipodDriverState.Initalized_PodInitializing) { } else if (driverState == OmnipodDriverState.Initalized_PodInitializing) {
omnipod_pod_address.text = omnipodPumpStatus.podSessionState.address.toString() omnipod_pod_address.text = omnipodPumpStatus.podStateManager.address.toString()
omnipod_pod_expiry.text = "-" omnipod_pod_expiry.text = "-"
omnipod_pod_status.text = resourceHelper.gs(R.string.omnipod_pod_status_initalizing) + " (" + omnipodPumpStatus.podSessionState.getSetupProgress().name + ")" omnipod_pod_status.text = resourceHelper.gs(R.string.omnipod_pod_status_initalizing) + " (" + omnipodPumpStatus.podStateManager.getSetupProgress().name + ")"
omnipodPumpStatus.podAvailable = false omnipodPumpStatus.podAvailable = false
omnipodPumpStatus.podNumber == omnipodPumpStatus.podSessionState.address.toString() omnipodPumpStatus.podNumber == omnipodPumpStatus.podStateManager.address.toString()
} else { } else {
omnipodPumpStatus.podLotNumber = "" + omnipodPumpStatus.podSessionState.lot omnipodPumpStatus.podLotNumber = "" + omnipodPumpStatus.podStateManager.lot
omnipodPumpStatus.podAvailable = true omnipodPumpStatus.podAvailable = true
omnipod_pod_address.text = omnipodPumpStatus.podSessionState.address.toString() omnipod_pod_address.text = omnipodPumpStatus.podStateManager.address.toString()
omnipod_pod_expiry.text = omnipodPumpStatus.podSessionState.expiryDateAsString omnipod_pod_expiry.text = omnipodPumpStatus.podStateManager.expiryDateAsString
omnipodPumpStatus.podNumber = omnipodPumpStatus.podSessionState.address.toString() omnipodPumpStatus.podNumber = omnipodPumpStatus.podStateManager.address.toString()
//pumpStatus.podSessionState = checkStatusSet(pumpStatus.podSessionState,
// OmnipodUtil.getPodSessionState()) as PodSessionState?
var podDeviceState = omnipodPumpStatus.podDeviceState var podDeviceState = omnipodPumpStatus.podDeviceState
@ -317,13 +314,13 @@ class OmnipodFragment : DaggerFragment() {
} }
} }
if (SetupProgress.COMPLETED.equals(omnipodPumpStatus.podSessionState.getSetupProgress())) { if (SetupProgress.COMPLETED.equals(omnipodPumpStatus.podStateManager.getSetupProgress())) {
if(omnipodPumpStatus.podSessionState.lastDeliveryStatus != null) { if(omnipodPumpStatus.podStateManager.lastDeliveryStatus != null) {
stateText += " (last delivery status: " + omnipodPumpStatus.podSessionState.lastDeliveryStatus.name + ")" stateText += " (last delivery status: " + omnipodPumpStatus.podStateManager.lastDeliveryStatus.name + ")"
} }
} else { } else {
if(omnipodPumpStatus.podSessionState.setupProgress != null) { if(omnipodPumpStatus.podStateManager.setupProgress != null) {
stateText += " (setup progress: " + omnipodPumpStatus.podSessionState.setupProgress.name + ")" stateText += " (setup progress: " + omnipodPumpStatus.podStateManager.setupProgress.name + ")"
} }
} }

View file

@ -49,7 +49,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract;
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.data.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair;
import info.nightscout.androidaps.plugins.pump.common.defs.DeviceCommandExecutor;
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;
@ -64,7 +63,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommunication
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCustomActionType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCustomActionType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodPumpPluginInterface; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodPumpPluginInterface;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodStatusRequest; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodStatusRequest;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodDriverState; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodDriverState;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIComm; import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIComm;
@ -488,17 +487,17 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump
public boolean isSuspended() { public boolean isSuspended() {
return (omnipodUtil.getDriverState() == OmnipodDriverState.Initalized_NoPod) || return (omnipodUtil.getDriverState() == OmnipodDriverState.Initalized_NoPod) ||
(omnipodUtil.getPodSessionState() != null && omnipodUtil.getPodSessionState().isSuspended()); (omnipodUtil.getPodStateManager() != null && omnipodUtil.getPodStateManager().isSuspended());
// return (pumpStatusLocal != null && !pumpStatusLocal.podAvailable) || // return (pumpStatusLocal != null && !pumpStatusLocal.podAvailable) ||
// (OmnipodUtil.getPodSessionState() != null && OmnipodUtil.getPodSessionState().isSuspended()); // (OmnipodUtil.getPodStateManager() != null && OmnipodUtil.getPodStateManager().isSuspended());
// //
// TODO ddd // TODO ddd
// return (OmnipodUtil.getDriverState() == OmnipodDriverState.Initalized_NoPod) || // return (OmnipodUtil.getDriverState() == OmnipodDriverState.Initalized_NoPod) ||
// (OmnipodUtil.getPodSessionState() != null && OmnipodUtil.getPodSessionState().isSuspended()); // (OmnipodUtil.getPodStateManager() != null && OmnipodUtil.getPodStateManager().isSuspended());
// //
// return (pumpStatusLocal != null && !pumpStatusLocal.podAvailable) || // return (pumpStatusLocal != null && !pumpStatusLocal.podAvailable) ||
// (OmnipodUtil.getPodSessionState() != null && OmnipodUtil.getPodSessionState().isSuspended()); // (OmnipodUtil.getPodStateManager() != null && OmnipodUtil.getPodStateManager().isSuspended());
} }
@Override @Override
@ -622,18 +621,9 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump
setRefreshButtonEnabled(false); setRefreshButtonEnabled(false);
PodSessionState podSessionState = null; PodStateManager podStateManager = omnipodUtil.getPodStateManager();
if (omnipodUtil.getPodSessionState() != null) {
podSessionState = omnipodUtil.getPodSessionState();
} else {
podSessionState = omnipodUtil.loadSessionState();
}
if (podSessionState != null) {
aapsLogger.debug(LTag.PUMP, "PodSessionState (saved): " + podSessionState);
if (podStateManager != null) {
if (!isRefresh) { if (!isRefresh) {
pumpState = PumpDriverState.Initialized; pumpState = PumpDriverState.Initialized;
} }
@ -642,7 +632,7 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump
getPodPumpStatus(); getPodPumpStatus();
} else { } else {
aapsLogger.debug(LTag.PUMP, "No PodSessionState found. Pod probably not running."); aapsLogger.error(LTag.PUMP, "No PodStateManager found");
omnipodUtil.setDriverState(OmnipodDriverState.Initalized_NoPod); omnipodUtil.setDriverState(OmnipodDriverState.Initalized_NoPod);
} }

View file

@ -16,11 +16,8 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLink
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.OmnipodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.OmnipodAction;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException;
@ -43,7 +40,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.pod
import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
@ -103,13 +100,13 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
this.omnipodPumpStatus.setPumpDeviceState(pumpDeviceState); this.omnipodPumpStatus.setPumpDeviceState(pumpDeviceState);
} }
public <T extends MessageBlock> T sendCommand(Class<T> responseClass, PodState podState, MessageBlock command) { public <T extends MessageBlock> T sendCommand(Class<T> responseClass, PodStateManager podStateManager, MessageBlock command) {
return sendCommand(responseClass, podState, command, true); return sendCommand(responseClass, podStateManager, command, true);
} }
public <T extends MessageBlock> T sendCommand(Class<T> responseClass, PodState podState, MessageBlock command, boolean automaticallyResyncNone) { public <T extends MessageBlock> T sendCommand(Class<T> responseClass, PodStateManager podStateManager, MessageBlock command, boolean automaticallyResyncNone) {
OmnipodMessage message = new OmnipodMessage(podState.getAddress(), Collections.singletonList(command), podState.getMessageNumber()); OmnipodMessage message = new OmnipodMessage(podStateManager.getAddress(), Collections.singletonList(command), podStateManager.getMessageNumber());
return exchangeMessages(responseClass, podState, message, automaticallyResyncNone); return exchangeMessages(responseClass, podStateManager, message, automaticallyResyncNone);
} }
// Convenience method // Convenience method
@ -117,33 +114,33 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
return action.execute(this); return action.execute(this);
} }
public <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodState podState, OmnipodMessage message) { public <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message) {
return exchangeMessages(responseClass, podState, message, true); return exchangeMessages(responseClass, podStateManager, message, true);
} }
public <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodState podState, OmnipodMessage message, boolean automaticallyResyncNonce) { public <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message, boolean automaticallyResyncNonce) {
return exchangeMessages(responseClass, podState, message, null, null, automaticallyResyncNonce); return exchangeMessages(responseClass, podStateManager, message, null, null, automaticallyResyncNonce);
} }
public synchronized <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodState podState, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { public synchronized <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) {
return exchangeMessages(responseClass, podState, message, addressOverride, ackAddressOverride, true); return exchangeMessages(responseClass, podStateManager, message, addressOverride, ackAddressOverride, true);
} }
public synchronized <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodState podState, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) { public synchronized <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) {
aapsLogger.debug(LTag.PUMPCOMM, "Exchanging OmnipodMessage [responseClass={}, podState={}, message={}, addressOverride={}, ackAddressOverride={}, automaticallyResyncNonce={}]: {}", // aapsLogger.debug(LTag.PUMPCOMM, "Exchanging OmnipodMessage [responseClass={}, podStateManager={}, message={}, addressOverride={}, ackAddressOverride={}, automaticallyResyncNonce={}]: {}", //
responseClass.getSimpleName(), podState, message, addressOverride, ackAddressOverride, automaticallyResyncNonce, message); responseClass.getSimpleName(), podStateManager, message, addressOverride, ackAddressOverride, automaticallyResyncNonce, message);
for (int i = 0; 2 > i; i++) { for (int i = 0; 2 > i; i++) {
if (podState.hasNonceState() && message.isNonceResyncable()) { if (podStateManager.isPaired() && message.isNonceResyncable()) {
podState.advanceToNextNonce(); podStateManager.advanceToNextNonce();
} }
MessageBlock responseMessageBlock = transportMessages(podState, message, addressOverride, ackAddressOverride); MessageBlock responseMessageBlock = transportMessages(podStateManager, message, addressOverride, ackAddressOverride);
if (responseMessageBlock instanceof StatusResponse) { if (responseMessageBlock instanceof StatusResponse) {
podState.updateFromStatusResponse((StatusResponse) responseMessageBlock); podStateManager.updateFromStatusResponse((StatusResponse) responseMessageBlock);
} }
if (responseClass.isInstance(responseMessageBlock)) { if (responseClass.isInstance(responseMessageBlock)) {
@ -152,9 +149,9 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
if (responseMessageBlock.getType() == MessageBlockType.ERROR_RESPONSE) { if (responseMessageBlock.getType() == MessageBlockType.ERROR_RESPONSE) {
ErrorResponse error = (ErrorResponse) responseMessageBlock; ErrorResponse error = (ErrorResponse) responseMessageBlock;
if (error.getErrorResponseCode() == ErrorResponse.ERROR_RESPONSE_CODE_BAD_NONCE) { if (error.getErrorResponseCode() == ErrorResponse.ERROR_RESPONSE_CODE_BAD_NONCE) {
podState.resyncNonce(error.getNonceSearchKey(), message.getSentNonce(), message.getSequenceNumber()); podStateManager.resyncNonce(error.getNonceSearchKey(), message.getSentNonce(), message.getSequenceNumber());
if (automaticallyResyncNonce) { if (automaticallyResyncNonce) {
message.resyncNonce(podState.getCurrentNonce()); message.resyncNonce(podStateManager.getCurrentNonce());
} else { } else {
throw new NonceOutOfSyncException(); throw new NonceOutOfSyncException();
} }
@ -163,7 +160,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
} }
} else if (responseMessageBlock.getType() == MessageBlockType.POD_INFO_RESPONSE && ((PodInfoResponse) responseMessageBlock).getSubType() == PodInfoType.FAULT_EVENT) { } else if (responseMessageBlock.getType() == MessageBlockType.POD_INFO_RESPONSE && ((PodInfoResponse) responseMessageBlock).getSubType() == PodInfoType.FAULT_EVENT) {
PodInfoFaultEvent faultEvent = ((PodInfoResponse) responseMessageBlock).getPodInfo(); PodInfoFaultEvent faultEvent = ((PodInfoResponse) responseMessageBlock).getPodInfo();
podState.setFaultEvent(faultEvent); podStateManager.setFaultEvent(faultEvent);
throw new PodFaultException(faultEvent); throw new PodFaultException(faultEvent);
} else { } else {
throw new IllegalResponseException(responseClass.getSimpleName(), responseMessageBlock.getType()); throw new IllegalResponseException(responseClass.getSimpleName(), responseMessageBlock.getType());
@ -174,13 +171,13 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
throw new NonceResyncException(); throw new NonceResyncException();
} }
private MessageBlock transportMessages(PodState podState, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { private MessageBlock transportMessages(PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) {
int packetAddress = podState.getAddress(); int packetAddress = podStateManager.getAddress();
if (addressOverride != null) { if (addressOverride != null) {
packetAddress = addressOverride; packetAddress = addressOverride;
} }
podState.increaseMessageNumber(); podStateManager.increaseMessageNumber();
boolean firstPacket = true; boolean firstPacket = true;
byte[] encodedMessage; byte[] encodedMessage;
@ -203,7 +200,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
OmnipodPacket response = null; OmnipodPacket response = null;
while (encodedMessage.length > 0) { while (encodedMessage.length > 0) {
PacketType packetType = firstPacket ? PacketType.PDM : PacketType.CON; PacketType packetType = firstPacket ? PacketType.PDM : PacketType.CON;
OmnipodPacket packet = new OmnipodPacket(packetAddress, packetType, podState.getPacketNumber(), encodedMessage); OmnipodPacket packet = new OmnipodPacket(packetAddress, packetType, podStateManager.getPacketNumber(), encodedMessage);
byte[] encodedMessageInPacket = packet.getEncodedMessage(); byte[] encodedMessageInPacket = packet.getEncodedMessage();
// getting the data remaining to be sent // getting the data remaining to be sent
@ -212,7 +209,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
try { try {
// We actually ignore previous (ack) responses if it was not last packet to send // We actually ignore previous (ack) responses if it was not last packet to send
response = exchangePackets(podState, packet); response = exchangePackets(podStateManager, packet);
} catch (Exception ex) { } catch (Exception ex) {
OmnipodException newException; OmnipodException newException;
if (ex instanceof OmnipodException) { if (ex instanceof OmnipodException) {
@ -245,15 +242,15 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
if (receivedMessage.getAddress() != message.getAddress()) { if (receivedMessage.getAddress() != message.getAddress()) {
throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress()); throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress());
} }
if (receivedMessage.getSequenceNumber() != podState.getMessageNumber()) { if (receivedMessage.getSequenceNumber() != podStateManager.getMessageNumber()) {
throw new IllegalMessageSequenceNumberException(podState.getMessageNumber(), receivedMessage.getSequenceNumber()); throw new IllegalMessageSequenceNumberException(podStateManager.getMessageNumber(), receivedMessage.getSequenceNumber());
} }
} catch (NotEnoughDataException ex) { } catch (NotEnoughDataException ex) {
// Message is (probably) not complete yet // Message is (probably) not complete yet
OmnipodPacket ackForCon = createAckPacket(podState, packetAddress, ackAddressOverride); OmnipodPacket ackForCon = createAckPacket(podStateManager, packetAddress, ackAddressOverride);
try { try {
OmnipodPacket conPacket = exchangePackets(podState, ackForCon, 3, 40); OmnipodPacket conPacket = exchangePackets(podStateManager, ackForCon, 3, 40);
if (conPacket.getPacketType() != PacketType.CON) { if (conPacket.getPacketType() != PacketType.CON) {
throw new IllegalPacketTypeException(PacketType.CON, conPacket.getPacketType()); throw new IllegalPacketTypeException(PacketType.CON, conPacket.getPacketType());
} }
@ -267,7 +264,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
} }
} }
ackUntilQuiet(podState, packetAddress, ackAddressOverride); ackUntilQuiet(podStateManager, packetAddress, ackAddressOverride);
List<MessageBlock> messageBlocks = receivedMessage.getMessageBlocks(); List<MessageBlock> messageBlocks = receivedMessage.getMessageBlocks();
@ -281,24 +278,24 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
MessageBlock messageBlock = messageBlocks.get(0); MessageBlock messageBlock = messageBlocks.get(0);
if (messageBlock.getType() != MessageBlockType.ERROR_RESPONSE) { if (messageBlock.getType() != MessageBlockType.ERROR_RESPONSE) {
podState.increaseMessageNumber(); podStateManager.increaseMessageNumber();
} }
return messageBlock; return messageBlock;
} }
private OmnipodPacket createAckPacket(PodState podState, Integer packetAddress, Integer messageAddress) { private OmnipodPacket createAckPacket(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) {
if (packetAddress == null) { if (packetAddress == null) {
packetAddress = podState.getAddress(); packetAddress = podStateManager.getAddress();
} }
if (messageAddress == null) { if (messageAddress == null) {
messageAddress = podState.getAddress(); messageAddress = podStateManager.getAddress();
} }
return new OmnipodPacket(packetAddress, PacketType.ACK, podState.getPacketNumber(), ByteUtil.getBytesFromInt(messageAddress)); return new OmnipodPacket(packetAddress, PacketType.ACK, podStateManager.getPacketNumber(), ByteUtil.getBytesFromInt(messageAddress));
} }
private void ackUntilQuiet(PodState podState, Integer packetAddress, Integer messageAddress) { private void ackUntilQuiet(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) {
OmnipodPacket ack = createAckPacket(podState, packetAddress, messageAddress); OmnipodPacket ack = createAckPacket(podStateManager, packetAddress, messageAddress);
boolean quiet = false; boolean quiet = false;
while (!quiet) try { while (!quiet) try {
sendAndListen(ack, 300, 1, 0, 40, OmnipodPacket.class); sendAndListen(ack, 300, 1, 0, 40, OmnipodPacket.class);
@ -314,21 +311,21 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex); throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex);
} }
podState.increasePacketNumber(); podStateManager.increasePacketNumber();
} }
private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet) { private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet) {
return exchangePackets(podState, packet, 0, 333, 9000, 127); return exchangePackets(podStateManager, packet, 0, 333, 9000, 127);
} }
private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet, int repeatCount, int preambleExtensionMilliseconds) { private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int preambleExtensionMilliseconds) {
return exchangePackets(podState, packet, repeatCount, 333, 9000, preambleExtensionMilliseconds); return exchangePackets(podStateManager, packet, repeatCount, 333, 9000, preambleExtensionMilliseconds);
} }
private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet, int repeatCount, int responseTimeoutMilliseconds, int exchangeTimeoutMilliseconds, int preambleExtensionMilliseconds) { private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int responseTimeoutMilliseconds, int exchangeTimeoutMilliseconds, int preambleExtensionMilliseconds) {
long timeoutTime = System.currentTimeMillis() + exchangeTimeoutMilliseconds; long timeoutTime = System.currentTimeMillis() + exchangeTimeoutMilliseconds;
podState.increasePacketNumber(); podStateManager.increasePacketNumber();
while (System.currentTimeMillis() < timeoutTime) { while (System.currentTimeMillis() < timeoutTime) {
OmnipodPacket response = null; OmnipodPacket response = null;
@ -353,13 +350,13 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager {
continue; continue;
} }
if (response.getSequenceNumber() != podState.getPacketNumber()) { if (response.getSequenceNumber() != podStateManager.getPacketNumber()) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Packet sequence number " + response.getSequenceNumber() + " does not match " + podState.getPacketNumber()); aapsLogger.debug(LTag.PUMPBTCOMM, "Packet sequence number " + response.getSequenceNumber() + " does not match " + podStateManager.getPacketNumber());
continue; continue;
} }
// Once we have verification that the POD heard us, we can increment our counters // Once we have verification that the POD heard us, we can increment our counters
podState.increasePacketNumber(); podStateManager.increasePacketNumber();
return response; return response;
} }

View file

@ -5,7 +5,6 @@ import org.joda.time.DateTimeZone;
import org.joda.time.Duration; import org.joda.time.Duration;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.Random;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -40,8 +39,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress; import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateChangedHandler;
import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -55,49 +53,45 @@ import io.reactivex.subjects.SingleSubject;
public class OmnipodManager { public class OmnipodManager {
private static final int ACTION_VERIFICATION_TRIES = 3; private static final int ACTION_VERIFICATION_TRIES = 3;
protected final OmnipodCommunicationManager communicationService; private final OmnipodCommunicationManager communicationService;
private final PodStateChangedHandler podStateChangedHandler; private PodStateManager podStateManager;
protected PodSessionState podState;
private ActiveBolusData activeBolusData; private ActiveBolusData activeBolusData;
private final Object bolusDataMutex = new Object(); private final Object bolusDataMutex = new Object();
private AAPSLogger aapsLogger; private AAPSLogger aapsLogger;
private SP sp;
public OmnipodManager(AAPSLogger aapsLogger, public OmnipodManager(AAPSLogger aapsLogger,
SP sp, SP sp,
OmnipodCommunicationManager communicationService, OmnipodCommunicationManager communicationService,
PodSessionState podState, PodStateManager podStateManager) {
PodStateChangedHandler podStateChangedHandler) {
if (communicationService == null) { if (communicationService == null) {
throw new IllegalArgumentException("Communication service cannot be null"); throw new IllegalArgumentException("Communication service cannot be null");
} }
this.aapsLogger = aapsLogger; if (podStateManager == null) {
this.sp = sp; throw new IllegalArgumentException("Pod State Manager can not be null");
this.communicationService = communicationService;
if (podState != null) {
podState.setStateChangedHandler(podStateChangedHandler);
} }
this.podState = podState; this.aapsLogger = aapsLogger;
this.podStateChangedHandler = podStateChangedHandler; this.communicationService = communicationService;
this.podStateManager = podStateManager;
} }
public synchronized Single<SetupActionResult> pairAndPrime(int address) { public synchronized Single<SetupActionResult> pairAndPrime() {
logStartingCommandExecution("pairAndPrime"); logStartingCommandExecution("pairAndPrime");
try { try {
if (podState == null || podState.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) { if (!podStateManager.hasState() || !podStateManager.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) {
// Always send both 0x07 and 0x03 on retries // Always send both 0x07 and 0x03 on retries
podState = communicationService.executeAction( communicationService.executeAction(
new AssignAddressAction(podStateChangedHandler, address)); new AssignAddressAction(podStateManager));
communicationService.executeAction(new SetupPodAction(podState)); communicationService.executeAction(new SetupPodAction(podStateManager));
} else if (SetupProgress.PRIMING.isBefore(podState.getSetupProgress())) { } else if (SetupProgress.PRIMING.isBefore(podStateManager.getSetupProgress())) {
throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podStateManager.getSetupProgress());
} }
communicationService.executeAction(new PrimeAction(new PrimeService(), podState)); communicationService.executeAction(new PrimeAction(new PrimeService(), podStateManager));
} finally { } finally {
logCommandExecutionFinished("pairAndPrime"); logCommandExecutionFinished("pairAndPrime");
} }
@ -106,21 +100,21 @@ public class OmnipodManager {
return Single.timer(delayInSeconds, TimeUnit.SECONDS) // return Single.timer(delayInSeconds, TimeUnit.SECONDS) //
.map(o -> verifySetupAction(statusResponse -> .map(o -> verifySetupAction(statusResponse ->
PrimeAction.updatePrimingStatus(podState, statusResponse, aapsLogger), SetupProgress.PRIMING_FINISHED)) // PrimeAction.updatePrimingStatus(podStateManager, statusResponse, aapsLogger), SetupProgress.PRIMING_FINISHED)) //
.observeOn(Schedulers.io()); .observeOn(Schedulers.io());
} }
public synchronized Single<SetupActionResult> insertCannula(BasalSchedule basalSchedule) { public synchronized Single<SetupActionResult> insertCannula(BasalSchedule basalSchedule) {
if (podState == null || podState.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) { if (!podStateManager.hasState() || podStateManager.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) {
throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, podState == null ? null : podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, !podStateManager.hasState() ? null : podStateManager.getSetupProgress());
} else if (podState.getSetupProgress().isAfter(SetupProgress.CANNULA_INSERTING)) { } else if (podStateManager.getSetupProgress().isAfter(SetupProgress.CANNULA_INSERTING)) {
throw new IllegalSetupProgressException(SetupProgress.CANNULA_INSERTING, podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.CANNULA_INSERTING, podStateManager.getSetupProgress());
} }
logStartingCommandExecution("insertCannula [basalSchedule=" + basalSchedule + "]"); logStartingCommandExecution("insertCannula [basalSchedule=" + basalSchedule + "]");
try { try {
communicationService.executeAction(new InsertCannulaAction(new InsertCannulaService(), podState, basalSchedule)); communicationService.executeAction(new InsertCannulaAction(new InsertCannulaService(), podStateManager, basalSchedule));
} finally { } finally {
logCommandExecutionFinished("insertCannula"); logCommandExecutionFinished("insertCannula");
} }
@ -129,19 +123,19 @@ public class OmnipodManager {
return Single.timer(delayInSeconds, TimeUnit.SECONDS) // return Single.timer(delayInSeconds, TimeUnit.SECONDS) //
.map(o -> verifySetupAction(statusResponse -> .map(o -> verifySetupAction(statusResponse ->
InsertCannulaAction.updateCannulaInsertionStatus(podState, statusResponse, aapsLogger), SetupProgress.COMPLETED)) // InsertCannulaAction.updateCannulaInsertionStatus(podStateManager, statusResponse, aapsLogger), SetupProgress.COMPLETED)) //
.observeOn(Schedulers.io()); .observeOn(Schedulers.io());
} }
public synchronized StatusResponse getPodStatus() { public synchronized StatusResponse getPodStatus() {
if (podState == null) { if (!podStateManager.hasState()) {
throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, null); throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, null);
} }
logStartingCommandExecution("getPodStatus"); logStartingCommandExecution("getPodStatus");
try { try {
return communicationService.executeAction(new GetStatusAction(podState)); return communicationService.executeAction(new GetStatusAction(podStateManager));
} finally { } finally {
logCommandExecutionFinished("getPodStatus"); logCommandExecutionFinished("getPodStatus");
} }
@ -153,7 +147,7 @@ public class OmnipodManager {
logStartingCommandExecution("getPodInfo"); logStartingCommandExecution("getPodInfo");
try { try {
return communicationService.executeAction(new GetPodInfoAction(podState, podInfoType)); return communicationService.executeAction(new GetPodInfoAction(podStateManager, podInfoType));
} finally { } finally {
logCommandExecutionFinished("getPodInfo"); logCommandExecutionFinished("getPodInfo");
} }
@ -165,7 +159,7 @@ public class OmnipodManager {
logStartingCommandExecution("acknowledgeAlerts"); logStartingCommandExecution("acknowledgeAlerts");
try { try {
return executeAndVerify(() -> communicationService.executeAction(new AcknowledgeAlertsAction(podState, podState.getActiveAlerts()))); return executeAndVerify(() -> communicationService.executeAction(new AcknowledgeAlertsAction(podStateManager, podStateManager.getActiveAlerts())));
} finally { } finally {
logCommandExecutionFinished("acknowledgeAlerts"); logCommandExecutionFinished("acknowledgeAlerts");
} }
@ -187,8 +181,8 @@ public class OmnipodManager {
try { try {
try { try {
return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podState, schedule, return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podStateManager, schedule,
false, podState.getScheduleOffset(), acknowledgementBeep))); false, podStateManager.getScheduleOffset(), acknowledgementBeep)));
} catch (OmnipodException ex) { } catch (OmnipodException ex) {
// Treat all exceptions as uncertain failures, because all delivery has been suspended here. // Treat all exceptions as uncertain failures, because all delivery has been suspended here.
// Setting this to an uncertain failure will enable for the user to get an appropriate warning // Setting this to an uncertain failure will enable for the user to get an appropriate warning
@ -215,7 +209,7 @@ public class OmnipodManager {
try { try {
return executeAndVerify(() -> communicationService.executeAction(new SetTempBasalAction( return executeAndVerify(() -> communicationService.executeAction(new SetTempBasalAction(
podState, rate, duration, podStateManager, rate, duration,
acknowledgementBeep, completionBeep))); acknowledgementBeep, completionBeep)));
} catch (OmnipodException ex) { } catch (OmnipodException ex) {
// Treat all exceptions as uncertain failures, because all delivery has been suspended here. // Treat all exceptions as uncertain failures, because all delivery has been suspended here.
@ -238,7 +232,7 @@ public class OmnipodManager {
try { try {
return executeAndVerify(() -> { return executeAndVerify(() -> {
StatusResponse statusResponse = communicationService.executeAction(new CancelDeliveryAction(podState, deliveryTypes, acknowledgementBeep)); StatusResponse statusResponse = communicationService.executeAction(new CancelDeliveryAction(podStateManager, deliveryTypes, acknowledgementBeep));
aapsLogger.info(LTag.PUMPBTCOMM, "Status response after cancel delivery[types={}]: {}", deliveryTypes.toString(), statusResponse.toString()); aapsLogger.info(LTag.PUMPBTCOMM, "Status response after cancel delivery[types={}]: {}", deliveryTypes.toString(), statusResponse.toString());
return statusResponse; return statusResponse;
}); });
@ -258,7 +252,7 @@ public class OmnipodManager {
CommandDeliveryStatus commandDeliveryStatus = CommandDeliveryStatus.SUCCESS; CommandDeliveryStatus commandDeliveryStatus = CommandDeliveryStatus.SUCCESS;
try { try {
executeAndVerify(() -> communicationService.executeAction(new BolusAction(podState, units, acknowledgementBeep, completionBeep))); executeAndVerify(() -> communicationService.executeAction(new BolusAction(podStateManager, units, acknowledgementBeep, completionBeep)));
} catch (OmnipodException ex) { } catch (OmnipodException ex) {
if (ex.isCertainFailure()) { if (ex.isCertainFailure()) {
throw ex; throw ex;
@ -339,7 +333,7 @@ public class OmnipodManager {
synchronized (bolusDataMutex) { synchronized (bolusDataMutex) {
if (activeBolusData == null) { if (activeBolusData == null) {
throw new IllegalDeliveryStatusException(DeliveryStatus.BOLUS_IN_PROGRESS, podState.getLastDeliveryStatus()); throw new IllegalDeliveryStatusException(DeliveryStatus.BOLUS_IN_PROGRESS, podStateManager.getLastDeliveryStatus());
} }
logStartingCommandExecution("cancelBolus [acknowledgementBeep=" + acknowledgementBeep + "]"); logStartingCommandExecution("cancelBolus [acknowledgementBeep=" + acknowledgementBeep + "]");
@ -374,8 +368,8 @@ public class OmnipodManager {
logStartingCommandExecution("resumeDelivery"); logStartingCommandExecution("resumeDelivery");
try { try {
return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podState, podState.getBasalSchedule(), return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podStateManager, podStateManager.getBasalSchedule(),
false, podState.getScheduleOffset(), acknowledgementBeep))); false, podStateManager.getScheduleOffset(), acknowledgementBeep)));
} finally { } finally {
logCommandExecutionFinished("resumeDelivery"); logCommandExecutionFinished("resumeDelivery");
} }
@ -395,18 +389,18 @@ public class OmnipodManager {
throw ex; throw ex;
} }
DateTimeZone oldTimeZone = podState.getTimeZone(); DateTimeZone oldTimeZone = podStateManager.getTimeZone();
try { try {
// Joda seems to cache the default time zone, so we use the JVM's // Joda seems to cache the default time zone, so we use the JVM's
DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault())); DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault()));
podState.setTimeZone(DateTimeZone.getDefault()); podStateManager.setTimeZone(DateTimeZone.getDefault());
setBasalSchedule(podState.getBasalSchedule(), acknowledgementBeeps); setBasalSchedule(podStateManager.getBasalSchedule(), acknowledgementBeeps);
} catch (OmnipodException ex) { } catch (OmnipodException ex) {
// Treat all exceptions as uncertain failures, because all delivery has been suspended here. // Treat all exceptions as uncertain failures, because all delivery has been suspended here.
// Setting this to an uncertain failure will enable for the user to get an appropriate warning // Setting this to an uncertain failure will enable for the user to get an appropriate warning
podState.setTimeZone(oldTimeZone); podStateManager.setTimeZone(oldTimeZone);
ex.setCertainFailure(false); ex.setCertainFailure(false);
throw ex; throw ex;
} finally { } finally {
@ -415,7 +409,7 @@ public class OmnipodManager {
} }
public synchronized void deactivatePod() { public synchronized void deactivatePod() {
if (podState == null) { if (!podStateManager.isPaired()) {
throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, null); throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, null);
} }
@ -424,7 +418,7 @@ public class OmnipodManager {
// Try to get pulse log for diagnostics // Try to get pulse log for diagnostics
// FIXME replace by storing to file // FIXME replace by storing to file
try { try {
PodInfoResponse podInfoResponse = communicationService.executeAction(new GetPodInfoAction(podState, PodInfoType.RECENT_PULSE_LOG)); PodInfoResponse podInfoResponse = communicationService.executeAction(new GetPodInfoAction(podStateManager, PodInfoType.RECENT_PULSE_LOG));
PodInfoRecentPulseLog pulseLogInfo = podInfoResponse.getPodInfo(); PodInfoRecentPulseLog pulseLogInfo = podInfoResponse.getPodInfo();
aapsLogger.info(LTag.PUMPBTCOMM, "Retrieved pulse log from the pod: {}", pulseLogInfo.toString()); aapsLogger.info(LTag.PUMPBTCOMM, "Retrieved pulse log from the pod: {}", pulseLogInfo.toString());
} catch (Exception ex) { } catch (Exception ex) {
@ -433,20 +427,14 @@ public class OmnipodManager {
try { try {
// Always send acknowledgement beeps here. Matches the PDM's behavior // Always send acknowledgement beeps here. Matches the PDM's behavior
communicationService.executeAction(new DeactivatePodAction(podState, true)); communicationService.executeAction(new DeactivatePodAction(podStateManager, true));
} catch (PodFaultException ex) { } catch (PodFaultException ex) {
aapsLogger.info(LTag.PUMPBTCOMM, "Ignoring PodFaultException in deactivatePod", ex); aapsLogger.info(LTag.PUMPBTCOMM, "Ignoring PodFaultException in deactivatePod", ex);
} finally { } finally {
logCommandExecutionFinished("deactivatePod"); logCommandExecutionFinished("deactivatePod");
} }
resetPodState(false); podStateManager.removeState();
}
public void resetPodState(boolean forcedByUser) {
aapsLogger.warn(LTag.PUMPBTCOMM, "resetPodState has been called. forcedByUser={}", forcedByUser);
podState = null;
sp.remove(OmnipodConst.Prefs.PodState);
} }
public OmnipodCommunicationManager getCommunicationService() { public OmnipodCommunicationManager getCommunicationService() {
@ -454,11 +442,11 @@ public class OmnipodManager {
} }
public DateTime getTime() { public DateTime getTime() {
return podState.getTime(); return podStateManager.getTime();
} }
public boolean isReadyForDelivery() { public boolean isReadyForDelivery() {
return podState != null && podState.getSetupProgress() == SetupProgress.COMPLETED; return podStateManager.isPaired() && podStateManager.getSetupProgress() == SetupProgress.COMPLETED;
} }
public boolean hasActiveBolus() { public boolean hasActiveBolus() {
@ -467,13 +455,12 @@ public class OmnipodManager {
} }
} }
// FIXME this is dirty, we should not expose the original pod state public PodStateManager getPodStateManager() {
public PodSessionState getPodState() { return this.podStateManager;
return this.podState;
} }
public String getPodStateAsString() { public String getPodStateAsString() {
return podState == null ? "null" : podState.toString(); return podStateManager.hasState() ? podStateManager.toString() : "null";
} }
// Only works for commands with nonce resyncable message blocks // Only works for commands with nonce resyncable message blocks
@ -489,8 +476,8 @@ public class OmnipodManager {
try { try {
logStartingCommandExecution("verifyCommand"); logStartingCommandExecution("verifyCommand");
StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podState, StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podStateManager,
new CancelDeliveryCommand(podState.getCurrentNonce(), BeepType.NO_BEEP, DeliveryType.NONE), false); new CancelDeliveryCommand(podStateManager.getCurrentNonce(), BeepType.NO_BEEP, DeliveryType.NONE), false);
aapsLogger.info(LTag.PUMPBTCOMM, "Command status resolved to SUCCESS. Status response after cancelDelivery[types=DeliveryType.NONE]: {}", statusResponse); aapsLogger.info(LTag.PUMPBTCOMM, "Command status resolved to SUCCESS. Status response after cancelDelivery[types=DeliveryType.NONE]: {}", statusResponse);
return statusResponse; return statusResponse;
@ -517,7 +504,7 @@ public class OmnipodManager {
private void assertReadyForDelivery() { private void assertReadyForDelivery() {
if (!isReadyForDelivery()) { if (!isReadyForDelivery()) {
throw new IllegalSetupProgressException(SetupProgress.COMPLETED, podState == null ? null : podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.COMPLETED, !podStateManager.hasState() ? null : podStateManager.getSetupProgress());
} }
} }
@ -525,15 +512,15 @@ public class OmnipodManager {
SetupActionResult result = null; SetupActionResult result = null;
for (int i = 0; ACTION_VERIFICATION_TRIES > i; i++) { for (int i = 0; ACTION_VERIFICATION_TRIES > i; i++) {
try { try {
StatusResponse delayedStatusResponse = communicationService.executeAction(new GetStatusAction(podState)); StatusResponse delayedStatusResponse = communicationService.executeAction(new GetStatusAction(podStateManager));
setupActionResponseHandler.accept(delayedStatusResponse); setupActionResponseHandler.accept(delayedStatusResponse);
if (podState.getSetupProgress().equals(expectedSetupProgress)) { if (podStateManager.getSetupProgress().equals(expectedSetupProgress)) {
result = new SetupActionResult(SetupActionResult.ResultType.SUCCESS); result = new SetupActionResult(SetupActionResult.ResultType.SUCCESS);
break; break;
} else { } else {
result = new SetupActionResult(SetupActionResult.ResultType.FAILURE) // result = new SetupActionResult(SetupActionResult.ResultType.FAILURE) //
.setupProgress(podState.getSetupProgress()); .setupProgress(podStateManager.getSetupProgress());
break; break;
} }
} catch (Exception ex) { } catch (Exception ex) {
@ -564,15 +551,6 @@ public class OmnipodManager {
return ex instanceof OmnipodException && ((OmnipodException) ex).isCertainFailure(); return ex instanceof OmnipodException && ((OmnipodException) ex).isCertainFailure();
} }
public static int generateRandomAddress() {
// Create random address with 20 bits to match PDM, could easily use 24 bits instead
return 0x1f000000 | (new Random().nextInt() & 0x000fffff);
}
public static boolean isValidAddress(int address) {
return (0x1f000000 | (address & 0x000fffff)) == address;
}
public static class BolusCommandResult { public static class BolusCommandResult {
private final CommandDeliveryStatus commandDeliveryStatus; private final CommandDeliveryStatus commandDeliveryStatus;
private final SingleSubject<BolusDeliveryResult> deliveryResultSubject; private final SingleSubject<BolusDeliveryResult> deliveryResultSubject;

View file

@ -3,37 +3,37 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action;
import java.util.Collections; import java.util.Collections;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.AcknowledgeAlertsCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.AcknowledgeAlertsCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSet;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class AcknowledgeAlertsAction implements OmnipodAction<StatusResponse> { public class AcknowledgeAlertsAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final AlertSet alerts; private final AlertSet alerts;
public AcknowledgeAlertsAction(PodSessionState podState, AlertSet alerts) { public AcknowledgeAlertsAction(PodStateManager podStateManager, AlertSet alerts) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (alerts == null) { if (alerts == null) {
throw new ActionInitializationException("Alert set can not be null"); throw new ActionInitializationException("Alert set can not be null");
} else if (alerts.size() == 0) { } else if (alerts.size() == 0) {
throw new ActionInitializationException("Alert set can not be empty"); throw new ActionInitializationException("Alert set can not be empty");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.alerts = alerts; this.alerts = alerts;
} }
public AcknowledgeAlertsAction(PodSessionState podState, AlertSlot alertSlot) { public AcknowledgeAlertsAction(PodStateManager podStateManager, AlertSlot alertSlot) {
this(podState, new AlertSet(Collections.singletonList(alertSlot))); this(podStateManager, new AlertSet(Collections.singletonList(alertSlot)));
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
return communicationService.sendCommand(StatusResponse.class, podState, return communicationService.sendCommand(StatusResponse.class, podStateManager,
new AcknowledgeAlertsCommand(podState.getCurrentNonce(), alerts)); new AcknowledgeAlertsCommand(podStateManager.getCurrentNonce(), alerts));
} }
} }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import java.util.Collections; import java.util.Collections;
import java.util.Random;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException;
@ -10,45 +11,52 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalVer
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.AssignAddressCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.AssignAddressCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.VersionResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.VersionResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSetupState;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateChangedHandler;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
public class AssignAddressAction implements OmnipodAction<PodSessionState> { public class AssignAddressAction implements OmnipodAction<VersionResponse> {
private final int address; private final PodStateManager podStateManager;
private final PodStateChangedHandler podStateChangedHandler;
public AssignAddressAction(PodStateChangedHandler podStateChangedHandler, int address) { public AssignAddressAction(PodStateManager podStateManager) {
this.address = address; if (podStateManager == null) {
this.podStateChangedHandler = podStateChangedHandler; throw new IllegalArgumentException("podStateManager can not be null");
}
this.podStateManager = podStateManager;
} }
@Override @Override
public PodSessionState execute(OmnipodCommunicationManager communicationService) { public VersionResponse execute(OmnipodCommunicationManager communicationService) {
PodSetupState setupState = new PodSetupState(address, 0x00, 0x00); if (!podStateManager.hasState()) {
podStateManager.initState(generateRandomAddress());
}
if (podStateManager.isPaired()) {
throw new IllegalStateException("podStateManager already has a paired Pod");
}
AssignAddressCommand assignAddress = new AssignAddressCommand(setupState.getAddress()); AssignAddressCommand assignAddress = new AssignAddressCommand(podStateManager.getAddress());
OmnipodMessage assignAddressMessage = new OmnipodMessage(OmnipodConst.DEFAULT_ADDRESS, OmnipodMessage assignAddressMessage = new OmnipodMessage(OmnipodConst.DEFAULT_ADDRESS,
Collections.singletonList(assignAddress), setupState.getMessageNumber()); Collections.singletonList(assignAddress), podStateManager.getMessageNumber());
VersionResponse assignAddressResponse = communicationService.exchangeMessages(VersionResponse.class, setupState, assignAddressMessage, VersionResponse assignAddressResponse = communicationService.exchangeMessages(VersionResponse.class, podStateManager, assignAddressMessage,
OmnipodConst.DEFAULT_ADDRESS, setupState.getAddress()); OmnipodConst.DEFAULT_ADDRESS, podStateManager.getAddress());
if (!assignAddressResponse.isAssignAddressVersionResponse()) { if (!assignAddressResponse.isAssignAddressVersionResponse()) {
throw new IllegalVersionResponseTypeException("assignAddress", "setupPod"); throw new IllegalVersionResponseTypeException("assignAddress", "setupPod");
} }
if (assignAddressResponse.getAddress() != address) { if (assignAddressResponse.getAddress() != podStateManager.getAddress()) {
throw new IllegalMessageAddressException(address, assignAddressResponse.getAddress()); throw new IllegalMessageAddressException(podStateManager.getAddress(), assignAddressResponse.getAddress());
} }
DateTimeZone timeZone = DateTimeZone.getDefault(); podStateManager.setPairingParameters(assignAddressResponse.getLot(), assignAddressResponse.getTid(), //
assignAddressResponse.getPiVersion(), assignAddressResponse.getPmVersion(), DateTimeZone.getDefault());
podStateManager.setMessageNumber(0x00);
PodSessionState podState = new PodSessionState(timeZone, address, assignAddressResponse.getPiVersion(), return assignAddressResponse;
assignAddressResponse.getPmVersion(), assignAddressResponse.getLot(), assignAddressResponse.getTid(), }
setupState.getPacketNumber(), 0x00, communicationService.injector); // At this point, for an unknown reason, the pod starts counting messages from 0 again
podState.setStateChangedHandler(podStateChangedHandler);
return podState; private static int generateRandomAddress() {
// Create random address with 20 bits to match PDM, could easily use 24 bits instead
return 0x1f000000 | (new Random().nextInt() & 0x000fffff);
} }
} }

View file

@ -5,49 +5,49 @@ import org.joda.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.BolusExtraCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.BolusExtraCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetInsulinScheduleCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetInsulinScheduleCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BolusDeliverySchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BolusDeliverySchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class BolusAction implements OmnipodAction<StatusResponse> { public class BolusAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final double units; private final double units;
private final Duration timeBetweenPulses; private final Duration timeBetweenPulses;
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
private final boolean completionBeep; private final boolean completionBeep;
public BolusAction(PodSessionState podState, double units, Duration timeBetweenPulses, public BolusAction(PodStateManager podStateManager, double units, Duration timeBetweenPulses,
boolean acknowledgementBeep, boolean completionBeep) { boolean acknowledgementBeep, boolean completionBeep) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (timeBetweenPulses == null) { if (timeBetweenPulses == null) {
throw new ActionInitializationException("Time between pulses cannot be null"); throw new ActionInitializationException("Time between pulses cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.units = units; this.units = units;
this.timeBetweenPulses = timeBetweenPulses; this.timeBetweenPulses = timeBetweenPulses;
this.acknowledgementBeep = acknowledgementBeep; this.acknowledgementBeep = acknowledgementBeep;
this.completionBeep = completionBeep; this.completionBeep = completionBeep;
} }
public BolusAction(PodSessionState podState, double units, boolean acknowledgementBeep, boolean completionBeep) { public BolusAction(PodStateManager podStateManager, double units, boolean acknowledgementBeep, boolean completionBeep) {
this(podState, units, Duration.standardSeconds(2), acknowledgementBeep, completionBeep); this(podStateManager, units, Duration.standardSeconds(2), acknowledgementBeep, completionBeep);
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
BolusDeliverySchedule bolusDeliverySchedule = new BolusDeliverySchedule(units, timeBetweenPulses); BolusDeliverySchedule bolusDeliverySchedule = new BolusDeliverySchedule(units, timeBetweenPulses);
SetInsulinScheduleCommand setInsulinScheduleCommand = new SetInsulinScheduleCommand( SetInsulinScheduleCommand setInsulinScheduleCommand = new SetInsulinScheduleCommand(
podState.getCurrentNonce(), bolusDeliverySchedule); podStateManager.getCurrentNonce(), bolusDeliverySchedule);
BolusExtraCommand bolusExtraCommand = new BolusExtraCommand(units, timeBetweenPulses, BolusExtraCommand bolusExtraCommand = new BolusExtraCommand(units, timeBetweenPulses,
acknowledgementBeep, completionBeep); acknowledgementBeep, completionBeep);
OmnipodMessage primeBolusMessage = new OmnipodMessage(podState.getAddress(), OmnipodMessage primeBolusMessage = new OmnipodMessage(podStateManager.getAddress(),
Arrays.asList(setInsulinScheduleCommand, bolusExtraCommand), podState.getMessageNumber()); Arrays.asList(setInsulinScheduleCommand, bolusExtraCommand), podStateManager.getMessageNumber());
return communicationService.exchangeMessages(StatusResponse.class, podState, primeBolusMessage); return communicationService.exchangeMessages(StatusResponse.class, podStateManager, primeBolusMessage);
} }
} }

View file

@ -5,29 +5,29 @@ import java.util.EnumSet;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.CancelDeliveryCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.CancelDeliveryCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.BeepType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.BeepType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class CancelDeliveryAction implements OmnipodAction<StatusResponse> { public class CancelDeliveryAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final EnumSet<DeliveryType> deliveryTypes; private final EnumSet<DeliveryType> deliveryTypes;
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
public CancelDeliveryAction(PodSessionState podState, EnumSet<DeliveryType> deliveryTypes, public CancelDeliveryAction(PodStateManager podStateManager, EnumSet<DeliveryType> deliveryTypes,
boolean acknowledgementBeep) { boolean acknowledgementBeep) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (deliveryTypes == null) { if (deliveryTypes == null) {
throw new ActionInitializationException("Delivery types cannot be null"); throw new ActionInitializationException("Delivery types cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.deliveryTypes = deliveryTypes; this.deliveryTypes = deliveryTypes;
this.acknowledgementBeep = acknowledgementBeep; this.acknowledgementBeep = acknowledgementBeep;
} }
@ -43,14 +43,14 @@ public class CancelDeliveryAction implements OmnipodAction<StatusResponse> {
EnumSet<DeliveryType> deliveryTypeWithBeep = EnumSet.of(deliveryTypeList.remove(deliveryTypeList.size() - 1)); EnumSet<DeliveryType> deliveryTypeWithBeep = EnumSet.of(deliveryTypeList.remove(deliveryTypeList.size() - 1));
EnumSet<DeliveryType> deliveryTypesWithoutBeep = EnumSet.copyOf(deliveryTypeList); EnumSet<DeliveryType> deliveryTypesWithoutBeep = EnumSet.copyOf(deliveryTypeList);
messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), BeepType.NO_BEEP, deliveryTypesWithoutBeep)); messageBlocks.add(new CancelDeliveryCommand(podStateManager.getCurrentNonce(), BeepType.NO_BEEP, deliveryTypesWithoutBeep));
messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), BeepType.BEEP, deliveryTypeWithBeep)); messageBlocks.add(new CancelDeliveryCommand(podStateManager.getCurrentNonce(), BeepType.BEEP, deliveryTypeWithBeep));
} else { } else {
messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), messageBlocks.add(new CancelDeliveryCommand(podStateManager.getCurrentNonce(),
acknowledgementBeep && deliveryTypes.size() == 1 ? BeepType.BEEP : BeepType.NO_BEEP, deliveryTypes)); acknowledgementBeep && deliveryTypes.size() == 1 ? BeepType.BEEP : BeepType.NO_BEEP, deliveryTypes));
} }
return communicationService.exchangeMessages(StatusResponse.class, podState, return communicationService.exchangeMessages(StatusResponse.class, podStateManager,
new OmnipodMessage(podState.getAddress(), messageBlocks, podState.getMessageNumber())); new OmnipodMessage(podStateManager.getAddress(), messageBlocks, podStateManager.getMessageNumber()));
} }
} }

View file

@ -3,33 +3,33 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.ConfigureAlertsCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.ConfigureAlertsCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfiguration; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfiguration;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class ConfigureAlertsAction implements OmnipodAction<StatusResponse> { public class ConfigureAlertsAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final List<AlertConfiguration> alertConfigurations; private final List<AlertConfiguration> alertConfigurations;
public ConfigureAlertsAction(PodSessionState podState, List<AlertConfiguration> alertConfigurations) { public ConfigureAlertsAction(PodStateManager podStateManager, List<AlertConfiguration> alertConfigurations) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (alertConfigurations == null) { if (alertConfigurations == null) {
throw new ActionInitializationException("Alert configurations cannot be null"); throw new ActionInitializationException("Alert configurations cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.alertConfigurations = alertConfigurations; this.alertConfigurations = alertConfigurations;
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
ConfigureAlertsCommand configureAlertsCommand = new ConfigureAlertsCommand(podState.getCurrentNonce(), alertConfigurations); ConfigureAlertsCommand configureAlertsCommand = new ConfigureAlertsCommand(podStateManager.getCurrentNonce(), alertConfigurations);
StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podState, configureAlertsCommand); StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podStateManager, configureAlertsCommand);
for (AlertConfiguration alertConfiguration : alertConfigurations) { for (AlertConfiguration alertConfiguration : alertConfigurations) {
podState.putConfiguredAlert(alertConfiguration.getAlertSlot(), alertConfiguration.getAlertType()); podStateManager.putConfiguredAlert(alertConfiguration.getAlertSlot(), alertConfiguration.getAlertType());
} }
return statusResponse; return statusResponse;
} }

View file

@ -3,36 +3,36 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action;
import java.util.EnumSet; import java.util.EnumSet;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.PodFaultException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.DeactivatePodCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.DeactivatePodCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.PodFaultException;
public class DeactivatePodAction implements OmnipodAction<StatusResponse> { public class DeactivatePodAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
public DeactivatePodAction(PodSessionState podState, boolean acknowledgementBeep) { public DeactivatePodAction(PodStateManager podStateManager, boolean acknowledgementBeep) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.acknowledgementBeep = acknowledgementBeep; this.acknowledgementBeep = acknowledgementBeep;
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
if (!podState.isSuspended() && !podState.hasFaultEvent()) { if (!podStateManager.isSuspended() && !podStateManager.hasFaultEvent()) {
try { try {
communicationService.executeAction(new CancelDeliveryAction(podState, communicationService.executeAction(new CancelDeliveryAction(podStateManager,
EnumSet.allOf(DeliveryType.class), acknowledgementBeep)); EnumSet.allOf(DeliveryType.class), acknowledgementBeep));
} catch (PodFaultException ex) { } catch (PodFaultException ex) {
// Ignore // Ignore
} }
} }
return communicationService.sendCommand(StatusResponse.class, podState, new DeactivatePodCommand(podState.getCurrentNonce())); return communicationService.sendCommand(StatusResponse.class, podStateManager, new DeactivatePodCommand(podStateManager.getCurrentNonce()));
} }
} }

View file

@ -1,29 +1,29 @@
package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; package info.nightscout.androidaps.plugins.pump.omnipod.comm.action;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.GetStatusCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.GetStatusCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class GetPodInfoAction implements OmnipodAction<PodInfoResponse> { public class GetPodInfoAction implements OmnipodAction<PodInfoResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final PodInfoType podInfoType; private final PodInfoType podInfoType;
public GetPodInfoAction(PodSessionState podState, PodInfoType podInfoType) { public GetPodInfoAction(PodStateManager podStateManager, PodInfoType podInfoType) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (podInfoType == null) { if (podInfoType == null) {
throw new ActionInitializationException("Pod info type cannot be null"); throw new ActionInitializationException("Pod info type cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.podInfoType = podInfoType; this.podInfoType = podInfoType;
} }
@Override @Override
public PodInfoResponse execute(OmnipodCommunicationManager communicationService) { public PodInfoResponse execute(OmnipodCommunicationManager communicationService) {
return communicationService.sendCommand(PodInfoResponse.class, podState, new GetStatusCommand(podInfoType)); return communicationService.sendCommand(PodInfoResponse.class, podStateManager, new GetStatusCommand(podInfoType));
} }
} }

View file

@ -4,21 +4,21 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunication
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.GetStatusCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.GetStatusCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
public class GetStatusAction implements OmnipodAction<StatusResponse> { public class GetStatusAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
public GetStatusAction(PodSessionState podState) { public GetStatusAction(PodStateManager podState) {
if (podState == null) { if (podState == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
this.podState = podState; this.podStateManager = podState;
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
return communicationService.sendCommand(StatusResponse.class, podState, new GetStatusCommand(PodInfoType.NORMAL)); return communicationService.sendCommand(StatusResponse.class, podStateManager, new GetStatusCommand(PodInfoType.NORMAL));
} }
} }

View file

@ -9,63 +9,63 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalSet
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress; import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
public class InsertCannulaAction implements OmnipodAction<StatusResponse> { public class InsertCannulaAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final InsertCannulaService service; private final InsertCannulaService service;
private final BasalSchedule initialBasalSchedule; private final BasalSchedule initialBasalSchedule;
public InsertCannulaAction(InsertCannulaService insertCannulaService, PodSessionState podState, BasalSchedule initialBasalSchedule) { public InsertCannulaAction(InsertCannulaService insertCannulaService, PodStateManager podStateManager, BasalSchedule initialBasalSchedule) {
if (insertCannulaService == null) { if (insertCannulaService == null) {
throw new ActionInitializationException("Insert cannula service cannot be null"); throw new ActionInitializationException("Insert cannula service cannot be null");
} }
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (initialBasalSchedule == null) { if (initialBasalSchedule == null) {
throw new ActionInitializationException("Initial basal schedule cannot be null"); throw new ActionInitializationException("Initial basal schedule cannot be null");
} }
this.service = insertCannulaService; this.service = insertCannulaService;
this.podState = podState; this.podStateManager = podStateManager;
this.initialBasalSchedule = initialBasalSchedule; this.initialBasalSchedule = initialBasalSchedule;
} }
public static void updateCannulaInsertionStatus(PodSessionState podState, StatusResponse statusResponse, AAPSLogger aapsLogger) { public static void updateCannulaInsertionStatus(PodStateManager podStateManager, StatusResponse statusResponse, AAPSLogger aapsLogger) {
if (podState.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING) && if (podStateManager.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING) &&
statusResponse.getPodProgressStatus().isReadyForDelivery()) { statusResponse.getPodProgressStatus().isReadyForDelivery()) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from CANNULA_INSERTING to COMPLETED"); aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from CANNULA_INSERTING to COMPLETED");
podState.setSetupProgress(SetupProgress.COMPLETED); podStateManager.setSetupProgress(SetupProgress.COMPLETED);
} }
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
if (podState.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) {
throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, podStateManager.getSetupProgress());
} }
if (podState.getSetupProgress().isBefore(SetupProgress.INITIAL_BASAL_SCHEDULE_SET)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.INITIAL_BASAL_SCHEDULE_SET)) {
service.programInitialBasalSchedule(communicationService, podState, initialBasalSchedule); service.programInitialBasalSchedule(communicationService, podStateManager, initialBasalSchedule);
podState.setSetupProgress(SetupProgress.INITIAL_BASAL_SCHEDULE_SET); podStateManager.setSetupProgress(SetupProgress.INITIAL_BASAL_SCHEDULE_SET);
} }
if (podState.getSetupProgress().isBefore(SetupProgress.STARTING_INSERT_CANNULA)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.STARTING_INSERT_CANNULA)) {
service.executeExpirationRemindersAlertCommand(communicationService, podState); service.executeExpirationRemindersAlertCommand(communicationService, podStateManager);
podState.setSetupProgress(SetupProgress.STARTING_INSERT_CANNULA); podStateManager.setSetupProgress(SetupProgress.STARTING_INSERT_CANNULA);
} }
if (podState.getSetupProgress().isBefore(SetupProgress.CANNULA_INSERTING)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.CANNULA_INSERTING)) {
StatusResponse statusResponse = service.executeInsertionBolusCommand(communicationService, podState); StatusResponse statusResponse = service.executeInsertionBolusCommand(communicationService, podStateManager);
podState.setSetupProgress(SetupProgress.CANNULA_INSERTING); podStateManager.setSetupProgress(SetupProgress.CANNULA_INSERTING);
return statusResponse; return statusResponse;
} else if (podState.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING)) { } else if (podStateManager.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING)) {
// Check status // Check status
StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podState)); StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podStateManager));
updateCannulaInsertionStatus(podState, statusResponse, communicationService.aapsLogger); updateCannulaInsertionStatus(podStateManager, statusResponse, communicationService.aapsLogger);
return statusResponse; return statusResponse;
} else { } else {
throw new IllegalSetupProgressException(null, podState.getSetupProgress()); throw new IllegalSetupProgressException(null, podStateManager.getSetupProgress());
} }
} }
} }

View file

@ -9,53 +9,53 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalSet
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress; import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
public class PrimeAction implements OmnipodAction<StatusResponse> { public class PrimeAction implements OmnipodAction<StatusResponse> {
private final PrimeService service; private final PrimeService service;
private final PodSessionState podState; private final PodStateManager podStateManager;
public PrimeAction(PrimeService primeService, PodSessionState podState) { public PrimeAction(PrimeService primeService, PodStateManager podStateManager) {
if (primeService == null) { if (primeService == null) {
throw new ActionInitializationException("Prime service cannot be null"); throw new ActionInitializationException("Prime service cannot be null");
} }
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
this.service = primeService; this.service = primeService;
this.podState = podState; this.podStateManager = podStateManager;
} }
public static void updatePrimingStatus(PodSessionState podState, StatusResponse statusResponse, AAPSLogger aapsLogger) { public static void updatePrimingStatus(PodStateManager podStateManager, StatusResponse statusResponse, AAPSLogger aapsLogger) {
if (podState.getSetupProgress().equals(SetupProgress.PRIMING) && statusResponse.getPodProgressStatus().equals(PodProgressStatus.PRIMING_COMPLETED)) { if (podStateManager.getSetupProgress().equals(SetupProgress.PRIMING) && statusResponse.getPodProgressStatus().equals(PodProgressStatus.PRIMING_COMPLETED)) {
aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from PRIMING to PRIMING_FINISHED"); aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from PRIMING to PRIMING_FINISHED");
podState.setSetupProgress(SetupProgress.PRIMING_FINISHED); podStateManager.setSetupProgress(SetupProgress.PRIMING_FINISHED);
} }
} }
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
if (podState.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) {
throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podStateManager.getSetupProgress());
} }
if (podState.getSetupProgress().isBefore(SetupProgress.STARTING_PRIME)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.STARTING_PRIME)) {
service.executeDisableTab5Sub16FaultConfigCommand(communicationService, podState); service.executeDisableTab5Sub16FaultConfigCommand(communicationService, podStateManager);
service.executeFinishSetupReminderAlertCommand(communicationService, podState); service.executeFinishSetupReminderAlertCommand(communicationService, podStateManager);
podState.setSetupProgress(SetupProgress.STARTING_PRIME); podStateManager.setSetupProgress(SetupProgress.STARTING_PRIME);
} }
if (podState.getSetupProgress().isBefore(SetupProgress.PRIMING)) { if (podStateManager.getSetupProgress().isBefore(SetupProgress.PRIMING)) {
StatusResponse statusResponse = service.executePrimeBolusCommand(communicationService, podState); StatusResponse statusResponse = service.executePrimeBolusCommand(communicationService, podStateManager);
podState.setSetupProgress(SetupProgress.PRIMING); podStateManager.setSetupProgress(SetupProgress.PRIMING);
return statusResponse; return statusResponse;
} else if (podState.getSetupProgress().equals(SetupProgress.PRIMING)) { } else if (podStateManager.getSetupProgress().equals(SetupProgress.PRIMING)) {
// Check status // Check status
StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podState)); StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podStateManager));
updatePrimingStatus(podState, statusResponse, communicationService.aapsLogger); updatePrimingStatus(podStateManager, statusResponse, communicationService.aapsLogger);
return statusResponse; return statusResponse;
} else { } else {
throw new IllegalSetupProgressException(null, podState.getSetupProgress()); throw new IllegalSetupProgressException(null, podStateManager.getSetupProgress());
} }
} }
} }

View file

@ -5,25 +5,25 @@ import org.joda.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.BasalScheduleExtraCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.BasalScheduleExtraCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetInsulinScheduleCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetInsulinScheduleCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class SetBasalScheduleAction implements OmnipodAction<StatusResponse> { public class SetBasalScheduleAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final BasalSchedule basalSchedule; private final BasalSchedule basalSchedule;
private final boolean confidenceReminder; private final boolean confidenceReminder;
private final Duration scheduleOffset; private final Duration scheduleOffset;
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
public SetBasalScheduleAction(PodSessionState podState, BasalSchedule basalSchedule, public SetBasalScheduleAction(PodStateManager podStateManager, BasalSchedule basalSchedule,
boolean confidenceReminder, Duration scheduleOffset, boolean acknowledgementBeep) { boolean confidenceReminder, Duration scheduleOffset, boolean acknowledgementBeep) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (basalSchedule == null) { if (basalSchedule == null) {
throw new ActionInitializationException("Basal schedule cannot be null"); throw new ActionInitializationException("Basal schedule cannot be null");
@ -31,7 +31,7 @@ public class SetBasalScheduleAction implements OmnipodAction<StatusResponse> {
if (scheduleOffset == null) { if (scheduleOffset == null) {
throw new ActionInitializationException("Schedule offset cannot be null"); throw new ActionInitializationException("Schedule offset cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.basalSchedule = basalSchedule; this.basalSchedule = basalSchedule;
this.confidenceReminder = confidenceReminder; this.confidenceReminder = confidenceReminder;
this.scheduleOffset = scheduleOffset; this.scheduleOffset = scheduleOffset;
@ -40,14 +40,14 @@ public class SetBasalScheduleAction implements OmnipodAction<StatusResponse> {
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
SetInsulinScheduleCommand setBasal = new SetInsulinScheduleCommand(podState.getCurrentNonce(), basalSchedule, scheduleOffset); SetInsulinScheduleCommand setBasal = new SetInsulinScheduleCommand(podStateManager.getCurrentNonce(), basalSchedule, scheduleOffset);
BasalScheduleExtraCommand extraCommand = new BasalScheduleExtraCommand(basalSchedule, scheduleOffset, BasalScheduleExtraCommand extraCommand = new BasalScheduleExtraCommand(basalSchedule, scheduleOffset,
acknowledgementBeep, confidenceReminder, Duration.ZERO); acknowledgementBeep, confidenceReminder, Duration.ZERO);
OmnipodMessage basalMessage = new OmnipodMessage(podState.getAddress(), Arrays.asList(setBasal, extraCommand), OmnipodMessage basalMessage = new OmnipodMessage(podStateManager.getAddress(), Arrays.asList(setBasal, extraCommand),
podState.getMessageNumber()); podStateManager.getMessageNumber());
StatusResponse statusResponse = communicationService.exchangeMessages(StatusResponse.class, podState, basalMessage); StatusResponse statusResponse = communicationService.exchangeMessages(StatusResponse.class, podStateManager, basalMessage);
podState.setBasalSchedule(basalSchedule); podStateManager.setBasalSchedule(basalSchedule);
return statusResponse; return statusResponse;
} }
} }

View file

@ -6,30 +6,30 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetInsulinScheduleCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetInsulinScheduleCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.TempBasalExtraCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.TempBasalExtraCommand;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException;
public class SetTempBasalAction implements OmnipodAction<StatusResponse> { public class SetTempBasalAction implements OmnipodAction<StatusResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
private final double rate; private final double rate;
private final Duration duration; private final Duration duration;
private final boolean acknowledgementBeep; private final boolean acknowledgementBeep;
private final boolean completionBeep; private final boolean completionBeep;
public SetTempBasalAction(PodSessionState podState, double rate, Duration duration, public SetTempBasalAction(PodStateManager podStateManager, double rate, Duration duration,
boolean acknowledgementBeep, boolean completionBeep) { boolean acknowledgementBeep, boolean completionBeep) {
if (podState == null) { if (podStateManager == null) {
throw new ActionInitializationException("Pod state cannot be null"); throw new ActionInitializationException("Pod state manager cannot be null");
} }
if (duration == null) { if (duration == null) {
throw new ActionInitializationException("Duration cannot be null"); throw new ActionInitializationException("Duration cannot be null");
} }
this.podState = podState; this.podStateManager = podStateManager;
this.rate = rate; this.rate = rate;
this.duration = duration; this.duration = duration;
this.acknowledgementBeep = acknowledgementBeep; this.acknowledgementBeep = acknowledgementBeep;
@ -39,10 +39,10 @@ public class SetTempBasalAction implements OmnipodAction<StatusResponse> {
@Override @Override
public StatusResponse execute(OmnipodCommunicationManager communicationService) { public StatusResponse execute(OmnipodCommunicationManager communicationService) {
List<MessageBlock> messageBlocks = Arrays.asList( // List<MessageBlock> messageBlocks = Arrays.asList( //
new SetInsulinScheduleCommand(podState.getCurrentNonce(), rate, duration), new SetInsulinScheduleCommand(podStateManager.getCurrentNonce(), rate, duration),
new TempBasalExtraCommand(rate, duration, acknowledgementBeep, completionBeep, Duration.ZERO)); new TempBasalExtraCommand(rate, duration, acknowledgementBeep, completionBeep, Duration.ZERO));
OmnipodMessage message = new OmnipodMessage(podState.getAddress(), messageBlocks, podState.getMessageNumber()); OmnipodMessage message = new OmnipodMessage(podStateManager.getAddress(), messageBlocks, podStateManager.getMessageNumber());
return communicationService.exchangeMessages(StatusResponse.class, podState, message); return communicationService.exchangeMessages(StatusResponse.class, podStateManager, message);
} }
} }

View file

@ -16,35 +16,38 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.Ver
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress; import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
public class SetupPodAction implements OmnipodAction<VersionResponse> { public class SetupPodAction implements OmnipodAction<VersionResponse> {
private final PodSessionState podState; private final PodStateManager podStateManager;
public SetupPodAction(PodSessionState podState) { public SetupPodAction(PodStateManager podStateManager) {
this.podState = podState; if(podStateManager == null) {
throw new IllegalArgumentException("Pod state manager can not be null");
}
this.podStateManager = podStateManager;
} }
@Override @Override
public VersionResponse execute(OmnipodCommunicationManager communicationService) { public VersionResponse execute(OmnipodCommunicationManager communicationService) {
if (!podState.getSetupProgress().equals(SetupProgress.ADDRESS_ASSIGNED)) { if (!podStateManager.getSetupProgress().equals(SetupProgress.ADDRESS_ASSIGNED)) {
throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, podState.getSetupProgress()); throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, podStateManager.getSetupProgress());
} }
DateTime activationDate = DateTime.now(podState.getTimeZone()); DateTime activationDate = DateTime.now(podStateManager.getTimeZone());
SetupPodCommand setupPodCommand = new SetupPodCommand(podState.getAddress(), activationDate, SetupPodCommand setupPodCommand = new SetupPodCommand(podStateManager.getAddress(), activationDate,
podState.getLot(), podState.getTid()); podStateManager.getLot(), podStateManager.getTid());
OmnipodMessage message = new OmnipodMessage(OmnipodConst.DEFAULT_ADDRESS, OmnipodMessage message = new OmnipodMessage(OmnipodConst.DEFAULT_ADDRESS,
Collections.singletonList(setupPodCommand), podState.getMessageNumber()); Collections.singletonList(setupPodCommand), podStateManager.getMessageNumber());
VersionResponse setupPodResponse; VersionResponse setupPodResponse;
try { try {
setupPodResponse = communicationService.exchangeMessages(VersionResponse.class, podState, setupPodResponse = communicationService.exchangeMessages(VersionResponse.class, podStateManager,
message, OmnipodConst.DEFAULT_ADDRESS, podState.getAddress()); message, OmnipodConst.DEFAULT_ADDRESS, podStateManager.getAddress());
} catch (IllegalPacketTypeException ex) { } catch (IllegalPacketTypeException ex) {
if (PacketType.ACK.equals(ex.getActual())) { if (PacketType.ACK.equals(ex.getActual())) {
// Pod is already configured // Pod is already configured
podState.setSetupProgress(SetupProgress.POD_CONFIGURED); podStateManager.setSetupProgress(SetupProgress.POD_CONFIGURED);
return null; return null;
} }
throw ex; throw ex;
@ -53,14 +56,14 @@ public class SetupPodAction implements OmnipodAction<VersionResponse> {
if (!setupPodResponse.isSetupPodVersionResponse()) { if (!setupPodResponse.isSetupPodVersionResponse()) {
throw new IllegalVersionResponseTypeException("setupPod", "assignAddress"); throw new IllegalVersionResponseTypeException("setupPod", "assignAddress");
} }
if (setupPodResponse.getAddress() != podState.getAddress()) { if (setupPodResponse.getAddress() != podStateManager.getAddress()) {
throw new IllegalMessageAddressException(podState.getAddress(), setupPodResponse.getAddress()); throw new IllegalMessageAddressException(podStateManager.getAddress(), setupPodResponse.getAddress());
} }
if (setupPodResponse.getPodProgressStatus() != PodProgressStatus.PAIRING_COMPLETED) { if (setupPodResponse.getPodProgressStatus() != PodProgressStatus.PAIRING_COMPLETED) {
throw new IllegalPodProgressException(PodProgressStatus.PAIRING_COMPLETED, setupPodResponse.getPodProgressStatus()); throw new IllegalPodProgressException(PodProgressStatus.PAIRING_COMPLETED, setupPodResponse.getPodProgressStatus());
} }
podState.setSetupProgress(SetupProgress.POD_CONFIGURED); podStateManager.setSetupProgress(SetupProgress.POD_CONFIGURED);
return setupPodResponse; return setupPodResponse;
} }

View file

@ -14,21 +14,21 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.Sta
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfiguration; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfiguration;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfigurationFactory; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfigurationFactory;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
public class InsertCannulaService { public class InsertCannulaService {
public StatusResponse programInitialBasalSchedule(OmnipodCommunicationManager communicationService, public StatusResponse programInitialBasalSchedule(OmnipodCommunicationManager communicationService,
PodSessionState podState, BasalSchedule basalSchedule) { PodStateManager podStateManager, BasalSchedule basalSchedule) {
return communicationService.executeAction(new SetBasalScheduleAction(podState, basalSchedule, return communicationService.executeAction(new SetBasalScheduleAction(podStateManager, basalSchedule,
true, podState.getScheduleOffset(), false)); true, podStateManager.getScheduleOffset(), false));
} }
public StatusResponse executeExpirationRemindersAlertCommand(OmnipodCommunicationManager communicationService, public StatusResponse executeExpirationRemindersAlertCommand(OmnipodCommunicationManager communicationService,
PodSessionState podState) { PodStateManager podStateManager) {
AlertConfiguration lowReservoirAlertConfiguration = AlertConfigurationFactory.createLowReservoirAlertConfiguration(OmnipodConst.LOW_RESERVOIR_ALERT); AlertConfiguration lowReservoirAlertConfiguration = AlertConfigurationFactory.createLowReservoirAlertConfiguration(OmnipodConst.LOW_RESERVOIR_ALERT);
DateTime endOfServiceTime = podState.getActivatedAt().plus(OmnipodConst.SERVICE_DURATION); DateTime endOfServiceTime = podStateManager.getActivatedAt().plus(OmnipodConst.SERVICE_DURATION);
Duration timeUntilExpirationAdvisoryAlarm = new Duration(DateTime.now(), Duration timeUntilExpirationAdvisoryAlarm = new Duration(DateTime.now(),
endOfServiceTime.minus(OmnipodConst.EXPIRATION_ADVISORY_WINDOW)); endOfServiceTime.minus(OmnipodConst.EXPIRATION_ADVISORY_WINDOW));
@ -49,11 +49,11 @@ public class InsertCannulaService {
autoOffAlertConfiguration // autoOffAlertConfiguration //
); );
return new ConfigureAlertsAction(podState, alertConfigurations).execute(communicationService); return new ConfigureAlertsAction(podStateManager, alertConfigurations).execute(communicationService);
} }
public StatusResponse executeInsertionBolusCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { public StatusResponse executeInsertionBolusCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) {
return communicationService.executeAction(new BolusAction(podState, OmnipodConst.POD_CANNULA_INSERTION_BOLUS_UNITS, return communicationService.executeAction(new BolusAction(podStateManager, OmnipodConst.POD_CANNULA_INSERTION_BOLUS_UNITS,
Duration.standardSeconds(1), false, false)); Duration.standardSeconds(1), false, false));
} }
} }

View file

@ -12,26 +12,26 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.Faul
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfiguration; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfiguration;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfigurationFactory; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertConfigurationFactory;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
public class PrimeService { public class PrimeService {
public StatusResponse executeDisableTab5Sub16FaultConfigCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { public StatusResponse executeDisableTab5Sub16FaultConfigCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) {
FaultConfigCommand faultConfigCommand = new FaultConfigCommand(podState.getCurrentNonce(), (byte) 0x00, (byte) 0x00); FaultConfigCommand faultConfigCommand = new FaultConfigCommand(podStateManager.getCurrentNonce(), (byte) 0x00, (byte) 0x00);
OmnipodMessage faultConfigMessage = new OmnipodMessage(podState.getAddress(), OmnipodMessage faultConfigMessage = new OmnipodMessage(podStateManager.getAddress(),
Collections.singletonList(faultConfigCommand), podState.getMessageNumber()); Collections.singletonList(faultConfigCommand), podStateManager.getMessageNumber());
return communicationService.exchangeMessages(StatusResponse.class, podState, faultConfigMessage); return communicationService.exchangeMessages(StatusResponse.class, podStateManager, faultConfigMessage);
} }
public StatusResponse executeFinishSetupReminderAlertCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { public StatusResponse executeFinishSetupReminderAlertCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) {
AlertConfiguration finishSetupReminderAlertConfiguration = AlertConfigurationFactory.createFinishSetupReminderAlertConfiguration(); AlertConfiguration finishSetupReminderAlertConfiguration = AlertConfigurationFactory.createFinishSetupReminderAlertConfiguration();
return communicationService.executeAction(new ConfigureAlertsAction(podState, return communicationService.executeAction(new ConfigureAlertsAction(podStateManager,
Collections.singletonList(finishSetupReminderAlertConfiguration))); Collections.singletonList(finishSetupReminderAlertConfiguration)));
} }
public StatusResponse executePrimeBolusCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { public StatusResponse executePrimeBolusCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) {
return communicationService.executeAction(new BolusAction(podState, OmnipodConst.POD_PRIME_BOLUS_UNITS, return communicationService.executeAction(new BolusAction(podStateManager, OmnipodConst.POD_PRIME_BOLUS_UNITS,
Duration.standardSeconds(1), false, false)); Duration.standardSeconds(1), false, false));
} }
} }

View file

@ -1,299 +0,0 @@
package info.nightscout.androidaps.plugins.pump.omnipod.defs.state;
import com.google.gson.Gson;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoFaultEvent;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSet;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.FirmwareVersion;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.NonceState;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmniCRC;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodUtil;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class PodSessionState extends PodState {
@Inject transient AAPSLogger aapsLogger;
@Inject transient SP sp;
@Inject transient OmnipodUtil omnipodUtil;
private transient PodStateChangedHandler stateChangedHandler;
private final Map<AlertSlot, AlertType> configuredAlerts;
private DateTimeZone timeZone;
private DateTime activatedAt;
private DateTime expiresAt;
private final FirmwareVersion piVersion;
private final FirmwareVersion pmVersion;
private final int lot;
private final int tid;
private Double reservoirLevel;
private boolean suspended;
private NonceState nonceState;
private SetupProgress setupProgress;
private AlertSet activeAlerts;
private BasalSchedule basalSchedule;
private DeliveryStatus lastDeliveryStatus;
public PodSessionState(DateTimeZone timeZone, int address, FirmwareVersion piVersion,
FirmwareVersion pmVersion, int lot, int tid, int packetNumber, int messageNumber, HasAndroidInjector injector) {
super(address, messageNumber, packetNumber);
injectDaggerClass(injector);
if (timeZone == null) {
throw new IllegalArgumentException("Time zone can not be null");
}
suspended = false;
configuredAlerts = new HashMap<>();
configuredAlerts.put(AlertSlot.SLOT7, AlertType.FINISH_SETUP_REMINDER);
this.timeZone = timeZone;
this.setupProgress = SetupProgress.ADDRESS_ASSIGNED;
this.piVersion = piVersion;
this.pmVersion = pmVersion;
this.lot = lot;
this.tid = tid;
this.nonceState = new NonceState(lot, tid);
handleUpdates();
}
public void injectDaggerClass(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
}
public void setStateChangedHandler(PodStateChangedHandler handler) {
// FIXME this is an ugly workaround for not being able to serialize the PodStateChangedHandler
if (stateChangedHandler != null) {
throw new IllegalStateException("A PodStateChangedHandler has already been already registered");
}
stateChangedHandler = handler;
}
public AlertType getConfiguredAlertType(AlertSlot alertSlot) {
return configuredAlerts.get(alertSlot);
}
public void putConfiguredAlert(AlertSlot alertSlot, AlertType alertType) {
configuredAlerts.put(alertSlot, alertType);
handleUpdates();
}
public void removeConfiguredAlert(AlertSlot alertSlot) {
configuredAlerts.remove(alertSlot);
handleUpdates();
}
public DateTime getActivatedAt() {
return activatedAt == null ? null : activatedAt.withZone(timeZone);
}
public DateTime getExpiresAt() {
return expiresAt == null ? null : expiresAt.withZone(timeZone);
}
public String getExpiryDateAsString() {
return expiresAt == null ? "???" : DateUtil.dateAndTimeString(expiresAt.toDate());
}
public FirmwareVersion getPiVersion() {
return piVersion;
}
public FirmwareVersion getPmVersion() {
return pmVersion;
}
public int getLot() {
return lot;
}
public int getTid() {
return tid;
}
public Double getReservoirLevel() {
return reservoirLevel;
}
public synchronized void resyncNonce(int syncWord, int sentNonce, int sequenceNumber) {
int sum = (sentNonce & 0xFFFF)
+ OmniCRC.crc16lookup[sequenceNumber]
+ (this.lot & 0xFFFF)
+ (this.tid & 0xFFFF);
int seed = ((sum & 0xFFFF) ^ syncWord);
this.nonceState = new NonceState(lot, tid, (byte) (seed & 0xFF));
handleUpdates();
}
public int getCurrentNonce() {
return nonceState.getCurrentNonce();
}
public synchronized void advanceToNextNonce() {
nonceState.advanceToNextNonce();
handleUpdates();
}
public SetupProgress getSetupProgress() {
return setupProgress;
}
public synchronized void setSetupProgress(SetupProgress setupProgress) {
if (setupProgress == null) {
throw new IllegalArgumentException("Setup state cannot be null");
}
this.setupProgress = setupProgress;
handleUpdates();
}
public boolean isSuspended() {
return suspended;
}
public boolean hasActiveAlerts() {
return activeAlerts != null && activeAlerts.size() > 0;
}
public AlertSet getActiveAlerts() {
return activeAlerts;
}
public DateTimeZone getTimeZone() {
return timeZone;
}
public void setTimeZone(DateTimeZone timeZone) {
if (timeZone == null) {
throw new IllegalArgumentException("Time zone can not be null");
}
this.timeZone = timeZone;
handleUpdates();
}
public DateTime getTime() {
DateTime now = DateTime.now();
return now.withZone(timeZone);
}
public Duration getScheduleOffset() {
DateTime now = getTime();
DateTime startOfDay = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(),
0, 0, 0, timeZone);
return new Duration(startOfDay, now);
}
public boolean hasNonceState() {
return true;
}
@Override
public void setPacketNumber(int packetNumber) {
super.setPacketNumber(packetNumber);
handleUpdates();
}
@Override
public void setMessageNumber(int messageNumber) {
super.setMessageNumber(messageNumber);
handleUpdates();
}
public BasalSchedule getBasalSchedule() {
return basalSchedule;
}
public void setBasalSchedule(BasalSchedule basalSchedule) {
this.basalSchedule = basalSchedule;
handleUpdates();
}
public DeliveryStatus getLastDeliveryStatus() {
return lastDeliveryStatus;
}
@Override
public void setFaultEvent(PodInfoFaultEvent faultEvent) {
super.setFaultEvent(faultEvent);
suspended = true;
handleUpdates();
}
@Override
public void updateFromStatusResponse(StatusResponse statusResponse) {
DateTime activatedAtCalculated = getTime().minus(statusResponse.getTimeActive());
if (activatedAt == null) {
activatedAt = activatedAtCalculated;
}
DateTime expiresAtCalculated = activatedAtCalculated.plus(OmnipodConst.NOMINAL_POD_LIFE);
if (expiresAt == null || expiresAtCalculated.isBefore(expiresAt) || expiresAtCalculated.isAfter(expiresAt.plusMinutes(1))) {
expiresAt = expiresAtCalculated;
}
boolean newSuspendedState = statusResponse.getDeliveryStatus() == DeliveryStatus.SUSPENDED;
if (suspended != newSuspendedState) {
aapsLogger.info(LTag.PUMPCOMM, "Updating pod suspended state in updateFromStatusResponse. newSuspendedState={}, statusResponse={}", newSuspendedState, statusResponse.toString());
suspended = newSuspendedState;
}
activeAlerts = statusResponse.getAlerts();
lastDeliveryStatus = statusResponse.getDeliveryStatus();
reservoirLevel = statusResponse.getReservoirLevel();
handleUpdates();
}
private void handleUpdates() {
Gson gson = omnipodUtil.getGsonInstance();
String gsonValue = gson.toJson(this);
aapsLogger.info(LTag.PUMPCOMM, "PodSessionState-SP: Saved Session State to SharedPreferences: " + gsonValue);
sp.putString(OmnipodConst.Prefs.PodState, gsonValue);
if (stateChangedHandler != null) {
stateChangedHandler.handle(this);
}
}
@Override
public String toString() {
return "PodSessionState{" +
"configuredAlerts=" + configuredAlerts +
", stateChangedHandler=" + stateChangedHandler +
", activatedAt=" + activatedAt +
", expiresAt=" + expiresAt +
", piVersion=" + piVersion +
", pmVersion=" + pmVersion +
", lot=" + lot +
", tid=" + tid +
", reservoirLevel=" + reservoirLevel +
", suspended=" + suspended +
", timeZone=" + timeZone +
", nonceState=" + nonceState +
", setupProgress=" + setupProgress +
", activeAlerts=" + activeAlerts +
", basalSchedule=" + basalSchedule +
", lastDeliveryStatus=" + lastDeliveryStatus +
", address=" + address +
", packetNumber=" + packetNumber +
", messageNumber=" + messageNumber +
", faultEvent=" + faultEvent +
'}';
}
}

View file

@ -1,43 +0,0 @@
package info.nightscout.androidaps.plugins.pump.omnipod.defs.state;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
public class PodSetupState extends PodState {
public PodSetupState(int address, int packetNumber, int messageNumber) {
super(address, packetNumber, messageNumber);
}
@Override
public boolean hasNonceState() {
return false;
}
@Override
public int getCurrentNonce() {
throw new UnsupportedOperationException("PodSetupState does not have a nonce state");
}
@Override
public void advanceToNextNonce() {
throw new UnsupportedOperationException("PodSetupState does not have a nonce state");
}
@Override
public void resyncNonce(int syncWord, int sentNonce, int sequenceNumber) {
throw new UnsupportedOperationException("PodSetupState does not have a nonce state");
}
@Override
public void updateFromStatusResponse(StatusResponse statusResponse) {
}
@Override
public String toString() {
return "PodSetupState{" +
"address=" + address +
", packetNumber=" + packetNumber +
", messageNumber=" + messageNumber +
", faultEvent=" + faultEvent +
'}';
}
}

View file

@ -1,68 +0,0 @@
package info.nightscout.androidaps.plugins.pump.omnipod.defs.state;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoFaultEvent;
public abstract class PodState {
protected final int address;
protected int packetNumber;
protected int messageNumber;
protected PodInfoFaultEvent faultEvent;
public PodState(int address, int packetNumber, int messageNumber) {
this.address = address;
this.packetNumber = packetNumber;
this.messageNumber = messageNumber;
}
public abstract boolean hasNonceState();
public abstract int getCurrentNonce();
public abstract void advanceToNextNonce();
public abstract void resyncNonce(int syncWord, int sentNonce, int sequenceNumber);
public abstract void updateFromStatusResponse(StatusResponse statusResponse);
public int getAddress() {
return address;
}
public int getMessageNumber() {
return messageNumber;
}
public void setMessageNumber(int messageNumber) {
this.messageNumber = messageNumber;
}
public int getPacketNumber() {
return packetNumber;
}
public void setPacketNumber(int packetNumber) {
this.packetNumber = packetNumber;
}
public void increaseMessageNumber() {
setMessageNumber((messageNumber + 1) & 0b1111);
}
public void increasePacketNumber() {
setPacketNumber((packetNumber + 1) & 0b11111);
}
public boolean hasFaultEvent() {
return faultEvent != null;
}
public PodInfoFaultEvent getFaultEvent() {
return faultEvent;
}
public void setFaultEvent(PodInfoFaultEvent faultEvent) {
this.faultEvent = faultEvent;
}
}

View file

@ -2,5 +2,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.defs.state;
@FunctionalInterface @FunctionalInterface
public interface PodStateChangedHandler { public interface PodStateChangedHandler {
void handle(PodSessionState podState); void handle(PodStateManager podStateManager);
} }

View file

@ -20,21 +20,25 @@ public interface PodStateManager {
void removeState(); void removeState();
void initState(int address);
boolean isPaired(); boolean isPaired();
public int getAddress(); void setPairingParameters(int lot, int tid, FirmwareVersion piVersion, FirmwareVersion pmVersion, DateTimeZone timeZone);
public int getMessageNumber(); int getAddress();
public void setMessageNumber(int messageNumber); int getMessageNumber();
public int getPacketNumber(); void setMessageNumber(int messageNumber);
public void setPacketNumber(int packetNumber); int getPacketNumber();
public void increaseMessageNumber(); void setPacketNumber(int packetNumber);
public void increasePacketNumber(); void increaseMessageNumber();
void increasePacketNumber();
void resyncNonce(int syncWord, int sentNonce, int sequenceNumber); void resyncNonce(int syncWord, int sentNonce, int sequenceNumber);
@ -42,11 +46,11 @@ public interface PodStateManager {
void advanceToNextNonce(); void advanceToNextNonce();
public boolean hasFaultEvent(); boolean hasFaultEvent();
public PodInfoFaultEvent getFaultEvent(); PodInfoFaultEvent getFaultEvent();
public void setFaultEvent(PodInfoFaultEvent faultEvent); void setFaultEvent(PodInfoFaultEvent faultEvent);
AlertType getConfiguredAlertType(AlertSlot alertSlot); AlertType getConfiguredAlertType(AlertSlot alertSlot);
@ -95,4 +99,6 @@ public interface PodStateManager {
DeliveryStatus getLastDeliveryStatus(); DeliveryStatus getLastDeliveryStatus();
void updateFromStatusResponse(StatusResponse statusResponse); void updateFromStatusResponse(StatusResponse statusResponse);
void setStateChangedHandler(PodStateChangedHandler handler);
} }

View file

@ -45,7 +45,6 @@ class PodManagementActivity : NoSplashAppCompatActivity() {
@Inject lateinit var injector: HasAndroidInjector @Inject lateinit var injector: HasAndroidInjector
private var initPodChanged = false private var initPodChanged = false
private var podSessionFullyInitalized = false
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -99,8 +98,8 @@ class PodManagementActivity : NoSplashAppCompatActivity() {
wizardPagerContext.clearContext() wizardPagerContext.clearContext()
wizardPagerContext.pagerSettings = pagerSettings wizardPagerContext.pagerSettings = pagerSettings
val podSessionState = omnipodUtil.getPodSessionState() val podStateManager = omnipodUtil.getPodStateManager()
val isFullInit = podSessionState == null || podSessionState.setupProgress.isBefore(SetupProgress.PRIMING_FINISHED) val isFullInit = podStateManager == null || podStateManager.setupProgress.isBefore(SetupProgress.PRIMING_FINISHED)
if (isFullInit) { if (isFullInit) {
wizardPagerContext.wizardModel = FullInitPodWizardModel(applicationContext) wizardPagerContext.wizardModel = FullInitPodWizardModel(applicationContext)
} else { } else {
@ -151,13 +150,13 @@ class PodManagementActivity : NoSplashAppCompatActivity() {
} }
fun refreshButtons() { fun refreshButtons() {
initpod_init_pod.isEnabled = (omnipodUtil.getPodSessionState() == null || initpod_init_pod.isEnabled = omnipodUtil.podStateManager == null || !omnipodUtil.podStateManager.isPaired() ||
omnipodUtil.getPodSessionState().getSetupProgress().isBefore(SetupProgress.COMPLETED)) omnipodUtil.getPodStateManager().getSetupProgress().isBefore(SetupProgress.COMPLETED)
val isPodSessionActive = (omnipodUtil.getPodSessionState() != null) val isPodSessionActive = omnipodUtil.podStateManager != null && omnipodUtil.podStateManager.hasState()
initpod_remove_pod.isEnabled = isPodSessionActive initpod_remove_pod.isEnabled = isPodSessionActive && omnipodUtil.podStateManager.isPaired
initpod_reset_pod.isEnabled = isPodSessionActive || omnipodUtil.hasNextPodAddress() initpod_reset_pod.isEnabled = isPodSessionActive
if (omnipodUtil.getDriverState() == OmnipodDriverState.NotInitalized) { if (omnipodUtil.getDriverState() == OmnipodDriverState.NotInitalized) {
// if rileylink is not running we disable all operations // if rileylink is not running we disable all operations

View file

@ -58,7 +58,7 @@ public class InitPodRefreshAction extends AbstractCancelAction implements Finish
@Override @Override
public void execute() { public void execute() {
if (actionType == PodActionType.InitPod) { if (actionType == PodActionType.InitPod) {
if (omnipodUtil.getPodSessionState().getSetupProgress().isBefore(SetupProgress.COMPLETED)) { if (omnipodUtil.getPodStateManager().getSetupProgress().isBefore(SetupProgress.COMPLETED)) {
omnipodUtil.setDriverState(OmnipodDriverState.Initalized_PodInitializing); omnipodUtil.setDriverState(OmnipodDriverState.Initalized_PodInitializing);
} else { } else {
omnipodUtil.setDriverState(OmnipodDriverState.Initalized_PodAttached); omnipodUtil.setDriverState(OmnipodDriverState.Initalized_PodAttached);

View file

@ -19,7 +19,7 @@ import javax.inject.Inject;
import dagger.android.support.DaggerFragment; import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodUtil; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodUtil;
@ -85,27 +85,26 @@ public class PodInfoFragment extends DaggerFragment {
private boolean createDataOfPod() { private boolean createDataOfPod() {
PodSessionState podSessionState = omnipodUtil.getPodSessionState(); PodStateManager podStateManager = omnipodUtil.getPodStateManager();
// PodSessionState podSessionState = new PodSessionState(DateTimeZone.UTC, if (podStateManager == null)
// 483748738,
// new DateTime(),
// new FirmwareVersion(1,0,0),
// new FirmwareVersion(1,0,0),
// 574875,
// 5487584,
// 1,
// 1
// );
if (podSessionState == null)
return false; return false;
mCurrentReviewItems = new ArrayList<>(); mCurrentReviewItems = new ArrayList<>();
mCurrentReviewItems.add(new ReviewItem("Pod Address", "" + podSessionState.getAddress(), "33")); mCurrentReviewItems.add(new ReviewItem("Pod Address", "" + podStateManager.getAddress(), "33"));
mCurrentReviewItems.add(new ReviewItem("Activated At", podSessionState.getActivatedAt().toString("dd.MM.yyyy HH:mm:ss"), "34")); mCurrentReviewItems.add(new ReviewItem("Activated At", podStateManager.getActivatedAt() == null ? "Not activated yet" : podStateManager.getActivatedAt().toString("dd.MM.yyyy HH:mm:ss"), "34"));
mCurrentReviewItems.add(new ReviewItem("Firmware Version", podSessionState.getPiVersion().toString(), "35")); if (podStateManager.getLot() != null) {
mCurrentReviewItems.add(new ReviewItem("LOT", "" + podSessionState.getLot(), "36")); mCurrentReviewItems.add(new ReviewItem("LOT", "" + podStateManager.getLot(), "35"));
}
if(podStateManager.getTid() != null) {
mCurrentReviewItems.add(new ReviewItem("TID", "" + podStateManager.getLot(), "36"));
}
if (podStateManager.getPiVersion() != null) {
mCurrentReviewItems.add(new ReviewItem("Pi Version", podStateManager.getPiVersion().toString(), "37"));
}
if (podStateManager.getPmVersion() != null) {
mCurrentReviewItems.add(new ReviewItem("Pm Version", podStateManager.getPmVersion().toString(), "38"));
}
return true; return true;
} }

View file

@ -15,9 +15,8 @@ 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.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
@ -47,7 +46,7 @@ public class OmnipodPumpStatus extends PumpStatus {
public Double tempBasalAmount = 0.0d; public Double tempBasalAmount = 0.0d;
public Integer tempBasalLength; public Integer tempBasalLength;
public long tempBasalPumpId; public long tempBasalPumpId;
public PodSessionState podSessionState; public PodStateManager podStateManager;
public PumpType pumpType; public PumpType pumpType;
public String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}"; public String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}";
@ -142,7 +141,7 @@ public class OmnipodPumpStatus extends PumpStatus {
", tempBasalEnd=" + tempBasalEnd + ", tempBasalEnd=" + tempBasalEnd +
", tempBasalAmount=" + tempBasalAmount + ", tempBasalAmount=" + tempBasalAmount +
", tempBasalLength=" + tempBasalLength + ", tempBasalLength=" + tempBasalLength +
", podSessionState=" + podSessionState + ", podStateManager=" + podStateManager +
", regexMac='" + regexMac + '\'' + ", regexMac='" + regexMac + '\'' +
", podNumber='" + podNumber + '\'' + ", podNumber='" + podNumber + '\'' +
", podDeviceState=" + podDeviceState + ", podDeviceState=" + podDeviceState +

View file

@ -60,6 +60,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.PodReturne
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoRecentPulseLog; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoRecentPulseLog;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSet;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode;
@ -69,7 +70,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitReceiver; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitReceiver;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalScheduleEntry; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalScheduleEntry;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.db.PodHistory; import info.nightscout.androidaps.plugins.pump.omnipod.driver.db.PodHistory;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.db.PodHistoryEntryType; import info.nightscout.androidaps.plugins.pump.omnipod.driver.db.PodHistoryEntryType;
@ -103,7 +104,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
} }
public AapsOmnipodManager(OmnipodCommunicationManager communicationService, public AapsOmnipodManager(OmnipodCommunicationManager communicationService,
PodSessionState podState, PodStateManager podStateManager,
OmnipodPumpStatus _pumpStatus, OmnipodPumpStatus _pumpStatus,
OmnipodUtil omnipodUtil, OmnipodUtil omnipodUtil,
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
@ -120,17 +121,26 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
this.activePlugin = activePlugin; this.activePlugin = activePlugin;
this.pumpStatus = _pumpStatus; this.pumpStatus = _pumpStatus;
delegate = new OmnipodManager(aapsLogger, sp, communicationService, podState, podSessionState -> { podStateManager.setStateChangedHandler(manager -> {
// Handle pod state changes // Handle pod state changes
omnipodUtil.setPodSessionState(podSessionState); // FIXME only set once (?) (before instantiating AapsOmnipodManager)
updatePumpStatus(podSessionState); // Maybe not, it seems to not only set something, but also fire an event
omnipodUtil.setPodStateManager(manager);
updatePumpStatus(manager);
}); });
delegate = new OmnipodManager(aapsLogger, sp, communicationService, podStateManager);
instance = this; instance = this;
} }
private void updatePumpStatus(PodSessionState podSessionState) { public PodStateManager getPodStateManager() {
return delegate.getPodStateManager();
}
private void updatePumpStatus(PodStateManager podStateManager) {
if (pumpStatus != null) { if (pumpStatus != null) {
if (podSessionState == null) { if (!podStateManager.hasState()) {
pumpStatus.ackAlertsText = null; pumpStatus.ackAlertsText = null;
pumpStatus.ackAlertsAvailable = false; pumpStatus.ackAlertsAvailable = false;
pumpStatus.lastBolusTime = null; pumpStatus.lastBolusTime = null;
@ -142,8 +152,8 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
sendEvent(new EventRefreshOverview("Omnipod Pump", false)); sendEvent(new EventRefreshOverview("Omnipod Pump", false));
} else { } else {
// Update active alerts // Update active alerts
if (podSessionState.hasActiveAlerts()) { if (podStateManager.hasActiveAlerts()) {
List<String> alerts = translateActiveAlerts(podSessionState); List<String> alerts = translateActiveAlerts(podStateManager);
String alertsText = TextUtils.join("\n", alerts); String alertsText = TextUtils.join("\n", alerts);
if (!pumpStatus.ackAlertsAvailable || !alertsText.equals(pumpStatus.ackAlertsText)) { if (!pumpStatus.ackAlertsAvailable || !alertsText.equals(pumpStatus.ackAlertsText)) {
@ -163,15 +173,15 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
// Update other info: last bolus, units remaining, suspended // Update other info: last bolus, units remaining, suspended
if (!Objects.equals(lastBolusTime, pumpStatus.lastBolusTime) // if (!Objects.equals(lastBolusTime, pumpStatus.lastBolusTime) //
|| !Objects.equals(lastBolusUnits, pumpStatus.lastBolusAmount) // || !Objects.equals(lastBolusUnits, pumpStatus.lastBolusAmount) //
|| !isReservoirStatusUpToDate(pumpStatus, podSessionState.getReservoirLevel()) || !isReservoirStatusUpToDate(pumpStatus, podStateManager.getReservoirLevel())
|| podSessionState.isSuspended() != PumpStatusType.Suspended.equals(pumpStatus.pumpStatusType)) { || podStateManager.isSuspended() != PumpStatusType.Suspended.equals(pumpStatus.pumpStatusType)) {
pumpStatus.lastBolusTime = lastBolusTime; pumpStatus.lastBolusTime = lastBolusTime;
pumpStatus.lastBolusAmount = lastBolusUnits; pumpStatus.lastBolusAmount = lastBolusUnits;
pumpStatus.reservoirRemainingUnits = podSessionState.getReservoirLevel() == null ? 75.0 : podSessionState.getReservoirLevel(); pumpStatus.reservoirRemainingUnits = podStateManager.getReservoirLevel() == null ? 75.0 : podStateManager.getReservoirLevel();
pumpStatus.pumpStatusType = podSessionState.isSuspended() ? PumpStatusType.Suspended : PumpStatusType.Running; pumpStatus.pumpStatusType = podStateManager.isSuspended() ? PumpStatusType.Suspended : PumpStatusType.Running;
sendEvent(new EventOmnipodPumpValuesChanged()); sendEvent(new EventOmnipodPumpValuesChanged());
if (podSessionState.isSuspended() != PumpStatusType.Suspended.equals(pumpStatus.pumpStatusType)) { if (podStateManager.isSuspended() != PumpStatusType.Suspended.equals(pumpStatus.pumpStatusType)) {
sendEvent(new EventRefreshOverview("Omnipod Pump", false)); sendEvent(new EventRefreshOverview("Omnipod Pump", false));
} }
} }
@ -179,31 +189,31 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
} }
} }
private List<String> translateActiveAlerts(PodStateManager podStateManager) {
List<String> translatedAlerts = new ArrayList<>();
AlertSet activeAlerts = podStateManager.getActiveAlerts();
if (activeAlerts == null) {
return translatedAlerts;
}
for (AlertSlot alertSlot : activeAlerts.getAlertSlots()) {
translatedAlerts.add(translateAlertType(podStateManager.getConfiguredAlertType(alertSlot)));
}
return translatedAlerts;
}
private static boolean isReservoirStatusUpToDate(OmnipodPumpStatus pumpStatus, Double unitsRemaining) { private static boolean isReservoirStatusUpToDate(OmnipodPumpStatus pumpStatus, Double unitsRemaining) {
double expectedUnitsRemaining = unitsRemaining == null ? 75.0 : unitsRemaining; double expectedUnitsRemaining = unitsRemaining == null ? 75.0 : unitsRemaining;
return Math.abs(expectedUnitsRemaining - pumpStatus.reservoirRemainingUnits) < 0.000001; return Math.abs(expectedUnitsRemaining - pumpStatus.reservoirRemainingUnits) < 0.000001;
} }
private List<String> translateActiveAlerts(PodSessionState podSessionState) {
List<String> alerts = new ArrayList<>();
for (AlertSlot alertSlot : podSessionState.getActiveAlerts().getAlertSlots()) {
alerts.add(translateAlertType(podSessionState.getConfiguredAlertType(alertSlot)));
}
return alerts;
}
@Override @Override
public PumpEnactResult initPod(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, Profile profile) { public PumpEnactResult initPod(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, Profile profile) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
if (PodInitActionType.PairAndPrimeWizardStep.equals(podInitActionType)) { if (PodInitActionType.PairAndPrimeWizardStep.equals(podInitActionType)) {
try { try {
int address = obtainNextPodAddress(); Disposable disposable = delegate.pairAndPrime().subscribe(res -> //
Disposable disposable = delegate.pairAndPrime(address).subscribe(res -> //
handleSetupActionResult(podInitActionType, podInitReceiver, res, time, null)); handleSetupActionResult(podInitActionType, podInitReceiver, res, time, null));
removeNextPodAddress();
return new PumpEnactResult(injector).success(true).enacted(true); return new PumpEnactResult(injector).success(true).enacted(true);
} catch (Exception ex) { } catch (Exception ex) {
String comment = handleAndTranslateException(ex); String comment = handleAndTranslateException(ex);
@ -265,8 +275,6 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
podInitReceiver.returnInitTaskStatus(PodInitActionType.DeactivatePodWizardStep, true, null); podInitReceiver.returnInitTaskStatus(PodInitActionType.DeactivatePodWizardStep, true, null);
this.omnipodUtil.setPodSessionState(null);
return new PumpEnactResult(injector).success(true).enacted(true); return new PumpEnactResult(injector).success(true).enacted(true);
} }
@ -302,13 +310,10 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
@Override @Override
public PumpEnactResult resetPodStatus() { public PumpEnactResult resetPodStatus() {
delegate.resetPodState(true); getPodStateManager().removeState();
reportImplicitlyCanceledTbr(); reportImplicitlyCanceledTbr();
this.omnipodUtil.setPodSessionState(null);
this.omnipodUtil.removeNextPodAddress();
addSuccessToHistory(System.currentTimeMillis(), PodHistoryEntryType.ResetPodState, null); addSuccessToHistory(System.currentTimeMillis(), PodHistoryEntryType.ResetPodState, null);
return new PumpEnactResult(injector).success(true).enacted(true); return new PumpEnactResult(injector).success(true).enacted(true);
@ -363,8 +368,8 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false);
if (delegate.getPodState().hasFaultEvent()) { if (delegate.getPodStateManager().hasFaultEvent()) {
showPodFaultErrorDialog(delegate.getPodState().getFaultEvent().getFaultEventCode(), R.raw.urgentalarm); showPodFaultErrorDialog(delegate.getPodStateManager().getFaultEvent().getFaultEventCode(), R.raw.urgentalarm);
} }
return new PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(unitsDelivered); return new PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(unitsDelivered);
@ -463,7 +468,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
@Override @Override
public void setPumpStatus(OmnipodPumpStatus pumpStatus) { public void setPumpStatus(OmnipodPumpStatus pumpStatus) {
this.pumpStatus = pumpStatus; this.pumpStatus = pumpStatus;
updatePumpStatus(delegate.getPodState()); updatePumpStatus(delegate.getPodStateManager());
} }
// TODO should we add this to the OmnipodCommunicationManager interface? // TODO should we add this to the OmnipodCommunicationManager interface?
@ -598,20 +603,6 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface
return podHistory.getPumpId(); return podHistory.getPumpId();
} }
private int obtainNextPodAddress() {
Integer nextPodAddress = this.omnipodUtil.getNextPodAddress();
if (nextPodAddress == null) {
nextPodAddress = OmnipodManager.generateRandomAddress();
this.omnipodUtil.setNextPodAddress(nextPodAddress);
}
return nextPodAddress;
}
private void removeNextPodAddress() {
this.omnipodUtil.removeNextPodAddress();
}
private void handleSetupActionResult(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, SetupActionResult res, long time, Profile profile) { private void handleSetupActionResult(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, SetupActionResult res, long time, Profile profile) {
String comment = null; String comment = null;
switch (res.getResultType()) { switch (res.getResultType()) {

View file

@ -25,6 +25,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.FirmwareVersion; import info.nightscout.androidaps.plugins.pump.omnipod.defs.FirmwareVersion;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress; import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.defs.schedule.BasalSchedule;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateChangedHandler;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmniCRC; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmniCRC;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
@ -34,11 +35,12 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class AapsPodStateManager implements PodStateManager { public class AapsPodStateManager implements PodStateManager {
@Inject private AAPSLogger aapsLogger; @Inject protected AAPSLogger aapsLogger;
@Inject private SP sp; @Inject protected SP sp;
@Inject private OmnipodUtil omnipodUtil; @Inject protected OmnipodUtil omnipodUtil;
private PodState podState; private PodState podState;
private PodStateChangedHandler stateChangedHandler;
public AapsPodStateManager(HasAndroidInjector injector) { public AapsPodStateManager(HasAndroidInjector injector) {
injector.androidInjector().inject(this); injector.androidInjector().inject(this);
@ -56,6 +58,15 @@ public class AapsPodStateManager implements PodStateManager {
persistPodState(); persistPodState();
} }
@Override
public void initState(int address) {
if (hasState()) {
throw new IllegalStateException("Can not init a new pod state: podState <> null");
}
podState = new PodState(address);
persistPodState();
}
@Override public boolean isPaired() { @Override public boolean isPaired() {
return hasState() // return hasState() //
&& podState.getLot() != null && podState.getTid() != null // && podState.getLot() != null && podState.getTid() != null //
@ -64,6 +75,7 @@ public class AapsPodStateManager implements PodStateManager {
&& podState.getSetupProgress() != null; && podState.getSetupProgress() != null;
} }
@Override
public void setPairingParameters(int lot, int tid, FirmwareVersion piVersion, FirmwareVersion pmVersion, DateTimeZone timeZone) { public void setPairingParameters(int lot, int tid, FirmwareVersion piVersion, FirmwareVersion pmVersion, DateTimeZone timeZone) {
if (!hasState()) { if (!hasState()) {
throw new IllegalStateException("Cannot set pairing parameters: podState is null"); throw new IllegalStateException("Cannot set pairing parameters: podState is null");
@ -81,6 +93,7 @@ public class AapsPodStateManager implements PodStateManager {
throw new IllegalArgumentException("Cannot set pairing parameters: timeZone can not be null"); throw new IllegalArgumentException("Cannot set pairing parameters: timeZone can not be null");
} }
setAndStore(() -> {
podState.setLot(lot); podState.setLot(lot);
podState.setTid(tid); podState.setTid(tid);
podState.setPiVersion(piVersion); podState.setPiVersion(piVersion);
@ -88,6 +101,8 @@ public class AapsPodStateManager implements PodStateManager {
podState.setTimeZone(timeZone); podState.setTimeZone(timeZone);
podState.setNonceState(new NonceState(lot, tid)); podState.setNonceState(new NonceState(lot, tid));
podState.setSetupProgress(SetupProgress.ADDRESS_ASSIGNED); podState.setSetupProgress(SetupProgress.ADDRESS_ASSIGNED);
podState.getConfiguredAlerts().put(AlertSlot.SLOT7, AlertType.FINISH_SETUP_REMINDER);
});
} }
@Override public int getAddress() { @Override public int getAddress() {
@ -118,7 +133,7 @@ public class AapsPodStateManager implements PodStateManager {
setAndStore(() -> podState.setPacketNumber(podState.getPacketNumber() + 1)); setAndStore(() -> podState.setPacketNumber(podState.getPacketNumber() + 1));
} }
@Override public void resyncNonce(int syncWord, int sentNonce, int sequenceNumber) { @Override public synchronized void resyncNonce(int syncWord, int sentNonce, int sequenceNumber) {
if (!isPaired()) { if (!isPaired()) {
throw new IllegalStateException("Cannot resync nonce: Pod is not paired yet"); throw new IllegalStateException("Cannot resync nonce: Pod is not paired yet");
} }
@ -133,14 +148,14 @@ public class AapsPodStateManager implements PodStateManager {
setAndStore(() -> podState.setNonceState(nonceState)); setAndStore(() -> podState.setNonceState(nonceState));
} }
@Override public int getCurrentNonce() { @Override public synchronized int getCurrentNonce() {
if (!isPaired()) { if (!isPaired()) {
throw new IllegalStateException("Cannot get current nonce: Pod is not paired yet"); throw new IllegalStateException("Cannot get current nonce: Pod is not paired yet");
} }
return podState.getNonceState().getCurrentNonce(); return podState.getNonceState().getCurrentNonce();
} }
@Override public void advanceToNextNonce() { @Override public synchronized void advanceToNextNonce() {
if (!isPaired()) { if (!isPaired()) {
throw new IllegalStateException("Cannot advance to next nonce: Pod is not paired yet"); throw new IllegalStateException("Cannot advance to next nonce: Pod is not paired yet");
} }
@ -292,12 +307,35 @@ public class AapsPodStateManager implements PodStateManager {
}); });
} }
@Override
public void setStateChangedHandler(PodStateChangedHandler handler) {
// FIXME this is an ugly workaround for not being able to serialize the PodStateChangedHandler
if (stateChangedHandler != null) {
throw new IllegalStateException("A PodStateChangedHandler has already been already registered");
}
stateChangedHandler = handler;
}
private void setAndStore(Runnable runnable) { private void setAndStore(Runnable runnable) {
if (!hasState()) { if (!hasState()) {
throw new IllegalStateException("Cannot mutate PodState: podState is null"); throw new IllegalStateException("Cannot mutate PodState: podState is null");
} }
runnable.run(); runnable.run();
persistPodState(); persistPodState();
notifyPodStateChanged();
}
private void persistPodState() {
Gson gson = omnipodUtil.getGsonInstance();
String gsonValue = gson.toJson(podState);
aapsLogger.info(LTag.PUMPCOMM, "PodState-SP: Saved PodState to SharedPreferences: " + gsonValue);
sp.putString(OmnipodConst.Prefs.PodState, gsonValue);
}
private void notifyPodStateChanged() {
if (stateChangedHandler != null) {
stateChangedHandler.handle(this);
}
} }
// Not actually "safe" as it throws an Exception, but it prevents NPEs // Not actually "safe" as it throws an Exception, but it prevents NPEs
@ -308,13 +346,6 @@ public class AapsPodStateManager implements PodStateManager {
return supplier.get(); return supplier.get();
} }
private void persistPodState() {
Gson gson = omnipodUtil.getGsonInstance();
String gsonValue = gson.toJson(podState);
aapsLogger.info(LTag.PUMPCOMM, "PodState-SP: Saved PodState to SharedPreferences: " + gsonValue);
sp.putString(OmnipodConst.Prefs.PodState, gsonValue);
}
private void loadPodState() { private void loadPodState() {
podState = null; podState = null;
@ -330,6 +361,14 @@ public class AapsPodStateManager implements PodStateManager {
aapsLogger.error(LTag.PUMPCOMM, "PodState-SP: could not deserialize PodState", ex); aapsLogger.error(LTag.PUMPCOMM, "PodState-SP: could not deserialize PodState", ex);
} }
} }
notifyPodStateChanged();
}
@Override public String toString() {
return "AapsPodStateManager{" +
"podState=" + podState +
'}';
} }
private static class PodState { private static class PodState {
@ -506,6 +545,30 @@ public class AapsPodStateManager implements PodStateManager {
public Map<AlertSlot, AlertType> getConfiguredAlerts() { public Map<AlertSlot, AlertType> getConfiguredAlerts() {
return configuredAlerts; return configuredAlerts;
} }
@Override public String toString() {
return "PodState{" +
"address=" + address +
", lot=" + lot +
", tid=" + tid +
", piVersion=" + piVersion +
", pmVersion=" + pmVersion +
", packetNumber=" + packetNumber +
", messageNumber=" + messageNumber +
", timeZone=" + timeZone +
", activatedAt=" + activatedAt +
", expiresAt=" + expiresAt +
", faultEvent=" + faultEvent +
", reservoirLevel=" + reservoirLevel +
", suspended=" + suspended +
", nonceState=" + nonceState +
", setupProgress=" + setupProgress +
", lastDeliveryStatus=" + lastDeliveryStatus +
", activeAlerts=" + activeAlerts +
", basalSchedule=" + basalSchedule +
", configuredAlerts=" + configuredAlerts +
'}';
}
} }
private static class NonceState { private static class NonceState {

View file

@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager
/** /**
* Created by andy on 4.8.2019 * Created by andy on 4.8.2019
@ -15,7 +15,7 @@ class EventOmnipodDeviceStatusChange : Event {
var rileyLinkServiceState: RileyLinkServiceState? = null var rileyLinkServiceState: RileyLinkServiceState? = null
var rileyLinkError: RileyLinkError? = null var rileyLinkError: RileyLinkError? = null
var podSessionState: PodSessionState? = null var podStateManager: PodStateManager? = null
var errorDescription: String? = null var errorDescription: String? = null
var podDeviceState: PodDeviceState? = null var podDeviceState: PodDeviceState? = null
var pumpDeviceState: PumpDeviceState? = null var pumpDeviceState: PumpDeviceState? = null
@ -32,8 +32,8 @@ class EventOmnipodDeviceStatusChange : Event {
} }
constructor(podSessionState: PodSessionState?) { constructor(podStateManager: PodStateManager?) {
this.podSessionState = podSessionState this.podStateManager = podStateManager
} }
constructor(errorDescription: String?) { constructor(errorDescription: String?) {
@ -58,7 +58,7 @@ class EventOmnipodDeviceStatusChange : Event {
return ("EventOmnipodDeviceStatusChange [" // return ("EventOmnipodDeviceStatusChange [" //
+ "rileyLinkServiceState=" + rileyLinkServiceState + "rileyLinkServiceState=" + rileyLinkServiceState
+ ", rileyLinkError=" + rileyLinkError // + ", rileyLinkError=" + rileyLinkError //
+ ", podSessionState=" + podSessionState // + ", podStateManager=" + podStateManager //
+ ", podDeviceState=" + podDeviceState + "]") + ", podDeviceState=" + podDeviceState + "]")
} }
} }

View file

@ -23,9 +23,10 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.Riley
import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState;
import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin; import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager; import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsPodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIComm; import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIComm;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIPostprocessor; import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIPostprocessor;
import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst;
@ -106,19 +107,23 @@ public class RileyLinkOmnipodService extends RileyLinkService {
} }
private void initializeErosOmnipodManager() { private void initializeErosOmnipodManager() {
if (AapsOmnipodManager.getInstance() == null) { AapsOmnipodManager instance = AapsOmnipodManager.getInstance();
PodSessionState podState = omnipodUtil.loadSessionState(); if (instance == null) {
PodStateManager podStateManager = new AapsPodStateManager(injector);
omnipodUtil.setPodStateManager(podStateManager);
OmnipodCommunicationManager omnipodCommunicationService = new OmnipodCommunicationManager(injector, rfspy); OmnipodCommunicationManager omnipodCommunicationService = new OmnipodCommunicationManager(injector, rfspy);
//omnipodCommunicationService.setPumpStatus(omnipodPumpStatus); //omnipodCommunicationService.setPumpStatus(omnipodPumpStatus);
this.omnipodCommunicationManager = omnipodCommunicationService; this.omnipodCommunicationManager = omnipodCommunicationService;
this.aapsOmnipodManager = new AapsOmnipodManager(omnipodCommunicationService, podState, omnipodPumpStatus, aapsOmnipodManager = new AapsOmnipodManager(omnipodCommunicationService, podStateManager, omnipodPumpStatus,
omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin); omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin);
omnipodUIComm = new OmnipodUIComm(injector, aapsLogger, omnipodUtil, omnipodUIPostprocessor, aapsOmnipodManager); omnipodUIComm = new OmnipodUIComm(injector, aapsLogger, omnipodUtil, omnipodUIPostprocessor, aapsOmnipodManager);
} else { } else {
aapsOmnipodManager = AapsOmnipodManager.getInstance(); aapsOmnipodManager = instance;
omnipodUtil.setPodStateManager(instance.getPodStateManager());
} }
} }

View file

@ -8,7 +8,6 @@ import com.google.gson.JsonDeserializer;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISODateTimeFormat;
@ -16,21 +15,18 @@ import org.joda.time.format.ISODateTimeFormat;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
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.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
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.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem;
import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodManager;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodPodType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodPodType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodDriverState; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodDriverState;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus;
import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange;
@ -49,13 +45,10 @@ public class OmnipodUtil {
private final OmnipodPumpStatus omnipodPumpStatus; private final OmnipodPumpStatus omnipodPumpStatus;
private final ActivePluginProvider activePlugins; private final ActivePluginProvider activePlugins;
private final SP sp; private final SP sp;
private final HasAndroidInjector injector;
private boolean lowLevelDebug = true; private boolean lowLevelDebug = true;
private OmnipodCommandType currentCommand; private OmnipodCommandType currentCommand;
private Gson gsonInstance = createGson(); private Gson gsonInstance = createGson();
//private static PodSessionState podSessionState;
//private static PodDeviceState podDeviceState;
private OmnipodPodType omnipodPodType; private OmnipodPodType omnipodPodType;
private OmnipodDriverState driverState = OmnipodDriverState.NotInitalized; private OmnipodDriverState driverState = OmnipodDriverState.NotInitalized;
@ -67,8 +60,7 @@ public class OmnipodUtil {
RileyLinkUtil rileyLinkUtil, RileyLinkUtil rileyLinkUtil,
OmnipodPumpStatus omnipodPumpStatus, OmnipodPumpStatus omnipodPumpStatus,
SP sp, SP sp,
ActivePluginProvider activePlugins, ActivePluginProvider activePlugins
HasAndroidInjector injector
) { ) {
this.aapsLogger = aapsLogger; this.aapsLogger = aapsLogger;
this.rxBus = rxBus; this.rxBus = rxBus;
@ -76,7 +68,6 @@ public class OmnipodUtil {
this.omnipodPumpStatus = omnipodPumpStatus; this.omnipodPumpStatus = omnipodPumpStatus;
this.sp = sp; this.sp = sp;
this.activePlugins = activePlugins; this.activePlugins = activePlugins;
this.injector = injector;
} }
@ -148,9 +139,9 @@ public class OmnipodUtil {
} }
public void setPodSessionState(PodSessionState podSessionState) { public void setPodStateManager(PodStateManager podStateManager) {
omnipodPumpStatus.podSessionState = podSessionState; omnipodPumpStatus.podStateManager = podStateManager;
rxBus.send(new EventOmnipodDeviceStatusChange(podSessionState)); rxBus.send(new EventOmnipodDeviceStatusChange(podStateManager));
} }
@ -174,8 +165,8 @@ public class OmnipodUtil {
} }
public PodSessionState getPodSessionState() { public PodStateManager getPodStateManager() {
return omnipodPumpStatus.podSessionState; return omnipodPumpStatus.podStateManager;
} }
@ -202,28 +193,6 @@ public class OmnipodUtil {
return this.gsonInstance; return this.gsonInstance;
} }
public Integer getNextPodAddress() {
if (sp.contains(OmnipodConst.Prefs.NextPodAddress)) {
int nextPodAddress = sp.getInt(OmnipodConst.Prefs.NextPodAddress, 0);
if (OmnipodManager.isValidAddress(nextPodAddress)) {
return nextPodAddress;
}
}
return null;
}
public boolean hasNextPodAddress() {
return getNextPodAddress() != null;
}
public void setNextPodAddress(int address) {
sp.putInt(OmnipodConst.Prefs.NextPodAddress, address);
}
public void removeNextPodAddress() {
sp.remove(OmnipodConst.Prefs.NextPodAddress);
}
public AAPSLogger getAapsLogger() { public AAPSLogger getAapsLogger() {
return this.aapsLogger; return this.aapsLogger;
} }
@ -231,25 +200,4 @@ public class OmnipodUtil {
public SP getSp() { public SP getSp() {
return this.sp; return this.sp;
} }
public PodSessionState loadSessionState() {
PodSessionState podSessionState = null;
String storedPodState = sp.getString(OmnipodConst.Prefs.PodState, "");
if (StringUtils.isEmpty(storedPodState)) {
aapsLogger.info(LTag.PUMP, "PodSessionState-SP: no PodSessionState present in SharedPreferences");
} else {
aapsLogger.info(LTag.PUMP, "PodSessionState-SP: loaded from SharedPreferences: " + storedPodState);
try {
podSessionState = gsonInstance.fromJson(storedPodState, PodSessionState.class);
podSessionState.injectDaggerClass(injector);
} catch (Exception ex) {
aapsLogger.error(LTag.PUMPCOMM, "Could not deserialize Pod state", ex);
}
}
setPodSessionState(podSessionState);
return podSessionState;
}
} }

View file

@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.pod
import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommunicationManagerInterface; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommunicationManagerInterface;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitReceiver; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitReceiver;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus;
/** /**
@ -34,7 +34,7 @@ public class OmnipodDashCommunicationManager implements OmnipodCommunicationMana
// RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); // RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L);
} }
private PodSessionState getPodSessionState() { private PodStateManager getPodStateManager() {
return null; return null;
} }

View file

@ -11,10 +11,11 @@ import org.mockito.Mock;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.plugins.pump.omnipod.defs.FirmwareVersion; import info.nightscout.androidaps.plugins.pump.omnipod.defs.FirmwareVersion;
import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsPodStateManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class PodSessionStateTest { public class AapsPodStateManagerTest {
@Mock HasAndroidInjector hasAndroidInjector; @Mock HasAndroidInjector hasAndroidInjector;
@Test @Test
@ -24,17 +25,16 @@ public class PodSessionStateTest {
DateTimeZone.setDefault(timeZone); DateTimeZone.setDefault(timeZone);
DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone); DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone);
DateTime initialized = now.minus(Duration.standardDays(1));
DateTimeUtils.setCurrentMillisFixed(now.getMillis()); DateTimeUtils.setCurrentMillisFixed(now.getMillis());
PodSessionState podSessionState = new PodSessionState(timeZone, 0x0, AapsPodStateManager podStateManager = new AapsPodStateManager(hasAndroidInjector);
new FirmwareVersion(1, 1, 1), podStateManager.initState(0x0);
new FirmwareVersion(2, 2, 2), podStateManager.setPairingParameters(0, 0, new FirmwareVersion(1, 1, 1),
0, 0, 0, 0, hasAndroidInjector); new FirmwareVersion(2, 2, 2), timeZone);
assertEquals(now, podSessionState.getTime()); assertEquals(now, podStateManager.getTime());
assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podSessionState.getScheduleOffset()); assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podStateManager.getScheduleOffset());
} }
@Test @Test
@ -44,22 +44,21 @@ public class PodSessionStateTest {
DateTimeZone.setDefault(timeZone); DateTimeZone.setDefault(timeZone);
DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone); DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone);
DateTime initialized = now.minus(Duration.standardDays(1));
DateTimeUtils.setCurrentMillisFixed(now.getMillis()); DateTimeUtils.setCurrentMillisFixed(now.getMillis());
PodSessionState podSessionState = new PodSessionState(timeZone, 0x0, AapsPodStateManager podStateManager = new AapsPodStateManager(hasAndroidInjector);
new FirmwareVersion(1, 1, 1), podStateManager.initState(0x0);
new FirmwareVersion(2, 2, 2), podStateManager.setPairingParameters(0, 0, new FirmwareVersion(1, 1, 1),
0, 0, 0, 0, hasAndroidInjector); new FirmwareVersion(2, 2, 2), timeZone);
DateTimeZone newTimeZone = DateTimeZone.forOffsetHours(2); DateTimeZone newTimeZone = DateTimeZone.forOffsetHours(2);
DateTimeZone.setDefault(newTimeZone); DateTimeZone.setDefault(newTimeZone);
// The system time zone has been updated, but the pod session state's time zone hasn't // The system time zone has been updated, but the pod session state's time zone hasn't
// So the pods time should not have been changed // So the pods time should not have been changed
assertEquals(now, podSessionState.getTime()); assertEquals(now, podStateManager.getTime());
assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podSessionState.getScheduleOffset()); assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podStateManager.getScheduleOffset());
} }
@Test @Test
@ -69,23 +68,22 @@ public class PodSessionStateTest {
DateTimeZone.setDefault(timeZone); DateTimeZone.setDefault(timeZone);
DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone); DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone);
DateTime initialized = now.minus(Duration.standardDays(1));
DateTimeUtils.setCurrentMillisFixed(now.getMillis()); DateTimeUtils.setCurrentMillisFixed(now.getMillis());
PodSessionState podSessionState = new PodSessionState(timeZone, 0x0, AapsPodStateManager podStateManager = new AapsPodStateManager(hasAndroidInjector);
new FirmwareVersion(1, 1, 1), podStateManager.initState(0x0);
new FirmwareVersion(2, 2, 2), podStateManager.setPairingParameters(0, 0, new FirmwareVersion(1, 1, 1),
0, 0, 0, 0, hasAndroidInjector); new FirmwareVersion(2, 2, 2), timeZone);
DateTimeZone newTimeZone = DateTimeZone.forOffsetHours(2); DateTimeZone newTimeZone = DateTimeZone.forOffsetHours(2);
DateTimeZone.setDefault(newTimeZone); DateTimeZone.setDefault(newTimeZone);
podSessionState.setTimeZone(newTimeZone); podStateManager.setTimeZone(newTimeZone);
// Both the system time zone have been updated // Both the system time zone have been updated
// So the pods time should have been changed (to +2 hours) // So the pods time should have been changed (to +2 hours)
assertEquals(now.withZone(newTimeZone), podSessionState.getTime()); assertEquals(now.withZone(newTimeZone), podStateManager.getTime());
assertEquals(Duration.standardHours(3).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podSessionState.getScheduleOffset()); assertEquals(Duration.standardHours(3).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podStateManager.getScheduleOffset());
} }
@After @After