diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt index 447e901737..e458957fb9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector 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.PodManagementActivity import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.initpod.InitActionFragment @@ -35,7 +35,7 @@ abstract class OmnipodModule { // Data @ContributesAndroidInjector abstract fun omnipodUITaskProvider(): OmnipodUITask @ContributesAndroidInjector abstract fun initPodRefreshAction(): InitPodRefreshAction - @ContributesAndroidInjector abstract fun podSessionState(): PodSessionState + @ContributesAndroidInjector abstract fun podStateManager(): PodStateManager @ContributesAndroidInjector abstract fun initPodTask() : InitPodTask @ContributesAndroidInjector abstract fun initAapsPodStateManager() : AapsPodStateManager diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt index 667961be61..27b7558d62 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt @@ -263,20 +263,17 @@ class OmnipodFragment : DaggerFragment() { omnipodPumpStatus.podAvailable = false omnipodPumpStatus.podNumber == null } 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_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.podNumber == omnipodPumpStatus.podSessionState.address.toString() + omnipodPumpStatus.podNumber == omnipodPumpStatus.podStateManager.address.toString() } else { - omnipodPumpStatus.podLotNumber = "" + omnipodPumpStatus.podSessionState.lot + omnipodPumpStatus.podLotNumber = "" + omnipodPumpStatus.podStateManager.lot omnipodPumpStatus.podAvailable = true - omnipod_pod_address.text = omnipodPumpStatus.podSessionState.address.toString() - omnipod_pod_expiry.text = omnipodPumpStatus.podSessionState.expiryDateAsString - omnipodPumpStatus.podNumber = omnipodPumpStatus.podSessionState.address.toString() - - //pumpStatus.podSessionState = checkStatusSet(pumpStatus.podSessionState, - // OmnipodUtil.getPodSessionState()) as PodSessionState? + omnipod_pod_address.text = omnipodPumpStatus.podStateManager.address.toString() + omnipod_pod_expiry.text = omnipodPumpStatus.podStateManager.expiryDateAsString + omnipodPumpStatus.podNumber = omnipodPumpStatus.podStateManager.address.toString() var podDeviceState = omnipodPumpStatus.podDeviceState @@ -317,13 +314,13 @@ class OmnipodFragment : DaggerFragment() { } } - if (SetupProgress.COMPLETED.equals(omnipodPumpStatus.podSessionState.getSetupProgress())) { - if(omnipodPumpStatus.podSessionState.lastDeliveryStatus != null) { - stateText += " (last delivery status: " + omnipodPumpStatus.podSessionState.lastDeliveryStatus.name + ")" + if (SetupProgress.COMPLETED.equals(omnipodPumpStatus.podStateManager.getSetupProgress())) { + if(omnipodPumpStatus.podStateManager.lastDeliveryStatus != null) { + stateText += " (last delivery status: " + omnipodPumpStatus.podStateManager.lastDeliveryStatus.name + ")" } } else { - if(omnipodPumpStatus.podSessionState.setupProgress != null) { - stateText += " (setup progress: " + omnipodPumpStatus.podSessionState.setupProgress.name + ")" + if(omnipodPumpStatus.podStateManager.setupProgress != null) { + stateText += " (setup progress: " + omnipodPumpStatus.podStateManager.setupProgress.name + ")" } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java index 521db02a60..a7a0eba086 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java @@ -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.data.PumpStatus; 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.PumpType; 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.OmnipodPumpPluginInterface; 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.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUIComm; @@ -488,17 +487,17 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump public boolean isSuspended() { return (omnipodUtil.getDriverState() == OmnipodDriverState.Initalized_NoPod) || - (omnipodUtil.getPodSessionState() != null && omnipodUtil.getPodSessionState().isSuspended()); + (omnipodUtil.getPodStateManager() != null && omnipodUtil.getPodStateManager().isSuspended()); // return (pumpStatusLocal != null && !pumpStatusLocal.podAvailable) || -// (OmnipodUtil.getPodSessionState() != null && OmnipodUtil.getPodSessionState().isSuspended()); +// (OmnipodUtil.getPodStateManager() != null && OmnipodUtil.getPodStateManager().isSuspended()); // // TODO ddd // return (OmnipodUtil.getDriverState() == OmnipodDriverState.Initalized_NoPod) || -// (OmnipodUtil.getPodSessionState() != null && OmnipodUtil.getPodSessionState().isSuspended()); +// (OmnipodUtil.getPodStateManager() != null && OmnipodUtil.getPodStateManager().isSuspended()); // // return (pumpStatusLocal != null && !pumpStatusLocal.podAvailable) || -// (OmnipodUtil.getPodSessionState() != null && OmnipodUtil.getPodSessionState().isSuspended()); +// (OmnipodUtil.getPodStateManager() != null && OmnipodUtil.getPodStateManager().isSuspended()); } @Override @@ -622,18 +621,9 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump setRefreshButtonEnabled(false); - PodSessionState podSessionState = null; - - if (omnipodUtil.getPodSessionState() != null) { - podSessionState = omnipodUtil.getPodSessionState(); - } else { - podSessionState = omnipodUtil.loadSessionState(); - } - - - if (podSessionState != null) { - aapsLogger.debug(LTag.PUMP, "PodSessionState (saved): " + podSessionState); + PodStateManager podStateManager = omnipodUtil.getPodStateManager(); + if (podStateManager != null) { if (!isRefresh) { pumpState = PumpDriverState.Initialized; } @@ -642,7 +632,7 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump getPodPumpStatus(); } else { - aapsLogger.debug(LTag.PUMP, "No PodSessionState found. Pod probably not running."); + aapsLogger.error(LTag.PUMP, "No PodStateManager found"); omnipodUtil.setDriverState(OmnipodDriverState.Initalized_NoPod); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java index e77befd258..6968532adb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java @@ -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.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; 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.exception.CommunicationException; 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.PacketType; 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.exception.OmnipodException; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; @@ -103,13 +100,13 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { this.omnipodPumpStatus.setPumpDeviceState(pumpDeviceState); } - public T sendCommand(Class responseClass, PodState podState, MessageBlock command) { - return sendCommand(responseClass, podState, command, true); + public T sendCommand(Class responseClass, PodStateManager podStateManager, MessageBlock command) { + return sendCommand(responseClass, podStateManager, command, true); } - public T sendCommand(Class responseClass, PodState podState, MessageBlock command, boolean automaticallyResyncNone) { - OmnipodMessage message = new OmnipodMessage(podState.getAddress(), Collections.singletonList(command), podState.getMessageNumber()); - return exchangeMessages(responseClass, podState, message, automaticallyResyncNone); + public T sendCommand(Class responseClass, PodStateManager podStateManager, MessageBlock command, boolean automaticallyResyncNone) { + OmnipodMessage message = new OmnipodMessage(podStateManager.getAddress(), Collections.singletonList(command), podStateManager.getMessageNumber()); + return exchangeMessages(responseClass, podStateManager, message, automaticallyResyncNone); } // Convenience method @@ -117,33 +114,33 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { return action.execute(this); } - public T exchangeMessages(Class responseClass, PodState podState, OmnipodMessage message) { - return exchangeMessages(responseClass, podState, message, true); + public T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message) { + return exchangeMessages(responseClass, podStateManager, message, true); } - public T exchangeMessages(Class responseClass, PodState podState, OmnipodMessage message, boolean automaticallyResyncNonce) { - return exchangeMessages(responseClass, podState, message, null, null, automaticallyResyncNonce); + public T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message, boolean automaticallyResyncNonce) { + return exchangeMessages(responseClass, podStateManager, message, null, null, automaticallyResyncNonce); } - public synchronized T exchangeMessages(Class responseClass, PodState podState, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { - return exchangeMessages(responseClass, podState, message, addressOverride, ackAddressOverride, true); + public synchronized T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { + return exchangeMessages(responseClass, podStateManager, message, addressOverride, ackAddressOverride, true); } - public synchronized T exchangeMessages(Class responseClass, PodState podState, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) { + public synchronized T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) { - aapsLogger.debug(LTag.PUMPCOMM, "Exchanging OmnipodMessage [responseClass={}, podState={}, message={}, addressOverride={}, ackAddressOverride={}, automaticallyResyncNonce={}]: {}", // - responseClass.getSimpleName(), podState, message, addressOverride, ackAddressOverride, automaticallyResyncNonce, message); + aapsLogger.debug(LTag.PUMPCOMM, "Exchanging OmnipodMessage [responseClass={}, podStateManager={}, message={}, addressOverride={}, ackAddressOverride={}, automaticallyResyncNonce={}]: {}", // + responseClass.getSimpleName(), podStateManager, message, addressOverride, ackAddressOverride, automaticallyResyncNonce, message); for (int i = 0; 2 > i; i++) { - if (podState.hasNonceState() && message.isNonceResyncable()) { - podState.advanceToNextNonce(); + if (podStateManager.isPaired() && message.isNonceResyncable()) { + podStateManager.advanceToNextNonce(); } - MessageBlock responseMessageBlock = transportMessages(podState, message, addressOverride, ackAddressOverride); + MessageBlock responseMessageBlock = transportMessages(podStateManager, message, addressOverride, ackAddressOverride); if (responseMessageBlock instanceof StatusResponse) { - podState.updateFromStatusResponse((StatusResponse) responseMessageBlock); + podStateManager.updateFromStatusResponse((StatusResponse) responseMessageBlock); } if (responseClass.isInstance(responseMessageBlock)) { @@ -152,9 +149,9 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { if (responseMessageBlock.getType() == MessageBlockType.ERROR_RESPONSE) { ErrorResponse error = (ErrorResponse) responseMessageBlock; 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) { - message.resyncNonce(podState.getCurrentNonce()); + message.resyncNonce(podStateManager.getCurrentNonce()); } else { 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) { PodInfoFaultEvent faultEvent = ((PodInfoResponse) responseMessageBlock).getPodInfo(); - podState.setFaultEvent(faultEvent); + podStateManager.setFaultEvent(faultEvent); throw new PodFaultException(faultEvent); } else { throw new IllegalResponseException(responseClass.getSimpleName(), responseMessageBlock.getType()); @@ -174,13 +171,13 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { throw new NonceResyncException(); } - private MessageBlock transportMessages(PodState podState, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { - int packetAddress = podState.getAddress(); + private MessageBlock transportMessages(PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { + int packetAddress = podStateManager.getAddress(); if (addressOverride != null) { packetAddress = addressOverride; } - podState.increaseMessageNumber(); + podStateManager.increaseMessageNumber(); boolean firstPacket = true; byte[] encodedMessage; @@ -203,7 +200,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { OmnipodPacket response = null; while (encodedMessage.length > 0) { 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(); // getting the data remaining to be sent @@ -212,7 +209,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { try { // 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) { OmnipodException newException; if (ex instanceof OmnipodException) { @@ -245,15 +242,15 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { if (receivedMessage.getAddress() != message.getAddress()) { throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress()); } - if (receivedMessage.getSequenceNumber() != podState.getMessageNumber()) { - throw new IllegalMessageSequenceNumberException(podState.getMessageNumber(), receivedMessage.getSequenceNumber()); + if (receivedMessage.getSequenceNumber() != podStateManager.getMessageNumber()) { + throw new IllegalMessageSequenceNumberException(podStateManager.getMessageNumber(), receivedMessage.getSequenceNumber()); } } catch (NotEnoughDataException ex) { // Message is (probably) not complete yet - OmnipodPacket ackForCon = createAckPacket(podState, packetAddress, ackAddressOverride); + OmnipodPacket ackForCon = createAckPacket(podStateManager, packetAddress, ackAddressOverride); try { - OmnipodPacket conPacket = exchangePackets(podState, ackForCon, 3, 40); + OmnipodPacket conPacket = exchangePackets(podStateManager, ackForCon, 3, 40); if (conPacket.getPacketType() != PacketType.CON) { 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 messageBlocks = receivedMessage.getMessageBlocks(); @@ -281,24 +278,24 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { MessageBlock messageBlock = messageBlocks.get(0); if (messageBlock.getType() != MessageBlockType.ERROR_RESPONSE) { - podState.increaseMessageNumber(); + podStateManager.increaseMessageNumber(); } return messageBlock; } - private OmnipodPacket createAckPacket(PodState podState, Integer packetAddress, Integer messageAddress) { + private OmnipodPacket createAckPacket(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { if (packetAddress == null) { - packetAddress = podState.getAddress(); + packetAddress = podStateManager.getAddress(); } 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) { - OmnipodPacket ack = createAckPacket(podState, packetAddress, messageAddress); + private void ackUntilQuiet(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { + OmnipodPacket ack = createAckPacket(podStateManager, packetAddress, messageAddress); boolean quiet = false; while (!quiet) try { 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); } - podState.increasePacketNumber(); + podStateManager.increasePacketNumber(); } - private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet) { - return exchangePackets(podState, packet, 0, 333, 9000, 127); + private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet) { + return exchangePackets(podStateManager, packet, 0, 333, 9000, 127); } - private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet, int repeatCount, int preambleExtensionMilliseconds) { - return exchangePackets(podState, packet, repeatCount, 333, 9000, preambleExtensionMilliseconds); + private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int 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; - podState.increasePacketNumber(); + podStateManager.increasePacketNumber(); while (System.currentTimeMillis() < timeoutTime) { OmnipodPacket response = null; @@ -353,13 +350,13 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { continue; } - if (response.getSequenceNumber() != podState.getPacketNumber()) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Packet sequence number " + response.getSequenceNumber() + " does not match " + podState.getPacketNumber()); + if (response.getSequenceNumber() != podStateManager.getPacketNumber()) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Packet sequence number " + response.getSequenceNumber() + " does not match " + podStateManager.getPacketNumber()); continue; } // Once we have verification that the POD heard us, we can increment our counters - podState.increasePacketNumber(); + podStateManager.increasePacketNumber(); return response; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java index c1a4cd57c5..6c12b27ab2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java @@ -5,7 +5,6 @@ import org.joda.time.DateTimeZone; import org.joda.time.Duration; import java.util.EnumSet; -import java.util.Random; import java.util.TimeZone; 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.SetupProgress; 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.PodStateChangedHandler; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -55,49 +53,45 @@ import io.reactivex.subjects.SingleSubject; public class OmnipodManager { private static final int ACTION_VERIFICATION_TRIES = 3; - protected final OmnipodCommunicationManager communicationService; - private final PodStateChangedHandler podStateChangedHandler; - protected PodSessionState podState; + private final OmnipodCommunicationManager communicationService; + private PodStateManager podStateManager; private ActiveBolusData activeBolusData; private final Object bolusDataMutex = new Object(); private AAPSLogger aapsLogger; - private SP sp; public OmnipodManager(AAPSLogger aapsLogger, SP sp, OmnipodCommunicationManager communicationService, - PodSessionState podState, - PodStateChangedHandler podStateChangedHandler) { + PodStateManager podStateManager) { if (communicationService == null) { throw new IllegalArgumentException("Communication service cannot be null"); } - this.aapsLogger = aapsLogger; - this.sp = sp; - this.communicationService = communicationService; - if (podState != null) { - podState.setStateChangedHandler(podStateChangedHandler); + if (podStateManager == null) { + throw new IllegalArgumentException("Pod State Manager can not be null"); } - this.podState = podState; - this.podStateChangedHandler = podStateChangedHandler; + this.aapsLogger = aapsLogger; + this.communicationService = communicationService; + + this.podStateManager = podStateManager; } - public synchronized Single pairAndPrime(int address) { + public synchronized Single pairAndPrime() { logStartingCommandExecution("pairAndPrime"); 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 - podState = communicationService.executeAction( - new AssignAddressAction(podStateChangedHandler, address)); + communicationService.executeAction( + new AssignAddressAction(podStateManager)); - communicationService.executeAction(new SetupPodAction(podState)); - } else if (SetupProgress.PRIMING.isBefore(podState.getSetupProgress())) { - throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podState.getSetupProgress()); + communicationService.executeAction(new SetupPodAction(podStateManager)); + } else if (SetupProgress.PRIMING.isBefore(podStateManager.getSetupProgress())) { + throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podStateManager.getSetupProgress()); } - communicationService.executeAction(new PrimeAction(new PrimeService(), podState)); + communicationService.executeAction(new PrimeAction(new PrimeService(), podStateManager)); } finally { logCommandExecutionFinished("pairAndPrime"); } @@ -106,21 +100,21 @@ public class OmnipodManager { return Single.timer(delayInSeconds, TimeUnit.SECONDS) // .map(o -> verifySetupAction(statusResponse -> - PrimeAction.updatePrimingStatus(podState, statusResponse, aapsLogger), SetupProgress.PRIMING_FINISHED)) // + PrimeAction.updatePrimingStatus(podStateManager, statusResponse, aapsLogger), SetupProgress.PRIMING_FINISHED)) // .observeOn(Schedulers.io()); } public synchronized Single insertCannula(BasalSchedule basalSchedule) { - if (podState == null || podState.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) { - throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, podState == null ? null : podState.getSetupProgress()); - } else if (podState.getSetupProgress().isAfter(SetupProgress.CANNULA_INSERTING)) { - throw new IllegalSetupProgressException(SetupProgress.CANNULA_INSERTING, podState.getSetupProgress()); + if (!podStateManager.hasState() || podStateManager.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) { + throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, !podStateManager.hasState() ? null : podStateManager.getSetupProgress()); + } else if (podStateManager.getSetupProgress().isAfter(SetupProgress.CANNULA_INSERTING)) { + throw new IllegalSetupProgressException(SetupProgress.CANNULA_INSERTING, podStateManager.getSetupProgress()); } logStartingCommandExecution("insertCannula [basalSchedule=" + basalSchedule + "]"); try { - communicationService.executeAction(new InsertCannulaAction(new InsertCannulaService(), podState, basalSchedule)); + communicationService.executeAction(new InsertCannulaAction(new InsertCannulaService(), podStateManager, basalSchedule)); } finally { logCommandExecutionFinished("insertCannula"); } @@ -129,19 +123,19 @@ public class OmnipodManager { return Single.timer(delayInSeconds, TimeUnit.SECONDS) // .map(o -> verifySetupAction(statusResponse -> - InsertCannulaAction.updateCannulaInsertionStatus(podState, statusResponse, aapsLogger), SetupProgress.COMPLETED)) // + InsertCannulaAction.updateCannulaInsertionStatus(podStateManager, statusResponse, aapsLogger), SetupProgress.COMPLETED)) // .observeOn(Schedulers.io()); } public synchronized StatusResponse getPodStatus() { - if (podState == null) { + if (!podStateManager.hasState()) { throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, null); } logStartingCommandExecution("getPodStatus"); try { - return communicationService.executeAction(new GetStatusAction(podState)); + return communicationService.executeAction(new GetStatusAction(podStateManager)); } finally { logCommandExecutionFinished("getPodStatus"); } @@ -153,7 +147,7 @@ public class OmnipodManager { logStartingCommandExecution("getPodInfo"); try { - return communicationService.executeAction(new GetPodInfoAction(podState, podInfoType)); + return communicationService.executeAction(new GetPodInfoAction(podStateManager, podInfoType)); } finally { logCommandExecutionFinished("getPodInfo"); } @@ -165,7 +159,7 @@ public class OmnipodManager { logStartingCommandExecution("acknowledgeAlerts"); try { - return executeAndVerify(() -> communicationService.executeAction(new AcknowledgeAlertsAction(podState, podState.getActiveAlerts()))); + return executeAndVerify(() -> communicationService.executeAction(new AcknowledgeAlertsAction(podStateManager, podStateManager.getActiveAlerts()))); } finally { logCommandExecutionFinished("acknowledgeAlerts"); } @@ -187,8 +181,8 @@ public class OmnipodManager { try { try { - return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podState, schedule, - false, podState.getScheduleOffset(), acknowledgementBeep))); + return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podStateManager, schedule, + false, podStateManager.getScheduleOffset(), acknowledgementBeep))); } catch (OmnipodException ex) { // 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 @@ -215,7 +209,7 @@ public class OmnipodManager { try { return executeAndVerify(() -> communicationService.executeAction(new SetTempBasalAction( - podState, rate, duration, + podStateManager, rate, duration, acknowledgementBeep, completionBeep))); } catch (OmnipodException ex) { // Treat all exceptions as uncertain failures, because all delivery has been suspended here. @@ -238,7 +232,7 @@ public class OmnipodManager { try { 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()); return statusResponse; }); @@ -258,7 +252,7 @@ public class OmnipodManager { CommandDeliveryStatus commandDeliveryStatus = CommandDeliveryStatus.SUCCESS; try { - executeAndVerify(() -> communicationService.executeAction(new BolusAction(podState, units, acknowledgementBeep, completionBeep))); + executeAndVerify(() -> communicationService.executeAction(new BolusAction(podStateManager, units, acknowledgementBeep, completionBeep))); } catch (OmnipodException ex) { if (ex.isCertainFailure()) { throw ex; @@ -339,7 +333,7 @@ public class OmnipodManager { synchronized (bolusDataMutex) { 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 + "]"); @@ -374,8 +368,8 @@ public class OmnipodManager { logStartingCommandExecution("resumeDelivery"); try { - return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podState, podState.getBasalSchedule(), - false, podState.getScheduleOffset(), acknowledgementBeep))); + return executeAndVerify(() -> communicationService.executeAction(new SetBasalScheduleAction(podStateManager, podStateManager.getBasalSchedule(), + false, podStateManager.getScheduleOffset(), acknowledgementBeep))); } finally { logCommandExecutionFinished("resumeDelivery"); } @@ -395,18 +389,18 @@ public class OmnipodManager { throw ex; } - DateTimeZone oldTimeZone = podState.getTimeZone(); + DateTimeZone oldTimeZone = podStateManager.getTimeZone(); try { // Joda seems to cache the default time zone, so we use the JVM's 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) { // 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 - podState.setTimeZone(oldTimeZone); + podStateManager.setTimeZone(oldTimeZone); ex.setCertainFailure(false); throw ex; } finally { @@ -415,7 +409,7 @@ public class OmnipodManager { } public synchronized void deactivatePod() { - if (podState == null) { + if (!podStateManager.isPaired()) { throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, null); } @@ -424,7 +418,7 @@ public class OmnipodManager { // Try to get pulse log for diagnostics // FIXME replace by storing to file 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(); aapsLogger.info(LTag.PUMPBTCOMM, "Retrieved pulse log from the pod: {}", pulseLogInfo.toString()); } catch (Exception ex) { @@ -433,20 +427,14 @@ public class OmnipodManager { try { // 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) { aapsLogger.info(LTag.PUMPBTCOMM, "Ignoring PodFaultException in deactivatePod", ex); } finally { logCommandExecutionFinished("deactivatePod"); } - resetPodState(false); - } - - public void resetPodState(boolean forcedByUser) { - aapsLogger.warn(LTag.PUMPBTCOMM, "resetPodState has been called. forcedByUser={}", forcedByUser); - podState = null; - sp.remove(OmnipodConst.Prefs.PodState); + podStateManager.removeState(); } public OmnipodCommunicationManager getCommunicationService() { @@ -454,11 +442,11 @@ public class OmnipodManager { } public DateTime getTime() { - return podState.getTime(); + return podStateManager.getTime(); } public boolean isReadyForDelivery() { - return podState != null && podState.getSetupProgress() == SetupProgress.COMPLETED; + return podStateManager.isPaired() && podStateManager.getSetupProgress() == SetupProgress.COMPLETED; } public boolean hasActiveBolus() { @@ -467,13 +455,12 @@ public class OmnipodManager { } } - // FIXME this is dirty, we should not expose the original pod state - public PodSessionState getPodState() { - return this.podState; + public PodStateManager getPodStateManager() { + return this.podStateManager; } public String getPodStateAsString() { - return podState == null ? "null" : podState.toString(); + return podStateManager.hasState() ? podStateManager.toString() : "null"; } // Only works for commands with nonce resyncable message blocks @@ -489,8 +476,8 @@ public class OmnipodManager { try { logStartingCommandExecution("verifyCommand"); - StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podState, - new CancelDeliveryCommand(podState.getCurrentNonce(), BeepType.NO_BEEP, DeliveryType.NONE), false); + StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podStateManager, + 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); return statusResponse; @@ -517,7 +504,7 @@ public class OmnipodManager { private void assertReadyForDelivery() { 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; for (int i = 0; ACTION_VERIFICATION_TRIES > i; i++) { try { - StatusResponse delayedStatusResponse = communicationService.executeAction(new GetStatusAction(podState)); + StatusResponse delayedStatusResponse = communicationService.executeAction(new GetStatusAction(podStateManager)); setupActionResponseHandler.accept(delayedStatusResponse); - if (podState.getSetupProgress().equals(expectedSetupProgress)) { + if (podStateManager.getSetupProgress().equals(expectedSetupProgress)) { result = new SetupActionResult(SetupActionResult.ResultType.SUCCESS); break; } else { result = new SetupActionResult(SetupActionResult.ResultType.FAILURE) // - .setupProgress(podState.getSetupProgress()); + .setupProgress(podStateManager.getSetupProgress()); break; } } catch (Exception ex) { @@ -564,15 +551,6 @@ public class OmnipodManager { 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 { private final CommandDeliveryStatus commandDeliveryStatus; private final SingleSubject deliveryResultSubject; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AcknowledgeAlertsAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AcknowledgeAlertsAction.java index facdb4b2d5..3ffbc5942f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AcknowledgeAlertsAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AcknowledgeAlertsAction.java @@ -3,37 +3,37 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; import java.util.Collections; 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.response.StatusResponse; 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.state.PodSessionState; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.ActionInitializationException; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; public class AcknowledgeAlertsAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final AlertSet alerts; - public AcknowledgeAlertsAction(PodSessionState podState, AlertSet alerts) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + public AcknowledgeAlertsAction(PodStateManager podStateManager, AlertSet alerts) { + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (alerts == null) { throw new ActionInitializationException("Alert set can not be null"); } else if (alerts.size() == 0) { throw new ActionInitializationException("Alert set can not be empty"); } - this.podState = podState; + this.podStateManager = podStateManager; this.alerts = alerts; } - public AcknowledgeAlertsAction(PodSessionState podState, AlertSlot alertSlot) { - this(podState, new AlertSet(Collections.singletonList(alertSlot))); + public AcknowledgeAlertsAction(PodStateManager podStateManager, AlertSlot alertSlot) { + this(podStateManager, new AlertSet(Collections.singletonList(alertSlot))); } @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { - return communicationService.sendCommand(StatusResponse.class, podState, - new AcknowledgeAlertsCommand(podState.getCurrentNonce(), alerts)); + return communicationService.sendCommand(StatusResponse.class, podStateManager, + new AcknowledgeAlertsCommand(podStateManager.getCurrentNonce(), alerts)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java index b5e46e38b5..91590185e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; import org.joda.time.DateTimeZone; 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.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.command.AssignAddressCommand; 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.PodSetupState; -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.util.OmnipodConst; -public class AssignAddressAction implements OmnipodAction { - private final int address; - private final PodStateChangedHandler podStateChangedHandler; +public class AssignAddressAction implements OmnipodAction { + private final PodStateManager podStateManager; - public AssignAddressAction(PodStateChangedHandler podStateChangedHandler, int address) { - this.address = address; - this.podStateChangedHandler = podStateChangedHandler; + public AssignAddressAction(PodStateManager podStateManager) { + if (podStateManager == null) { + throw new IllegalArgumentException("podStateManager can not be null"); + } + this.podStateManager = podStateManager; } @Override - public PodSessionState execute(OmnipodCommunicationManager communicationService) { - PodSetupState setupState = new PodSetupState(address, 0x00, 0x00); + public VersionResponse execute(OmnipodCommunicationManager communicationService) { + 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, - Collections.singletonList(assignAddress), setupState.getMessageNumber()); + Collections.singletonList(assignAddress), podStateManager.getMessageNumber()); - VersionResponse assignAddressResponse = communicationService.exchangeMessages(VersionResponse.class, setupState, assignAddressMessage, - OmnipodConst.DEFAULT_ADDRESS, setupState.getAddress()); + VersionResponse assignAddressResponse = communicationService.exchangeMessages(VersionResponse.class, podStateManager, assignAddressMessage, + OmnipodConst.DEFAULT_ADDRESS, podStateManager.getAddress()); if (!assignAddressResponse.isAssignAddressVersionResponse()) { throw new IllegalVersionResponseTypeException("assignAddress", "setupPod"); } - if (assignAddressResponse.getAddress() != address) { - throw new IllegalMessageAddressException(address, assignAddressResponse.getAddress()); + if (assignAddressResponse.getAddress() != podStateManager.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(), - 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 + return assignAddressResponse; + } - 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); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/BolusAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/BolusAction.java index 14cee38962..c57d2b3615 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/BolusAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/BolusAction.java @@ -5,49 +5,49 @@ import org.joda.time.Duration; import java.util.Arrays; 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.command.BolusExtraCommand; 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.defs.schedule.BolusDeliverySchedule; -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.defs.state.PodStateManager; public class BolusAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final double units; private final Duration timeBetweenPulses; private final boolean acknowledgementBeep; private final boolean completionBeep; - public BolusAction(PodSessionState podState, double units, Duration timeBetweenPulses, + public BolusAction(PodStateManager podStateManager, double units, Duration timeBetweenPulses, boolean acknowledgementBeep, boolean completionBeep) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (timeBetweenPulses == null) { throw new ActionInitializationException("Time between pulses cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.units = units; this.timeBetweenPulses = timeBetweenPulses; this.acknowledgementBeep = acknowledgementBeep; this.completionBeep = completionBeep; } - public BolusAction(PodSessionState podState, double units, boolean acknowledgementBeep, boolean completionBeep) { - this(podState, units, Duration.standardSeconds(2), acknowledgementBeep, completionBeep); + public BolusAction(PodStateManager podStateManager, double units, boolean acknowledgementBeep, boolean completionBeep) { + this(podStateManager, units, Duration.standardSeconds(2), acknowledgementBeep, completionBeep); } @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { BolusDeliverySchedule bolusDeliverySchedule = new BolusDeliverySchedule(units, timeBetweenPulses); SetInsulinScheduleCommand setInsulinScheduleCommand = new SetInsulinScheduleCommand( - podState.getCurrentNonce(), bolusDeliverySchedule); + podStateManager.getCurrentNonce(), bolusDeliverySchedule); BolusExtraCommand bolusExtraCommand = new BolusExtraCommand(units, timeBetweenPulses, acknowledgementBeep, completionBeep); - OmnipodMessage primeBolusMessage = new OmnipodMessage(podState.getAddress(), - Arrays.asList(setInsulinScheduleCommand, bolusExtraCommand), podState.getMessageNumber()); - return communicationService.exchangeMessages(StatusResponse.class, podState, primeBolusMessage); + OmnipodMessage primeBolusMessage = new OmnipodMessage(podStateManager.getAddress(), + Arrays.asList(setInsulinScheduleCommand, bolusExtraCommand), podStateManager.getMessageNumber()); + return communicationService.exchangeMessages(StatusResponse.class, podStateManager, primeBolusMessage); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/CancelDeliveryAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/CancelDeliveryAction.java index ca713bcab6..9df030fec5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/CancelDeliveryAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/CancelDeliveryAction.java @@ -5,29 +5,29 @@ import java.util.EnumSet; import java.util.List; 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.OmnipodMessage; 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.defs.BeepType; 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.comm.exception.ActionInitializationException; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; public class CancelDeliveryAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final EnumSet deliveryTypes; private final boolean acknowledgementBeep; - public CancelDeliveryAction(PodSessionState podState, EnumSet deliveryTypes, + public CancelDeliveryAction(PodStateManager podStateManager, EnumSet deliveryTypes, boolean acknowledgementBeep) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (deliveryTypes == null) { throw new ActionInitializationException("Delivery types cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.deliveryTypes = deliveryTypes; this.acknowledgementBeep = acknowledgementBeep; } @@ -43,14 +43,14 @@ public class CancelDeliveryAction implements OmnipodAction { EnumSet deliveryTypeWithBeep = EnumSet.of(deliveryTypeList.remove(deliveryTypeList.size() - 1)); EnumSet deliveryTypesWithoutBeep = EnumSet.copyOf(deliveryTypeList); - messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), BeepType.NO_BEEP, deliveryTypesWithoutBeep)); - messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), BeepType.BEEP, deliveryTypeWithBeep)); + messageBlocks.add(new CancelDeliveryCommand(podStateManager.getCurrentNonce(), BeepType.NO_BEEP, deliveryTypesWithoutBeep)); + messageBlocks.add(new CancelDeliveryCommand(podStateManager.getCurrentNonce(), BeepType.BEEP, deliveryTypeWithBeep)); } else { - messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), + messageBlocks.add(new CancelDeliveryCommand(podStateManager.getCurrentNonce(), acknowledgementBeep && deliveryTypes.size() == 1 ? BeepType.BEEP : BeepType.NO_BEEP, deliveryTypes)); } - return communicationService.exchangeMessages(StatusResponse.class, podState, - new OmnipodMessage(podState.getAddress(), messageBlocks, podState.getMessageNumber())); + return communicationService.exchangeMessages(StatusResponse.class, podStateManager, + new OmnipodMessage(podStateManager.getAddress(), messageBlocks, podStateManager.getMessageNumber())); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigureAlertsAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigureAlertsAction.java index b44fc092a8..e5f93e97f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigureAlertsAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigureAlertsAction.java @@ -3,33 +3,33 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; import java.util.List; 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.response.StatusResponse; 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.comm.exception.ActionInitializationException; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; public class ConfigureAlertsAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final List alertConfigurations; - public ConfigureAlertsAction(PodSessionState podState, List alertConfigurations) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + public ConfigureAlertsAction(PodStateManager podStateManager, List alertConfigurations) { + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (alertConfigurations == null) { throw new ActionInitializationException("Alert configurations cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.alertConfigurations = alertConfigurations; } @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { - ConfigureAlertsCommand configureAlertsCommand = new ConfigureAlertsCommand(podState.getCurrentNonce(), alertConfigurations); - StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podState, configureAlertsCommand); + ConfigureAlertsCommand configureAlertsCommand = new ConfigureAlertsCommand(podStateManager.getCurrentNonce(), alertConfigurations); + StatusResponse statusResponse = communicationService.sendCommand(StatusResponse.class, podStateManager, configureAlertsCommand); for (AlertConfiguration alertConfiguration : alertConfigurations) { - podState.putConfiguredAlert(alertConfiguration.getAlertSlot(), alertConfiguration.getAlertType()); + podStateManager.putConfiguredAlert(alertConfiguration.getAlertSlot(), alertConfiguration.getAlertType()); } return statusResponse; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/DeactivatePodAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/DeactivatePodAction.java index 01162ef434..7d1645c473 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/DeactivatePodAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/DeactivatePodAction.java @@ -3,36 +3,36 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; import java.util.EnumSet; 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.response.StatusResponse; 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.comm.exception.ActionInitializationException; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.PodFaultException; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; public class DeactivatePodAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final boolean acknowledgementBeep; - public DeactivatePodAction(PodSessionState podState, boolean acknowledgementBeep) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + public DeactivatePodAction(PodStateManager podStateManager, boolean acknowledgementBeep) { + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.acknowledgementBeep = acknowledgementBeep; } @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { - if (!podState.isSuspended() && !podState.hasFaultEvent()) { + if (!podStateManager.isSuspended() && !podStateManager.hasFaultEvent()) { try { - communicationService.executeAction(new CancelDeliveryAction(podState, + communicationService.executeAction(new CancelDeliveryAction(podStateManager, EnumSet.allOf(DeliveryType.class), acknowledgementBeep)); - } catch(PodFaultException ex) { + } catch (PodFaultException ex) { // Ignore } } - return communicationService.sendCommand(StatusResponse.class, podState, new DeactivatePodCommand(podState.getCurrentNonce())); + return communicationService.sendCommand(StatusResponse.class, podStateManager, new DeactivatePodCommand(podStateManager.getCurrentNonce())); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetPodInfoAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetPodInfoAction.java index 0eef011607..a082ca47d8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetPodInfoAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetPodInfoAction.java @@ -1,29 +1,29 @@ 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.exception.ActionInitializationException; 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.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.defs.state.PodStateManager; public class GetPodInfoAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final PodInfoType podInfoType; - public GetPodInfoAction(PodSessionState podState, PodInfoType podInfoType) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + public GetPodInfoAction(PodStateManager podStateManager, PodInfoType podInfoType) { + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (podInfoType == null) { throw new ActionInitializationException("Pod info type cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.podInfoType = podInfoType; } @Override public PodInfoResponse execute(OmnipodCommunicationManager communicationService) { - return communicationService.sendCommand(PodInfoResponse.class, podState, new GetStatusCommand(podInfoType)); + return communicationService.sendCommand(PodInfoResponse.class, podStateManager, new GetStatusCommand(podInfoType)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetStatusAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetStatusAction.java index dfcc1fe043..35431cea8b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetStatusAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/GetStatusAction.java @@ -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.response.StatusResponse; 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.defs.state.PodStateManager; public class GetStatusAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; - public GetStatusAction(PodSessionState podState) { + public GetStatusAction(PodStateManager podState) { 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 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)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/InsertCannulaAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/InsertCannulaAction.java index 9a433ab86a..559b41e109 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/InsertCannulaAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/InsertCannulaAction.java @@ -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.defs.SetupProgress; 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 { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final InsertCannulaService service; private final BasalSchedule initialBasalSchedule; - public InsertCannulaAction(InsertCannulaService insertCannulaService, PodSessionState podState, BasalSchedule initialBasalSchedule) { + public InsertCannulaAction(InsertCannulaService insertCannulaService, PodStateManager podStateManager, BasalSchedule initialBasalSchedule) { if (insertCannulaService == null) { throw new ActionInitializationException("Insert cannula service cannot be null"); } - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (initialBasalSchedule == null) { throw new ActionInitializationException("Initial basal schedule cannot be null"); } this.service = insertCannulaService; - this.podState = podState; + this.podStateManager = podStateManager; this.initialBasalSchedule = initialBasalSchedule; } - public static void updateCannulaInsertionStatus(PodSessionState podState, StatusResponse statusResponse, AAPSLogger aapsLogger) { - if (podState.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING) && + public static void updateCannulaInsertionStatus(PodStateManager podStateManager, StatusResponse statusResponse, AAPSLogger aapsLogger) { + if (podStateManager.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING) && statusResponse.getPodProgressStatus().isReadyForDelivery()) { aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from CANNULA_INSERTING to COMPLETED"); - podState.setSetupProgress(SetupProgress.COMPLETED); + podStateManager.setSetupProgress(SetupProgress.COMPLETED); } } @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { - if (podState.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) { - throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, podState.getSetupProgress()); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.PRIMING_FINISHED)) { + throw new IllegalSetupProgressException(SetupProgress.PRIMING_FINISHED, podStateManager.getSetupProgress()); } - if (podState.getSetupProgress().isBefore(SetupProgress.INITIAL_BASAL_SCHEDULE_SET)) { - service.programInitialBasalSchedule(communicationService, podState, initialBasalSchedule); - podState.setSetupProgress(SetupProgress.INITIAL_BASAL_SCHEDULE_SET); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.INITIAL_BASAL_SCHEDULE_SET)) { + service.programInitialBasalSchedule(communicationService, podStateManager, initialBasalSchedule); + podStateManager.setSetupProgress(SetupProgress.INITIAL_BASAL_SCHEDULE_SET); } - if (podState.getSetupProgress().isBefore(SetupProgress.STARTING_INSERT_CANNULA)) { - service.executeExpirationRemindersAlertCommand(communicationService, podState); - podState.setSetupProgress(SetupProgress.STARTING_INSERT_CANNULA); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.STARTING_INSERT_CANNULA)) { + service.executeExpirationRemindersAlertCommand(communicationService, podStateManager); + podStateManager.setSetupProgress(SetupProgress.STARTING_INSERT_CANNULA); } - if (podState.getSetupProgress().isBefore(SetupProgress.CANNULA_INSERTING)) { - StatusResponse statusResponse = service.executeInsertionBolusCommand(communicationService, podState); - podState.setSetupProgress(SetupProgress.CANNULA_INSERTING); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.CANNULA_INSERTING)) { + StatusResponse statusResponse = service.executeInsertionBolusCommand(communicationService, podStateManager); + podStateManager.setSetupProgress(SetupProgress.CANNULA_INSERTING); return statusResponse; - } else if (podState.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING)) { + } else if (podStateManager.getSetupProgress().equals(SetupProgress.CANNULA_INSERTING)) { // Check status - StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podState)); - updateCannulaInsertionStatus(podState, statusResponse, communicationService.aapsLogger); + StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podStateManager)); + updateCannulaInsertionStatus(podStateManager, statusResponse, communicationService.aapsLogger); return statusResponse; } else { - throw new IllegalSetupProgressException(null, podState.getSetupProgress()); + throw new IllegalSetupProgressException(null, podStateManager.getSetupProgress()); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java index 380eb0ce3d..a3056ac8a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java @@ -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.defs.PodProgressStatus; 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 { 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) { throw new ActionInitializationException("Prime service cannot be null"); } - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } this.service = primeService; - this.podState = podState; + this.podStateManager = podStateManager; } - public static void updatePrimingStatus(PodSessionState podState, StatusResponse statusResponse, AAPSLogger aapsLogger) { - if (podState.getSetupProgress().equals(SetupProgress.PRIMING) && statusResponse.getPodProgressStatus().equals(PodProgressStatus.PRIMING_COMPLETED)) { + public static void updatePrimingStatus(PodStateManager podStateManager, StatusResponse statusResponse, AAPSLogger aapsLogger) { + if (podStateManager.getSetupProgress().equals(SetupProgress.PRIMING) && statusResponse.getPodProgressStatus().equals(PodProgressStatus.PRIMING_COMPLETED)) { aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from PRIMING to PRIMING_FINISHED"); - podState.setSetupProgress(SetupProgress.PRIMING_FINISHED); + podStateManager.setSetupProgress(SetupProgress.PRIMING_FINISHED); } } @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { - if (podState.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) { - throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podState.getSetupProgress()); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) { + throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podStateManager.getSetupProgress()); } - if (podState.getSetupProgress().isBefore(SetupProgress.STARTING_PRIME)) { - service.executeDisableTab5Sub16FaultConfigCommand(communicationService, podState); - service.executeFinishSetupReminderAlertCommand(communicationService, podState); - podState.setSetupProgress(SetupProgress.STARTING_PRIME); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.STARTING_PRIME)) { + service.executeDisableTab5Sub16FaultConfigCommand(communicationService, podStateManager); + service.executeFinishSetupReminderAlertCommand(communicationService, podStateManager); + podStateManager.setSetupProgress(SetupProgress.STARTING_PRIME); } - if (podState.getSetupProgress().isBefore(SetupProgress.PRIMING)) { - StatusResponse statusResponse = service.executePrimeBolusCommand(communicationService, podState); - podState.setSetupProgress(SetupProgress.PRIMING); + if (podStateManager.getSetupProgress().isBefore(SetupProgress.PRIMING)) { + StatusResponse statusResponse = service.executePrimeBolusCommand(communicationService, podStateManager); + podStateManager.setSetupProgress(SetupProgress.PRIMING); return statusResponse; - } else if (podState.getSetupProgress().equals(SetupProgress.PRIMING)) { + } else if (podStateManager.getSetupProgress().equals(SetupProgress.PRIMING)) { // Check status - StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podState)); - updatePrimingStatus(podState, statusResponse, communicationService.aapsLogger); + StatusResponse statusResponse = communicationService.executeAction(new GetStatusAction(podStateManager)); + updatePrimingStatus(podStateManager, statusResponse, communicationService.aapsLogger); return statusResponse; } else { - throw new IllegalSetupProgressException(null, podState.getSetupProgress()); + throw new IllegalSetupProgressException(null, podStateManager.getSetupProgress()); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetBasalScheduleAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetBasalScheduleAction.java index 0c8ae7f8be..1a4fd91237 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetBasalScheduleAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetBasalScheduleAction.java @@ -5,25 +5,25 @@ import org.joda.time.Duration; import java.util.Arrays; 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.command.BasalScheduleExtraCommand; 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.defs.schedule.BasalSchedule; -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.defs.state.PodStateManager; public class SetBasalScheduleAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final BasalSchedule basalSchedule; private final boolean confidenceReminder; private final Duration scheduleOffset; private final boolean acknowledgementBeep; - public SetBasalScheduleAction(PodSessionState podState, BasalSchedule basalSchedule, + public SetBasalScheduleAction(PodStateManager podStateManager, BasalSchedule basalSchedule, boolean confidenceReminder, Duration scheduleOffset, boolean acknowledgementBeep) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (basalSchedule == null) { throw new ActionInitializationException("Basal schedule cannot be null"); @@ -31,7 +31,7 @@ public class SetBasalScheduleAction implements OmnipodAction { if (scheduleOffset == null) { throw new ActionInitializationException("Schedule offset cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.basalSchedule = basalSchedule; this.confidenceReminder = confidenceReminder; this.scheduleOffset = scheduleOffset; @@ -40,14 +40,14 @@ public class SetBasalScheduleAction implements OmnipodAction { @Override 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, acknowledgementBeep, confidenceReminder, Duration.ZERO); - OmnipodMessage basalMessage = new OmnipodMessage(podState.getAddress(), Arrays.asList(setBasal, extraCommand), - podState.getMessageNumber()); + OmnipodMessage basalMessage = new OmnipodMessage(podStateManager.getAddress(), Arrays.asList(setBasal, extraCommand), + podStateManager.getMessageNumber()); - StatusResponse statusResponse = communicationService.exchangeMessages(StatusResponse.class, podState, basalMessage); - podState.setBasalSchedule(basalSchedule); + StatusResponse statusResponse = communicationService.exchangeMessages(StatusResponse.class, podStateManager, basalMessage); + podStateManager.setBasalSchedule(basalSchedule); return statusResponse; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetTempBasalAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetTempBasalAction.java index d9406a3ed7..f316ece733 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetTempBasalAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetTempBasalAction.java @@ -6,30 +6,30 @@ import java.util.Arrays; import java.util.List; 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.OmnipodMessage; 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.response.StatusResponse; -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.defs.state.PodStateManager; public class SetTempBasalAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; private final double rate; private final Duration duration; private final boolean acknowledgementBeep; private final boolean completionBeep; - public SetTempBasalAction(PodSessionState podState, double rate, Duration duration, + public SetTempBasalAction(PodStateManager podStateManager, double rate, Duration duration, boolean acknowledgementBeep, boolean completionBeep) { - if (podState == null) { - throw new ActionInitializationException("Pod state cannot be null"); + if (podStateManager == null) { + throw new ActionInitializationException("Pod state manager cannot be null"); } if (duration == null) { throw new ActionInitializationException("Duration cannot be null"); } - this.podState = podState; + this.podStateManager = podStateManager; this.rate = rate; this.duration = duration; this.acknowledgementBeep = acknowledgementBeep; @@ -39,10 +39,10 @@ public class SetTempBasalAction implements OmnipodAction { @Override public StatusResponse execute(OmnipodCommunicationManager communicationService) { List messageBlocks = Arrays.asList( // - new SetInsulinScheduleCommand(podState.getCurrentNonce(), rate, duration), + new SetInsulinScheduleCommand(podStateManager.getCurrentNonce(), rate, duration), new TempBasalExtraCommand(rate, duration, acknowledgementBeep, completionBeep, Duration.ZERO)); - OmnipodMessage message = new OmnipodMessage(podState.getAddress(), messageBlocks, podState.getMessageNumber()); - return communicationService.exchangeMessages(StatusResponse.class, podState, message); + OmnipodMessage message = new OmnipodMessage(podStateManager.getAddress(), messageBlocks, podStateManager.getMessageNumber()); + return communicationService.exchangeMessages(StatusResponse.class, podStateManager, message); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java index 52979c91f3..a2ef13e488 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java @@ -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.PodProgressStatus; 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; public class SetupPodAction implements OmnipodAction { - private final PodSessionState podState; + private final PodStateManager podStateManager; - public SetupPodAction(PodSessionState podState) { - this.podState = podState; + public SetupPodAction(PodStateManager podStateManager) { + if(podStateManager == null) { + throw new IllegalArgumentException("Pod state manager can not be null"); + } + this.podStateManager = podStateManager; } @Override public VersionResponse execute(OmnipodCommunicationManager communicationService) { - if (!podState.getSetupProgress().equals(SetupProgress.ADDRESS_ASSIGNED)) { - throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, podState.getSetupProgress()); + if (!podStateManager.getSetupProgress().equals(SetupProgress.ADDRESS_ASSIGNED)) { + 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, - podState.getLot(), podState.getTid()); + SetupPodCommand setupPodCommand = new SetupPodCommand(podStateManager.getAddress(), activationDate, + podStateManager.getLot(), podStateManager.getTid()); OmnipodMessage message = new OmnipodMessage(OmnipodConst.DEFAULT_ADDRESS, - Collections.singletonList(setupPodCommand), podState.getMessageNumber()); + Collections.singletonList(setupPodCommand), podStateManager.getMessageNumber()); VersionResponse setupPodResponse; try { - setupPodResponse = communicationService.exchangeMessages(VersionResponse.class, podState, - message, OmnipodConst.DEFAULT_ADDRESS, podState.getAddress()); + setupPodResponse = communicationService.exchangeMessages(VersionResponse.class, podStateManager, + message, OmnipodConst.DEFAULT_ADDRESS, podStateManager.getAddress()); } catch (IllegalPacketTypeException ex) { if (PacketType.ACK.equals(ex.getActual())) { // Pod is already configured - podState.setSetupProgress(SetupProgress.POD_CONFIGURED); + podStateManager.setSetupProgress(SetupProgress.POD_CONFIGURED); return null; } throw ex; @@ -53,14 +56,14 @@ public class SetupPodAction implements OmnipodAction { if (!setupPodResponse.isSetupPodVersionResponse()) { throw new IllegalVersionResponseTypeException("setupPod", "assignAddress"); } - if (setupPodResponse.getAddress() != podState.getAddress()) { - throw new IllegalMessageAddressException(podState.getAddress(), setupPodResponse.getAddress()); + if (setupPodResponse.getAddress() != podStateManager.getAddress()) { + throw new IllegalMessageAddressException(podStateManager.getAddress(), setupPodResponse.getAddress()); } if (setupPodResponse.getPodProgressStatus() != PodProgressStatus.PAIRING_COMPLETED) { throw new IllegalPodProgressException(PodProgressStatus.PAIRING_COMPLETED, setupPodResponse.getPodProgressStatus()); } - podState.setSetupProgress(SetupProgress.POD_CONFIGURED); + podStateManager.setSetupProgress(SetupProgress.POD_CONFIGURED); return setupPodResponse; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/InsertCannulaService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/InsertCannulaService.java index b897e448c8..61c786eeca 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/InsertCannulaService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/InsertCannulaService.java @@ -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.AlertConfigurationFactory; 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; public class InsertCannulaService { public StatusResponse programInitialBasalSchedule(OmnipodCommunicationManager communicationService, - PodSessionState podState, BasalSchedule basalSchedule) { - return communicationService.executeAction(new SetBasalScheduleAction(podState, basalSchedule, - true, podState.getScheduleOffset(), false)); + PodStateManager podStateManager, BasalSchedule basalSchedule) { + return communicationService.executeAction(new SetBasalScheduleAction(podStateManager, basalSchedule, + true, podStateManager.getScheduleOffset(), false)); } public StatusResponse executeExpirationRemindersAlertCommand(OmnipodCommunicationManager communicationService, - PodSessionState podState) { + PodStateManager podStateManager) { 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(), endOfServiceTime.minus(OmnipodConst.EXPIRATION_ADVISORY_WINDOW)); @@ -49,11 +49,11 @@ public class InsertCannulaService { autoOffAlertConfiguration // ); - return new ConfigureAlertsAction(podState, alertConfigurations).execute(communicationService); + return new ConfigureAlertsAction(podStateManager, alertConfigurations).execute(communicationService); } - public StatusResponse executeInsertionBolusCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { - return communicationService.executeAction(new BolusAction(podState, OmnipodConst.POD_CANNULA_INSERTION_BOLUS_UNITS, + public StatusResponse executeInsertionBolusCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) { + return communicationService.executeAction(new BolusAction(podStateManager, OmnipodConst.POD_CANNULA_INSERTION_BOLUS_UNITS, Duration.standardSeconds(1), false, false)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/PrimeService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/PrimeService.java index 3fc7663398..d8726be029 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/PrimeService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/service/PrimeService.java @@ -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.defs.AlertConfiguration; 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; public class PrimeService { - public StatusResponse executeDisableTab5Sub16FaultConfigCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { - FaultConfigCommand faultConfigCommand = new FaultConfigCommand(podState.getCurrentNonce(), (byte) 0x00, (byte) 0x00); - OmnipodMessage faultConfigMessage = new OmnipodMessage(podState.getAddress(), - Collections.singletonList(faultConfigCommand), podState.getMessageNumber()); - return communicationService.exchangeMessages(StatusResponse.class, podState, faultConfigMessage); + public StatusResponse executeDisableTab5Sub16FaultConfigCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) { + FaultConfigCommand faultConfigCommand = new FaultConfigCommand(podStateManager.getCurrentNonce(), (byte) 0x00, (byte) 0x00); + OmnipodMessage faultConfigMessage = new OmnipodMessage(podStateManager.getAddress(), + Collections.singletonList(faultConfigCommand), podStateManager.getMessageNumber()); + 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(); - return communicationService.executeAction(new ConfigureAlertsAction(podState, + return communicationService.executeAction(new ConfigureAlertsAction(podStateManager, Collections.singletonList(finishSetupReminderAlertConfiguration))); } - public StatusResponse executePrimeBolusCommand(OmnipodCommunicationManager communicationService, PodSessionState podState) { - return communicationService.executeAction(new BolusAction(podState, OmnipodConst.POD_PRIME_BOLUS_UNITS, + public StatusResponse executePrimeBolusCommand(OmnipodCommunicationManager communicationService, PodStateManager podStateManager) { + return communicationService.executeAction(new BolusAction(podStateManager, OmnipodConst.POD_PRIME_BOLUS_UNITS, Duration.standardSeconds(1), false, false)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java deleted file mode 100644 index 64cb92e84b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java +++ /dev/null @@ -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 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 + - '}'; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSetupState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSetupState.java deleted file mode 100644 index 26b5802258..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSetupState.java +++ /dev/null @@ -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 + - '}'; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java deleted file mode 100644 index c6987c879e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java +++ /dev/null @@ -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; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateChangedHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateChangedHandler.java index 6e706131a2..c1171b498e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateChangedHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateChangedHandler.java @@ -2,5 +2,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.defs.state; @FunctionalInterface public interface PodStateChangedHandler { - void handle(PodSessionState podState); + void handle(PodStateManager podStateManager); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java index e9b0149835..009503bad1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java @@ -20,21 +20,25 @@ public interface PodStateManager { void removeState(); + void initState(int address); + 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); @@ -42,11 +46,11 @@ public interface PodStateManager { 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); @@ -95,4 +99,6 @@ public interface PodStateManager { DeliveryStatus getLastDeliveryStatus(); void updateFromStatusResponse(StatusResponse statusResponse); + + void setStateChangedHandler(PodStateChangedHandler handler); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt index 372304ab66..c37a2af49f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt @@ -45,7 +45,6 @@ class PodManagementActivity : NoSplashAppCompatActivity() { @Inject lateinit var injector: HasAndroidInjector private var initPodChanged = false - private var podSessionFullyInitalized = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -99,8 +98,8 @@ class PodManagementActivity : NoSplashAppCompatActivity() { wizardPagerContext.clearContext() wizardPagerContext.pagerSettings = pagerSettings - val podSessionState = omnipodUtil.getPodSessionState() - val isFullInit = podSessionState == null || podSessionState.setupProgress.isBefore(SetupProgress.PRIMING_FINISHED) + val podStateManager = omnipodUtil.getPodStateManager() + val isFullInit = podStateManager == null || podStateManager.setupProgress.isBefore(SetupProgress.PRIMING_FINISHED) if (isFullInit) { wizardPagerContext.wizardModel = FullInitPodWizardModel(applicationContext) } else { @@ -151,13 +150,13 @@ class PodManagementActivity : NoSplashAppCompatActivity() { } fun refreshButtons() { - initpod_init_pod.isEnabled = (omnipodUtil.getPodSessionState() == null || - omnipodUtil.getPodSessionState().getSetupProgress().isBefore(SetupProgress.COMPLETED)) + initpod_init_pod.isEnabled = omnipodUtil.podStateManager == null || !omnipodUtil.podStateManager.isPaired() || + 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_reset_pod.isEnabled = isPodSessionActive || omnipodUtil.hasNextPodAddress() + initpod_remove_pod.isEnabled = isPodSessionActive && omnipodUtil.podStateManager.isPaired + initpod_reset_pod.isEnabled = isPodSessionActive if (omnipodUtil.getDriverState() == OmnipodDriverState.NotInitalized) { // if rileylink is not running we disable all operations diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java index 37c6d420f7..d6b9734233 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java @@ -58,7 +58,7 @@ public class InitPodRefreshAction extends AbstractCancelAction implements Finish @Override public void execute() { if (actionType == PodActionType.InitPod) { - if (omnipodUtil.getPodSessionState().getSetupProgress().isBefore(SetupProgress.COMPLETED)) { + if (omnipodUtil.getPodStateManager().getSetupProgress().isBefore(SetupProgress.COMPLETED)) { omnipodUtil.setDriverState(OmnipodDriverState.Initalized_PodInitializing); } else { omnipodUtil.setDriverState(OmnipodDriverState.Initalized_PodAttached); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/PodInfoFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/PodInfoFragment.java index 65d032739d..9f8df4a783 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/PodInfoFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/PodInfoFragment.java @@ -19,7 +19,7 @@ import javax.inject.Inject; import dagger.android.support.DaggerFragment; 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; @@ -85,27 +85,26 @@ public class PodInfoFragment extends DaggerFragment { private boolean createDataOfPod() { - PodSessionState podSessionState = omnipodUtil.getPodSessionState(); + PodStateManager podStateManager = omnipodUtil.getPodStateManager(); -// PodSessionState podSessionState = new PodSessionState(DateTimeZone.UTC, -// 483748738, -// new DateTime(), -// new FirmwareVersion(1,0,0), -// new FirmwareVersion(1,0,0), -// 574875, -// 5487584, -// 1, -// 1 -// ); - - if (podSessionState == null) + if (podStateManager == null) return false; mCurrentReviewItems = new ArrayList<>(); - mCurrentReviewItems.add(new ReviewItem("Pod Address", "" + podSessionState.getAddress(), "33")); - mCurrentReviewItems.add(new ReviewItem("Activated At", podSessionState.getActivatedAt().toString("dd.MM.yyyy HH:mm:ss"), "34")); - mCurrentReviewItems.add(new ReviewItem("Firmware Version", podSessionState.getPiVersion().toString(), "35")); - mCurrentReviewItems.add(new ReviewItem("LOT", "" + podSessionState.getLot(), "36")); + mCurrentReviewItems.add(new ReviewItem("Pod Address", "" + podStateManager.getAddress(), "33")); + mCurrentReviewItems.add(new ReviewItem("Activated At", podStateManager.getActivatedAt() == null ? "Not activated yet" : podStateManager.getActivatedAt().toString("dd.MM.yyyy HH:mm:ss"), "34")); + if (podStateManager.getLot() != null) { + 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; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java index 05ca9d6ad5..e01acd7d9c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java @@ -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.RileyLinkTargetDevice; 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.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.util.OmnipodConst; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -47,7 +46,7 @@ public class OmnipodPumpStatus extends PumpStatus { public Double tempBasalAmount = 0.0d; public Integer tempBasalLength; public long tempBasalPumpId; - public PodSessionState podSessionState; + public PodStateManager podStateManager; public PumpType pumpType; public String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}"; @@ -142,7 +141,7 @@ public class OmnipodPumpStatus extends PumpStatus { ", tempBasalEnd=" + tempBasalEnd + ", tempBasalAmount=" + tempBasalAmount + ", tempBasalLength=" + tempBasalLength + - ", podSessionState=" + podSessionState + + ", podStateManager=" + podStateManager + ", regexMac='" + regexMac + '\'' + ", podNumber='" + podNumber + '\'' + ", podDeviceState=" + podDeviceState + diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java index f8c67f5471..fe232cf912 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java @@ -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.podinfo.PodInfoRecentPulseLog; 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.AlertType; 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.schedule.BasalSchedule; 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.db.PodHistory; import info.nightscout.androidaps.plugins.pump.omnipod.driver.db.PodHistoryEntryType; @@ -103,7 +104,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface } public AapsOmnipodManager(OmnipodCommunicationManager communicationService, - PodSessionState podState, + PodStateManager podStateManager, OmnipodPumpStatus _pumpStatus, OmnipodUtil omnipodUtil, AAPSLogger aapsLogger, @@ -120,17 +121,26 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface this.activePlugin = activePlugin; this.pumpStatus = _pumpStatus; - delegate = new OmnipodManager(aapsLogger, sp, communicationService, podState, podSessionState -> { + podStateManager.setStateChangedHandler(manager -> { // Handle pod state changes - omnipodUtil.setPodSessionState(podSessionState); - updatePumpStatus(podSessionState); + // FIXME only set once (?) (before instantiating AapsOmnipodManager) + // 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; } - private void updatePumpStatus(PodSessionState podSessionState) { + public PodStateManager getPodStateManager() { + return delegate.getPodStateManager(); + } + + private void updatePumpStatus(PodStateManager podStateManager) { if (pumpStatus != null) { - if (podSessionState == null) { + if (!podStateManager.hasState()) { pumpStatus.ackAlertsText = null; pumpStatus.ackAlertsAvailable = false; pumpStatus.lastBolusTime = null; @@ -142,8 +152,8 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface sendEvent(new EventRefreshOverview("Omnipod Pump", false)); } else { // Update active alerts - if (podSessionState.hasActiveAlerts()) { - List alerts = translateActiveAlerts(podSessionState); + if (podStateManager.hasActiveAlerts()) { + List alerts = translateActiveAlerts(podStateManager); String alertsText = TextUtils.join("\n", alerts); if (!pumpStatus.ackAlertsAvailable || !alertsText.equals(pumpStatus.ackAlertsText)) { @@ -163,15 +173,15 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface // Update other info: last bolus, units remaining, suspended if (!Objects.equals(lastBolusTime, pumpStatus.lastBolusTime) // || !Objects.equals(lastBolusUnits, pumpStatus.lastBolusAmount) // - || !isReservoirStatusUpToDate(pumpStatus, podSessionState.getReservoirLevel()) - || podSessionState.isSuspended() != PumpStatusType.Suspended.equals(pumpStatus.pumpStatusType)) { + || !isReservoirStatusUpToDate(pumpStatus, podStateManager.getReservoirLevel()) + || podStateManager.isSuspended() != PumpStatusType.Suspended.equals(pumpStatus.pumpStatusType)) { pumpStatus.lastBolusTime = lastBolusTime; pumpStatus.lastBolusAmount = lastBolusUnits; - pumpStatus.reservoirRemainingUnits = podSessionState.getReservoirLevel() == null ? 75.0 : podSessionState.getReservoirLevel(); - pumpStatus.pumpStatusType = podSessionState.isSuspended() ? PumpStatusType.Suspended : PumpStatusType.Running; + pumpStatus.reservoirRemainingUnits = podStateManager.getReservoirLevel() == null ? 75.0 : podStateManager.getReservoirLevel(); + pumpStatus.pumpStatusType = podStateManager.isSuspended() ? PumpStatusType.Suspended : PumpStatusType.Running; 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)); } } @@ -179,31 +189,31 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface } } + private List translateActiveAlerts(PodStateManager podStateManager) { + List 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) { double expectedUnitsRemaining = unitsRemaining == null ? 75.0 : unitsRemaining; return Math.abs(expectedUnitsRemaining - pumpStatus.reservoirRemainingUnits) < 0.000001; } - private List translateActiveAlerts(PodSessionState podSessionState) { - List alerts = new ArrayList<>(); - for (AlertSlot alertSlot : podSessionState.getActiveAlerts().getAlertSlots()) { - alerts.add(translateAlertType(podSessionState.getConfiguredAlertType(alertSlot))); - } - return alerts; - } - @Override public PumpEnactResult initPod(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, Profile profile) { long time = System.currentTimeMillis(); if (PodInitActionType.PairAndPrimeWizardStep.equals(podInitActionType)) { try { - int address = obtainNextPodAddress(); - - Disposable disposable = delegate.pairAndPrime(address).subscribe(res -> // + Disposable disposable = delegate.pairAndPrime().subscribe(res -> // handleSetupActionResult(podInitActionType, podInitReceiver, res, time, null)); - removeNextPodAddress(); - return new PumpEnactResult(injector).success(true).enacted(true); } catch (Exception ex) { String comment = handleAndTranslateException(ex); @@ -265,8 +275,6 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface podInitReceiver.returnInitTaskStatus(PodInitActionType.DeactivatePodWizardStep, true, null); - this.omnipodUtil.setPodSessionState(null); - return new PumpEnactResult(injector).success(true).enacted(true); } @@ -302,13 +310,10 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface @Override public PumpEnactResult resetPodStatus() { - delegate.resetPodState(true); + getPodStateManager().removeState(); reportImplicitlyCanceledTbr(); - this.omnipodUtil.setPodSessionState(null); - this.omnipodUtil.removeNextPodAddress(); - addSuccessToHistory(System.currentTimeMillis(), PodHistoryEntryType.ResetPodState, null); return new PumpEnactResult(injector).success(true).enacted(true); @@ -363,8 +368,8 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); - if (delegate.getPodState().hasFaultEvent()) { - showPodFaultErrorDialog(delegate.getPodState().getFaultEvent().getFaultEventCode(), R.raw.urgentalarm); + if (delegate.getPodStateManager().hasFaultEvent()) { + showPodFaultErrorDialog(delegate.getPodStateManager().getFaultEvent().getFaultEventCode(), R.raw.urgentalarm); } return new PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(unitsDelivered); @@ -463,7 +468,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface @Override public void setPumpStatus(OmnipodPumpStatus pumpStatus) { this.pumpStatus = pumpStatus; - updatePumpStatus(delegate.getPodState()); + updatePumpStatus(delegate.getPodStateManager()); } // TODO should we add this to the OmnipodCommunicationManager interface? @@ -598,20 +603,6 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface 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) { String comment = null; switch (res.getResultType()) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java index 75479709e2..3e278f03a8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java @@ -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.SetupProgress; 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.util.OmniCRC; 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 { - @Inject private AAPSLogger aapsLogger; - @Inject private SP sp; - @Inject private OmnipodUtil omnipodUtil; + @Inject protected AAPSLogger aapsLogger; + @Inject protected SP sp; + @Inject protected OmnipodUtil omnipodUtil; private PodState podState; + private PodStateChangedHandler stateChangedHandler; public AapsPodStateManager(HasAndroidInjector injector) { injector.androidInjector().inject(this); @@ -56,6 +58,15 @@ public class AapsPodStateManager implements PodStateManager { 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() { return hasState() // && podState.getLot() != null && podState.getTid() != null // @@ -64,6 +75,7 @@ public class AapsPodStateManager implements PodStateManager { && podState.getSetupProgress() != null; } + @Override public void setPairingParameters(int lot, int tid, FirmwareVersion piVersion, FirmwareVersion pmVersion, DateTimeZone timeZone) { if (!hasState()) { throw new IllegalStateException("Cannot set pairing parameters: podState is null"); @@ -81,13 +93,16 @@ public class AapsPodStateManager implements PodStateManager { throw new IllegalArgumentException("Cannot set pairing parameters: timeZone can not be null"); } - podState.setLot(lot); - podState.setTid(tid); - podState.setPiVersion(piVersion); - podState.setPmVersion(pmVersion); - podState.setTimeZone(timeZone); - podState.setNonceState(new NonceState(lot, tid)); - podState.setSetupProgress(SetupProgress.ADDRESS_ASSIGNED); + setAndStore(() -> { + podState.setLot(lot); + podState.setTid(tid); + podState.setPiVersion(piVersion); + podState.setPmVersion(pmVersion); + podState.setTimeZone(timeZone); + podState.setNonceState(new NonceState(lot, tid)); + podState.setSetupProgress(SetupProgress.ADDRESS_ASSIGNED); + podState.getConfiguredAlerts().put(AlertSlot.SLOT7, AlertType.FINISH_SETUP_REMINDER); + }); } @Override public int getAddress() { @@ -118,7 +133,7 @@ public class AapsPodStateManager implements PodStateManager { 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()) { throw new IllegalStateException("Cannot resync nonce: Pod is not paired yet"); } @@ -133,14 +148,14 @@ public class AapsPodStateManager implements PodStateManager { setAndStore(() -> podState.setNonceState(nonceState)); } - @Override public int getCurrentNonce() { + @Override public synchronized int getCurrentNonce() { if (!isPaired()) { throw new IllegalStateException("Cannot get current nonce: Pod is not paired yet"); } return podState.getNonceState().getCurrentNonce(); } - @Override public void advanceToNextNonce() { + @Override public synchronized void advanceToNextNonce() { if (!isPaired()) { 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) { if (!hasState()) { throw new IllegalStateException("Cannot mutate PodState: podState is null"); } runnable.run(); 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 @@ -308,13 +346,6 @@ public class AapsPodStateManager implements PodStateManager { 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() { podState = null; @@ -330,6 +361,14 @@ public class AapsPodStateManager implements PodStateManager { aapsLogger.error(LTag.PUMPCOMM, "PodState-SP: could not deserialize PodState", ex); } } + + notifyPodStateChanged(); + } + + @Override public String toString() { + return "AapsPodStateManager{" + + "podState=" + podState + + '}'; } private static class PodState { @@ -506,6 +545,30 @@ public class AapsPodStateManager implements PodStateManager { public Map getConfiguredAlerts() { 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 { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt index 7e7cc87279..41f4cfca9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt @@ -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.omnipod.defs.OmnipodCommandType 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 @@ -15,7 +15,7 @@ class EventOmnipodDeviceStatusChange : Event { var rileyLinkServiceState: RileyLinkServiceState? = null var rileyLinkError: RileyLinkError? = null - var podSessionState: PodSessionState? = null + var podStateManager: PodStateManager? = null var errorDescription: String? = null var podDeviceState: PodDeviceState? = null var pumpDeviceState: PumpDeviceState? = null @@ -32,8 +32,8 @@ class EventOmnipodDeviceStatusChange : Event { } - constructor(podSessionState: PodSessionState?) { - this.podSessionState = podSessionState + constructor(podStateManager: PodStateManager?) { + this.podStateManager = podStateManager } constructor(errorDescription: String?) { @@ -58,7 +58,7 @@ class EventOmnipodDeviceStatusChange : Event { return ("EventOmnipodDeviceStatusChange [" // + "rileyLinkServiceState=" + rileyLinkServiceState + ", rileyLinkError=" + rileyLinkError // - + ", podSessionState=" + podSessionState // + + ", podStateManager=" + podStateManager // + ", podDeviceState=" + podDeviceState + "]") } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java index f401e4ddd1..a84996dc53 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java @@ -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.omnipod.OmnipodPumpPlugin; 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.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.OmnipodUIPostprocessor; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; @@ -106,19 +107,23 @@ public class RileyLinkOmnipodService extends RileyLinkService { } private void initializeErosOmnipodManager() { - if (AapsOmnipodManager.getInstance() == null) { - PodSessionState podState = omnipodUtil.loadSessionState(); + AapsOmnipodManager instance = AapsOmnipodManager.getInstance(); + if (instance == null) { + PodStateManager podStateManager = new AapsPodStateManager(injector); + omnipodUtil.setPodStateManager(podStateManager); + OmnipodCommunicationManager omnipodCommunicationService = new OmnipodCommunicationManager(injector, rfspy); //omnipodCommunicationService.setPumpStatus(omnipodPumpStatus); this.omnipodCommunicationManager = omnipodCommunicationService; - this.aapsOmnipodManager = new AapsOmnipodManager(omnipodCommunicationService, podState, omnipodPumpStatus, + aapsOmnipodManager = new AapsOmnipodManager(omnipodCommunicationService, podStateManager, omnipodPumpStatus, omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin); omnipodUIComm = new OmnipodUIComm(injector, aapsLogger, omnipodUtil, omnipodUIPostprocessor, aapsOmnipodManager); } else { - aapsOmnipodManager = AapsOmnipodManager.getInstance(); + aapsOmnipodManager = instance; + omnipodUtil.setPodStateManager(instance.getPodStateManager()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java index 9c4f6cabe5..c008cee6e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java @@ -8,7 +8,6 @@ import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; -import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; @@ -16,21 +15,18 @@ import org.joda.time.format.ISODateTimeFormat; import javax.inject.Inject; import javax.inject.Singleton; -import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; 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.omnipod.comm.OmnipodManager; 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.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.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange; @@ -49,13 +45,10 @@ public class OmnipodUtil { private final OmnipodPumpStatus omnipodPumpStatus; private final ActivePluginProvider activePlugins; private final SP sp; - private final HasAndroidInjector injector; private boolean lowLevelDebug = true; private OmnipodCommandType currentCommand; private Gson gsonInstance = createGson(); - //private static PodSessionState podSessionState; - //private static PodDeviceState podDeviceState; private OmnipodPodType omnipodPodType; private OmnipodDriverState driverState = OmnipodDriverState.NotInitalized; @@ -67,8 +60,7 @@ public class OmnipodUtil { RileyLinkUtil rileyLinkUtil, OmnipodPumpStatus omnipodPumpStatus, SP sp, - ActivePluginProvider activePlugins, - HasAndroidInjector injector + ActivePluginProvider activePlugins ) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; @@ -76,7 +68,6 @@ public class OmnipodUtil { this.omnipodPumpStatus = omnipodPumpStatus; this.sp = sp; this.activePlugins = activePlugins; - this.injector = injector; } @@ -148,9 +139,9 @@ public class OmnipodUtil { } - public void setPodSessionState(PodSessionState podSessionState) { - omnipodPumpStatus.podSessionState = podSessionState; - rxBus.send(new EventOmnipodDeviceStatusChange(podSessionState)); + public void setPodStateManager(PodStateManager podStateManager) { + omnipodPumpStatus.podStateManager = podStateManager; + rxBus.send(new EventOmnipodDeviceStatusChange(podStateManager)); } @@ -174,8 +165,8 @@ public class OmnipodUtil { } - public PodSessionState getPodSessionState() { - return omnipodPumpStatus.podSessionState; + public PodStateManager getPodStateManager() { + return omnipodPumpStatus.podStateManager; } @@ -202,28 +193,6 @@ public class OmnipodUtil { 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() { return this.aapsLogger; } @@ -231,25 +200,4 @@ public class OmnipodUtil { public SP getSp() { 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; - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java index 4f869bd286..992a248994 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java @@ -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.PodInitActionType; 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; /** @@ -34,7 +34,7 @@ public class OmnipodDashCommunicationManager implements OmnipodCommunicationMana // RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); } - private PodSessionState getPodSessionState() { + private PodStateManager getPodStateManager() { return null; } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionStateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/AapsPodStateManagerTest.java similarity index 62% rename from app/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionStateTest.java rename to app/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/AapsPodStateManagerTest.java index a7ba9cb861..85d8dd897e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionStateTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/AapsPodStateManagerTest.java @@ -11,10 +11,11 @@ import org.mockito.Mock; import dagger.android.HasAndroidInjector; 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; -public class PodSessionStateTest { +public class AapsPodStateManagerTest { @Mock HasAndroidInjector hasAndroidInjector; @Test @@ -24,17 +25,16 @@ public class PodSessionStateTest { DateTimeZone.setDefault(timeZone); DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone); - DateTime initialized = now.minus(Duration.standardDays(1)); DateTimeUtils.setCurrentMillisFixed(now.getMillis()); - PodSessionState podSessionState = new PodSessionState(timeZone, 0x0, - new FirmwareVersion(1, 1, 1), - new FirmwareVersion(2, 2, 2), - 0, 0, 0, 0, hasAndroidInjector); + AapsPodStateManager podStateManager = new AapsPodStateManager(hasAndroidInjector); + podStateManager.initState(0x0); + podStateManager.setPairingParameters(0, 0, new FirmwareVersion(1, 1, 1), + new FirmwareVersion(2, 2, 2), timeZone); - assertEquals(now, podSessionState.getTime()); - assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podSessionState.getScheduleOffset()); + assertEquals(now, podStateManager.getTime()); + assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podStateManager.getScheduleOffset()); } @Test @@ -44,22 +44,21 @@ public class PodSessionStateTest { DateTimeZone.setDefault(timeZone); DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone); - DateTime initialized = now.minus(Duration.standardDays(1)); DateTimeUtils.setCurrentMillisFixed(now.getMillis()); - PodSessionState podSessionState = new PodSessionState(timeZone, 0x0, - new FirmwareVersion(1, 1, 1), - new FirmwareVersion(2, 2, 2), - 0, 0, 0, 0, hasAndroidInjector); + AapsPodStateManager podStateManager = new AapsPodStateManager(hasAndroidInjector); + podStateManager.initState(0x0); + podStateManager.setPairingParameters(0, 0, new FirmwareVersion(1, 1, 1), + new FirmwareVersion(2, 2, 2), timeZone); DateTimeZone newTimeZone = DateTimeZone.forOffsetHours(2); DateTimeZone.setDefault(newTimeZone); // 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 - assertEquals(now, podSessionState.getTime()); - assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podSessionState.getScheduleOffset()); + assertEquals(now, podStateManager.getTime()); + assertEquals(Duration.standardHours(1).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podStateManager.getScheduleOffset()); } @Test @@ -69,23 +68,22 @@ public class PodSessionStateTest { DateTimeZone.setDefault(timeZone); DateTime now = new DateTime(2020, 1, 1, 1, 2, 3, timeZone); - DateTime initialized = now.minus(Duration.standardDays(1)); DateTimeUtils.setCurrentMillisFixed(now.getMillis()); - PodSessionState podSessionState = new PodSessionState(timeZone, 0x0, - new FirmwareVersion(1, 1, 1), - new FirmwareVersion(2, 2, 2), - 0, 0, 0, 0, hasAndroidInjector); + AapsPodStateManager podStateManager = new AapsPodStateManager(hasAndroidInjector); + podStateManager.initState(0x0); + podStateManager.setPairingParameters(0, 0, new FirmwareVersion(1, 1, 1), + new FirmwareVersion(2, 2, 2), timeZone); DateTimeZone newTimeZone = DateTimeZone.forOffsetHours(2); DateTimeZone.setDefault(newTimeZone); - podSessionState.setTimeZone(newTimeZone); + podStateManager.setTimeZone(newTimeZone); // Both the system time zone have been updated // So the pods time should have been changed (to +2 hours) - assertEquals(now.withZone(newTimeZone), podSessionState.getTime()); - assertEquals(Duration.standardHours(3).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podSessionState.getScheduleOffset()); + assertEquals(now.withZone(newTimeZone), podStateManager.getTime()); + assertEquals(Duration.standardHours(3).plus(Duration.standardMinutes(2).plus(Duration.standardSeconds(3))), podStateManager.getScheduleOffset()); } @After