diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/Shimmer.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/Shimmer.java
index 8ae9faef..38a12235 100644
--- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/Shimmer.java
+++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/android/Shimmer.java
@@ -148,6 +148,7 @@
import android.util.Log;
import com.shimmerresearch.bluetooth.BluetoothProgressReportPerCmd;
+import com.shimmerresearch.bluetooth.BtCommandDetails;
import com.shimmerresearch.bluetooth.ShimmerBluetooth;
import com.shimmerresearch.comms.wiredProtocol.ShimmerCrc;
import com.shimmerresearch.driver.CallbackObject;
@@ -175,6 +176,7 @@
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
@@ -823,31 +825,10 @@ else if(bufferTemp[0]==DATA_PACKET
processAckWhileStreaming();
}
- //this is for LogAndStream support, command is transmitted and ack received
+ //this is for LogAndStream support: an in-stream response, the reply to a
+ //GET command or the firmware's unsolicited status push
else if(isSupportedInStreamCmds() && bufferTemp[getPacketSizeWithCrc()+2]==INSTREAM_CMD_RESPONSE){
- printLogDataForDebugging("COMMAND TXed and ACK RECEIVED IN STREAM");
- printLogDataForDebugging("INS CMD RESP");
-
- //Firstly handle the in-stream response
- stopTimerCheckForAckOrResp(); //cancel the ack timer
- mWaitForResponse=false;
- mWaitForAck=false;
-
- processInstreamResponse(true);
-
- // Need to remove here because it is an
- // in-stream response while streaming so not
- // handled elsewhere
- if(getListofInstructions().size()>0){
- removeInstruction(0);
- }
-
- mTransactionCompleted=true;
- setInstructionStackLock(false);
-
- //Then process the Data packet
- //processDataPacket(bufferTemp);
- //clearBuffers();
+ processInstreamResponseWhileStreaming();
}
else {
printLogDataForDebugging("Unknown parsing error while streaming");
@@ -946,103 +927,118 @@ protected void discardFirstBufferByte(){
consolePrintLn("Throw Byte" + UtilShimmer.bytesToHexStringWithSpacesFormatted(bTemp));
}
- protected byte[] getDataFromArrayOutputStream(int extraBytesLength){
- if (mByteArrayOutputStream.size() >= getPacketSizeWithCrc() + extraBytesLength) {
- byte[] allBytes = mByteArrayOutputStream.toByteArray();
- byte[] bufferTemp = new byte[getPacketSizeWithCrc() + extraBytesLength]; //check if the next byte is data packet
- System.arraycopy(allBytes, 0, bufferTemp, 0, bufferTemp.length);
- return bufferTemp;
+ /**
+ * Handles an in-stream response that follows a data packet while streaming:
+ * [data packet][ACK][INSTREAM_CMD_RESPONSE][response opcode][payload], then
+ * the link CRC if one is on. It is the reply to GET_STATUS_COMMAND,
+ * GET_VBATT_COMMAND or GET_DIR_COMMAND, or the status push the firmware
+ * sends unprompted.
+ *
+ * processWhileStreaming() reads whatever has arrived, so the response can be
+ * split across reads anywhere. Nothing is done until all of it, its CRC
+ * included, is in the buffer. Then it is parsed from the buffer, the data
+ * packet is passed on, and the packet, the response and its CRC are consumed
+ * exactly once. This holds in every streaming state: the driver's
+ * processInstreamResponse() reads the response from the socket, which only
+ * suits its own byte-at-a-time reads.
+ */
+ private void processInstreamResponseWhileStreaming() {
+ byte[] allBytes = mByteArrayOutputStream.toByteArray();
+ int responseCommandIndex = getPacketSizeWithCrc()+3;
+ if(allBytes.length<=responseCommandIndex){
+ return; //wait for the response opcode
}
- return null;
- }
+ byte inStreamResponseCommand = allBytes[responseCommandIndex];
- /** process responses to in-stream response */
- @Override
- protected void processInstreamResponse(boolean shouldClearCrcFromBuffer) {
-
- if (!mBluetoothRadioState.equals(BT_STATE.STREAMING)){ //every other start besides streaming
- super.processInstreamResponse(shouldClearCrcFromBuffer);
- } else { //streaming state
- //byte[] inStreamResponseCommandBuffer = readBytes(1, INSTREAM_CMD_RESPONSE);
- byte[] bufferTemp = getDataFromArrayOutputStream(4);
- if (bufferTemp != null) {
- byte inStreamResponseCommand = bufferTemp[bufferTemp.length - 1];
- consolePrintLn("In-stream received = " + btCommandToString(inStreamResponseCommand));
-
- if (inStreamResponseCommand == DIR_RESPONSE) {
- printLogDataForDebugging("IN STREAM: DIR_RESPONSE");
- //byte[] responseData = readBytes(1, inStreamResponseCommand);
- bufferTemp = getDataFromArrayOutputStream(5);
- if (bufferTemp != null) {
- int directoryNameLength = bufferTemp[bufferTemp.length - 1];
- byte[] bufferDirectoryName = new byte[directoryNameLength];
- bufferTemp = getDataFromArrayOutputStream(5 + directoryNameLength);
- System.arraycopy(bufferTemp, bufferTemp.length - bufferDirectoryName.length, bufferDirectoryName, 0, bufferDirectoryName.length);
- if (bufferDirectoryName != null) {
- String tempDirectory = new String(bufferDirectoryName);
- mDirectoryName = tempDirectory;
- printLogDataForDebugging("Directory Name = " + mDirectoryName);
- }
- processDataPacket(bufferTemp);
- clearSingleDataPacketFromBuffers(bufferTemp, bufferTemp.length + mBtCommsCrcModeCurrent.getNumCrcBytes());
- }
- } else if (inStreamResponseCommand == STATUS_RESPONSE) {
- printLogDataForDebugging("IN STREAM: STATUS_RESPONSE");
- int length = 5;
- int statusBytesToRead = 0;
- if(isSupportedUSBPluggedInStatus()) {
- length+=1;
- statusBytesToRead = 2;
- } else {
- statusBytesToRead = 1;
- }
- bufferTemp = getDataFromArrayOutputStream(length);
- if (bufferTemp != null) {
- byte[] responseData = new byte[statusBytesToRead];
- System.arraycopy(bufferTemp, bufferTemp.length - responseData.length, responseData, 0, responseData.length);
- if (responseData != null) {
- parseStatusByte(responseData);
-
- if (!isSupportedRtcStateInStatus()) {
- if (!mIsSensing && !isInitialised()) {
- writeRealTimeClock();
- }
- } else {
- //New case to make sure RTC is set if it hasn't been already
- if (!isSDLogging() && (!isInitialised() || !mIsRtcSet)) {
- writeRealTimeClock();
- }
- }
- eventLogAndStreamStatusChanged(mCurrentCommand);
- processDataPacket(bufferTemp);
- clearSingleDataPacketFromBuffers(bufferTemp, bufferTemp.length + mBtCommsCrcModeCurrent.getNumCrcBytes());
- }
- }
- } else if (inStreamResponseCommand == VBATT_RESPONSE) {
- printLogDataForDebugging("IN STREAM: VBATT_RESPONSE");
- bufferTemp = getDataFromArrayOutputStream(7);
- if (bufferTemp != null) {
- byte[] responseData = new byte[3];
- System.arraycopy(bufferTemp, bufferTemp.length - responseData.length, responseData, 0, responseData.length);
- if (responseData != null) {
- ShimmerBattStatusDetails battStatusDetails = new ShimmerBattStatusDetails(((responseData[1] & 0xFF) << 8) + (responseData[0] & 0xFF), responseData[2]);
- setBattStatusDetails(battStatusDetails);
- printLogDataForDebugging("Battery Status:"
- + "\tVoltage=" + battStatusDetails.getBattVoltageParsed()
- + "\tCharging status=" + battStatusDetails.getChargingStatusParsed()
- + "\tBatt %=" + battStatusDetails.getEstimatedChargePercentageParsed());
- }
- processDataPacket(bufferTemp);
- clearSingleDataPacketFromBuffers(bufferTemp, bufferTemp.length + mBtCommsCrcModeCurrent.getNumCrcBytes());
- }
+ int responseDataIndex = responseCommandIndex+1;
+ int responseDataLength;
+ if(inStreamResponseCommand==DIR_RESPONSE){
+ if(allBytes.length<=responseDataIndex){
+ return; //wait for the length of the directory name
+ }
+ responseDataLength = 1+(allBytes[responseDataIndex]&0xFF);
+ }
+ else if(inStreamResponseCommand==STATUS_RESPONSE){
+ responseDataLength = isSupportedUSBPluggedInStatus()? 2:1;
+ }
+ else if(inStreamResponseCommand==VBATT_RESPONSE){
+ responseDataLength = 3;
+ }
+ else {
+ printLogDataForDebugging("IN STREAM: unknown response " + btCommandToString(inStreamResponseCommand));
+ discardFirstBufferByte();
+ return;
+ }
+ int frameLength = responseDataIndex+responseDataLength+mBtCommsCrcModeCurrent.getNumCrcBytes();
+ if(allBytes.length0){
+ removeInstruction(0);
+ }
+ mTransactionCompleted=true;
+ setInstructionStackLock(false);
+ }
+ }
+
+ /**
+ * Whether an in-stream response answers the queued command in flight. Not
+ * every one does. While streaming, readBattery() and readStatusLogAndStream()
+ * write their commands straight to the socket rather than queue them, and the
+ * firmware pushes its status unprompted: on a dock, an undock, the user
+ * button, a trial-duration expiry or a low-battery stop. A response's leading
+ * ACK is not the ACK of the command in flight, so a reply is matched to its
+ * command by response opcode (log-and-stream-common
+ * docs/SHIMMER3_BT_COMMUNICATION_PROTOCOL.md section 5.4).
+ */
+ private boolean isReplyToCommandInFlight(byte inStreamResponseCommand) {
+ BtCommandDetails commandDetails = mBtGetCommandMap.get(mCurrentCommand);
+ return mWaitForAck && commandDetails!=null && commandDetails.expectedResponse==inStreamResponseCommand;
}
diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00002_StreamingBareAckCrcTest.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00002_StreamingBareAckCrcTest.java
index cb3735b1..b990b8d5 100644
--- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00002_StreamingBareAckCrcTest.java
+++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00002_StreamingBareAckCrcTest.java
@@ -300,8 +300,8 @@ public void bareAckWithoutCrcWhileStreaming() throws Exception {
/**
* Already worked: an in-stream response's 0x8A follows the ACK, and its CRC
* comes at the end. Each frame arrives whole here, in a read of its own or
- * all in one: split across reads, an in-stream response has defects of its
- * own in processInstreamResponse(), which this change leaves alone.
+ * all in one. AAPI_00003_StreamingInstreamResponseTest splits in-stream
+ * responses across reads.
*/
private void inStreamResponseWhileStreaming(BT_CRC_MODE crcMode, boolean framePerRead) {
QueueShimmer device = streamingShimmer3r(crcMode);
diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00003_StreamingInstreamResponseTest.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00003_StreamingInstreamResponseTest.java
new file mode 100644
index 00000000..cce9a496
--- /dev/null
+++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00003_StreamingInstreamResponseTest.java
@@ -0,0 +1,444 @@
+package com.shimmerresearch.bluetooth;
+
+import static org.junit.Assert.*;
+
+import android.content.Context;
+import android.os.Handler;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Deque;
+import java.util.List;
+
+import org.junit.After;
+import org.junit.Test;
+
+import com.shimmerresearch.android.Shimmer;
+import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_CRC_MODE;
+import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_STATE;
+import com.shimmerresearch.comms.wiredProtocol.ShimmerCrc;
+import com.shimmerresearch.driver.ShimmerObject;
+import com.shimmerresearch.driverUtilities.ShimmerVerDetails.FW_ID;
+import com.shimmerresearch.driverUtilities.ShimmerVerDetails.HW_ID;
+import com.shimmerresearch.driverUtilities.ShimmerVerObject;
+import com.shimmerresearch.driverUtilities.UtilShimmer;
+
+/**
+ * DEV-1149: while streaming, the firmware's in-stream responses come between
+ * data packets: [ACK][INSTREAM_CMD_RESPONSE][response opcode][payload], then
+ * the link CRC if one is on. They are the replies to GET_STATUS_COMMAND,
+ * GET_VBATT_COMMAND and GET_DIR_COMMAND, and the status push the firmware
+ * sends unprompted on a dock, an undock, the user button, a trial-duration
+ * expiry or a low-battery stop. Shimmer.processPacket() mishandled them in
+ * three ways:
+ *
+ * - It parsed a response without waiting for its link CRC, and consumed
+ * nothing when the CRC had not arrived, so the next read parsed the response
+ * again and passed the data packet before it on twice. A GET_DIR reply whose
+ * name had not all arrived threw a NullPointerException.
+ * - It took every in-stream response for the reply to the queued command in
+ * flight, and removed that command from the instruction queue. But while
+ * streaming, readBattery() and readStatusLogAndStream() write their commands
+ * straight to the socket, and a status push answers no command at all. A SET
+ * command was removed while it awaited its ACK, and the ACK was then processed
+ * against the next instruction: for startSDLogging(), an
+ * ArrayIndexOutOfBoundsException on the IO thread.
+ * - While streaming and SD logging, it read the rest of the response from
+ * the socket, although Shimmer had already read it into its buffer.
+ *
+ * Each scenario is replayed with every link CRC mode, and with the bytes
+ * arriving in reads of every size, from one byte to all of them at once.
+ *
+ * No hardware: the parser reads from an in-memory byte queue. It lives in this
+ * package because the parser's state is protected or package-private in
+ * ShimmerBluetooth.
+ */
+public class AAPI_00003_StreamingInstreamResponseTest {
+
+ /** Bytes after the DATA_PACKET byte: a 3-byte timestamp and three 2-byte channels */
+ private static final int PACKET_SIZE = 9;
+
+ /** As many bytes as any scenario here sends in one go, so the largest read takes everything at once */
+ private static final int MAX_READ_SIZE = 48;
+
+ /** The battery ADC value in vbattReply() */
+ private static final int VBATT_ADC = 0x0B24;
+
+ /** Status byte 0: an SD card is in, and the device is streaming and has its clock set */
+ private static final byte STATUS_STREAMING = 0x20|0x10|0x04|0x02;
+
+ /** Status byte 0: as STATUS_STREAMING, and logging to the SD card too */
+ private static final byte STATUS_STREAMING_AND_LOGGING = STATUS_STREAMING|0x08;
+
+ /** The GET_DIR_COMMAND reply: the SD file path without its file number */
+ private static final String DIRECTORY_NAME = "Trial/Shim_A1B2-";
+
+ /** A Shimmer whose Bluetooth link is in memory */
+ private static class QueueShimmer extends Shimmer {
+ final Deque rx = new ArrayDeque();
+ final ByteArrayOutputStream tx = new ByteArrayOutputStream();
+ int bytesSkipped = 0;
+
+ QueueShimmer() {
+ super((Handler) null, (Context) null);
+ // A device has been initialised by the time it streams. Before then, a
+ // status response queues SET_RWC_COMMAND to set the clock.
+ mIsInitialised = true;
+ }
+
+ void queue(byte[] bytes) {
+ for(byte b:bytes){
+ rx.add(b);
+ }
+ }
+
+ /** What the IO thread does on each pass while streaming */
+ void ioThreadPass() {
+ processWhileStreaming();
+ }
+
+ @Override
+ protected int availableBytes() {
+ return rx.size();
+ }
+
+ @Override
+ protected byte[] readBytes(int numberofBytes) {
+ // Shimmer's would block for bytes that have not arrived, and none will
+ assertTrue("read " + numberofBytes + " bytes but only " + rx.size() + " had arrived", numberofBytes<=rx.size());
+ byte[] bytes = new byte[numberofBytes];
+ for(int i=0;i mDevices = new ArrayList();
+
+ @After
+ public void stopAckTimers() {
+ for(QueueShimmer device:mDevices){
+ device.stopTimerCheckForAckOrResp();
+ }
+ }
+
+ /**
+ * Shimmer reads whatever has arrived, so a frame can be split across reads
+ * anywhere. Runs the scenario with each link CRC mode, and the bytes
+ * arriving one at a time, two at a time and so on, up to all of them at once.
+ */
+ private static void forEveryCrcModeAndReadSize(Scenario scenario) throws Exception {
+ for(BT_CRC_MODE crcMode:BT_CRC_MODE.values()){
+ for(int readSize=1;readSize<=MAX_READ_SIZE;readSize++){
+ String run = crcMode + ", bytes arriving " + readSize + " at a time: ";
+ try {
+ scenario.run(crcMode, readSize);
+ }
+ catch(AssertionError e){
+ throw new AssertionError(run + e.getMessage(), e);
+ }
+ catch(RuntimeException e){
+ throw new AssertionError(run + e, e);
+ }
+ }
+ }
+ }
+
+ /** A Shimmer3R part way through streaming PACKET_SIZE-byte packets */
+ private QueueShimmer streamingShimmer3r(BT_CRC_MODE crcMode) {
+ QueueShimmer device = new QueueShimmer();
+ mDevices.add(device);
+ device.setShimmerVersionObjectAndCreateSensorMap(new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 7));
+ device.setPacketSize(PACKET_SIZE);
+ device.setCurrentBtCommsCrcMode(crcMode);
+ device.setBluetoothRadioState(BT_STATE.STREAMING);
+ // Queue each parsed packet rather than build an ObjectCluster from it
+ device.mUseProcessingThread = true;
+ return device;
+ }
+
+ /** What the IO thread does when it sends the next queued instruction while streaming */
+ private static void sendNextInstruction(QueueShimmer device) {
+ device.mCurrentCommand = device.getListofInstructions().get(0)[0];
+ device.setInstructionStackLock(true);
+ device.mWaitForAck = true;
+ device.startTimerCheckForAckOrResp(2);
+ }
+
+ /** Hands the frames to the streaming parser readSize bytes at a time, one IO thread pass per read */
+ private static void receive(QueueShimmer device, int readSize, byte[]... frames) {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ for(byte[] frame:frames){
+ bytes.write(frame, 0, frame.length);
+ }
+ byte[] all = bytes.toByteArray();
+ assertTrue("the largest read takes all " + all.length + " bytes at once", all.length<=MAX_READ_SIZE);
+ for(int start=0;start expected = new ArrayList();
+ for(byte[] payload:expectedPayloads){
+ expected.add(hex(payload));
+ }
+ List parsed = new ArrayList();
+ // Package-private, so Shimmer does not inherit it
+ ShimmerBluetooth parser = device;
+ for(RawBytePacketWithPCTimeStamp packet:parser.mABQPacketByeArray){
+ parsed.add(hex(packet.mDataArray));
+ }
+ assertEquals("every good data packet is parsed, once and in order", expected, parsed);
+ }
+
+ /** The commands in the instruction queue, in order */
+ private static void assertQueued(QueueShimmer device, byte... expectedCommands) {
+ List expected = new ArrayList();
+ for(byte command:expectedCommands){
+ expected.add(ShimmerBluetooth.btCommandToString(command));
+ }
+ List queued = new ArrayList();
+ for(byte[] instruction:device.getListofInstructions()){
+ queued.add(ShimmerBluetooth.btCommandToString(instruction[0]));
+ }
+ assertEquals("the instruction queue", expected, queued);
+ }
+
+ /** The command was sent and nothing has answered it yet */
+ private static void assertAwaitingReply(QueueShimmer device, byte command) {
+ assertEquals("the command in flight", ShimmerBluetooth.btCommandToString(command),
+ ShimmerBluetooth.btCommandToString(device.mCurrentCommand));
+ assertTrue("it still awaits its reply", device.mWaitForAck);
+ assertTrue("so the next instruction cannot be sent", device.isInstructionStackLock());
+ assertNotNull("and its ACK timer still runs", device.mTimerCheckForAckOrResp);
+ }
+
+ /** The command in flight was answered, and the next can be sent */
+ private static void assertAnswered(QueueShimmer device) {
+ assertFalse("the reply is taken", device.mWaitForAck);
+ assertFalse("the next instruction can be sent", device.isInstructionStackLock());
+ assertNull("the ACK timer is cancelled, so it cannot clear the instruction queue", device.mTimerCheckForAckOrResp);
+ }
+
+ /** What is left in the parser's buffer, each byte with its PC timestamp */
+ private static void assertBuffered(QueueShimmer device, byte... expected) {
+ assertEquals(hex(expected), hex(device.mByteArrayOutputStream.toByteArray()));
+ assertEquals("one PC timestamp per buffered byte", expected.length, device.mListofPCTimeStamps.size());
+ }
+
+ /** The parser never lost its place, so every frame was consumed whole and once */
+ private static void assertNoResync(QueueShimmer device) {
+ assertEquals("bytes skipped to find the next frame", 0, device.bytesSkipped);
+ }
+
+ /**
+ * A response is processed once, when all of it has arrived. Split at its
+ * link CRC, it was processed again on the next read, and the data packet
+ * before it passed on twice.
+ */
+ @Test
+ public void inStreamResponseSplitAcrossReads() throws Exception {
+ forEveryCrcModeAndReadSize((crcMode, readSize) -> {
+ QueueShimmer device = streamingShimmer3r(crcMode);
+ device.readBattery();
+ assertEquals("while streaming, Shimmer writes the command straight out rather than queue it",
+ hex(new byte[] {ShimmerObject.GET_VBATT_COMMAND}), hex(device.tx.toByteArray()));
+
+ receive(device, readSize, dataPacket(payload(1), crcMode), vbattReply(crcMode),
+ dataPacket(payload(2), crcMode), new byte[] {ShimmerObject.DATA_PACKET});
+
+ assertEquals(VBATT_ADC, device.getBattStatusDetails().getBattAdcValue(), 0);
+ assertParsed(device, payload(1), payload(2));
+ assertBuffered(device, ShimmerObject.DATA_PACKET);
+ assertNoResync(device);
+ });
+ }
+
+ /**
+ * The reply to the queued command in flight completes it, once, however the
+ * reply is split. A status push that arrives first answers nothing (the
+ * protocol's rule: match a reply to its command by response opcode, never by
+ * its ACK).
+ */
+ @Test
+ public void replyToTheQueuedCommandInFlightCompletesItOnce() throws Exception {
+ forEveryCrcModeAndReadSize((crcMode, readSize) -> {
+ QueueShimmer device = streamingShimmer3r(crcMode);
+ device.readDirectoryName();
+ device.startSDLogging();
+ sendNextInstruction(device);
+
+ receive(device, readSize, dataPacket(payload(1), crcMode), statusPush(STATUS_STREAMING, crcMode),
+ dataPacket(payload(2), crcMode));
+ assertAwaitingReply(device, ShimmerObject.GET_DIR_COMMAND);
+ assertQueued(device, ShimmerObject.GET_DIR_COMMAND, ShimmerObject.SET_RWC_COMMAND, ShimmerObject.START_LOGGING_ONLY_COMMAND);
+
+ receive(device, readSize, dataPacket(payload(3), crcMode), dirReply(crcMode),
+ dataPacket(payload(4), crcMode), new byte[] {ShimmerObject.DATA_PACKET});
+ assertEquals(DIRECTORY_NAME, device.getDirectoryName());
+ assertAnswered(device);
+ assertQueued(device, ShimmerObject.SET_RWC_COMMAND, ShimmerObject.START_LOGGING_ONLY_COMMAND);
+
+ assertParsed(device, payload(1), payload(2), payload(3), payload(4));
+ assertBuffered(device, ShimmerObject.DATA_PACKET);
+ assertNoResync(device);
+ });
+ }
+
+ /**
+ * startSDLogging() while streaming queues SET_RWC_COMMAND, then
+ * START_LOGGING_ONLY_COMMAND. In-stream responses that answer neither leave
+ * both alone: the battery timer's reading, which readBattery() wrote straight
+ * out, while the first awaits its ACK, and a status push while the second
+ * waits its turn. The first used to take SET_RWC_COMMAND off the queue, so
+ * its ACK was processed against START_LOGGING_ONLY_COMMAND's instruction.
+ */
+ @Test
+ public void responsesThatAnswerNoQueuedCommandLeaveTheQueueAlone() throws Exception {
+ forEveryCrcModeAndReadSize((crcMode, readSize) -> {
+ QueueShimmer device = streamingShimmer3r(crcMode);
+ device.startSDLogging();
+ sendNextInstruction(device);
+ device.readBattery();
+
+ receive(device, readSize, dataPacket(payload(1), crcMode), vbattReply(crcMode), dataPacket(payload(2), crcMode));
+ assertEquals(VBATT_ADC, device.getBattStatusDetails().getBattAdcValue(), 0);
+ assertAwaitingReply(device, ShimmerObject.SET_RWC_COMMAND);
+ assertQueued(device, ShimmerObject.SET_RWC_COMMAND, ShimmerObject.START_LOGGING_ONLY_COMMAND);
+
+ receive(device, readSize, dataPacket(payload(3), crcMode), bareAck(crcMode), dataPacket(payload(4), crcMode));
+ assertAnswered(device);
+ assertQueued(device, ShimmerObject.START_LOGGING_ONLY_COMMAND);
+
+ receive(device, readSize, dataPacket(payload(5), crcMode), statusPush(STATUS_STREAMING, crcMode), dataPacket(payload(6), crcMode));
+ assertQueued(device, ShimmerObject.START_LOGGING_ONLY_COMMAND);
+
+ sendNextInstruction(device);
+ receive(device, readSize, dataPacket(payload(7), crcMode), bareAck(crcMode),
+ dataPacket(payload(8), crcMode), new byte[] {ShimmerObject.DATA_PACKET});
+ assertAnswered(device);
+ assertQueued(device);
+ assertTrue(device.isSDLogging());
+ assertEquals(BT_STATE.STREAMING_AND_SDLOGGING, device.getBluetoothRadioState());
+
+ assertParsed(device, payload(1), payload(2), payload(3), payload(4), payload(5), payload(6), payload(7), payload(8));
+ assertBuffered(device, ShimmerObject.DATA_PACKET);
+ assertNoResync(device);
+ });
+ }
+
+ /**
+ * While streaming and SD logging, as while only streaming, a response is
+ * parsed from what Shimmer has already read. It used to be read from the
+ * socket, as the driver does: QueueShimmer.readBytes() fails such a read,
+ * where Shimmer's would wait for later bytes and take them for the response.
+ */
+ @Test
+ public void inStreamResponseWhileStreamingAndSdLogging() throws Exception {
+ forEveryCrcModeAndReadSize((crcMode, readSize) -> {
+ QueueShimmer device = streamingShimmer3r(crcMode);
+
+ // The user button starts logging, so the firmware pushes its status
+ receive(device, readSize, dataPacket(payload(1), crcMode), statusPush(STATUS_STREAMING_AND_LOGGING, crcMode),
+ dataPacket(payload(2), crcMode));
+ assertTrue(device.isSDLogging());
+ assertEquals(BT_STATE.STREAMING_AND_SDLOGGING, device.getBluetoothRadioState());
+
+ device.readBattery();
+ receive(device, readSize, dataPacket(payload(3), crcMode), vbattReply(crcMode),
+ dataPacket(payload(4), crcMode), new byte[] {ShimmerObject.DATA_PACKET});
+ assertEquals(VBATT_ADC, device.getBattStatusDetails().getBattAdcValue(), 0);
+ assertEquals(BT_STATE.STREAMING_AND_SDLOGGING, device.getBluetoothRadioState());
+
+ assertParsed(device, payload(1), payload(2), payload(3), payload(4));
+ assertBuffered(device, ShimmerObject.DATA_PACKET);
+ assertNoResync(device);
+ });
+ }
+}