From 0261ae1c2c130c8c58c3d0e5749dc93fa99402f5 Mon Sep 17 00:00:00 2001 From: Mark Nolan Date: Mon, 5 Oct 2026 04:29:08 +0100 Subject: [PATCH] DEV-1149: handle in-stream responses once, whole, and by opcode While streaming, Shimmer.processPacket() handed an in-stream response (FF 8A [link CRC]) to processInstreamResponse(). That had three defects: - It sized each response without its link CRC, and consumed nothing when the CRC had not arrived. 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 NullPointerException. - It took every in-stream response for the reply to the queued command in flight. But while streaming, readBattery() and readStatusLogAndStream() write their commands straight to the socket, and the firmware pushes its status unprompted. So a queued SET command was removed while it awaited its ACK. For startSDLogging(), that ACK was then processed against START_LOGGING_ONLY_COMMAND's instruction and threw ArrayIndexOutOfBoundsException on the IO thread. A response split across reads also removed an instruction on every read. - It parsed from the buffer only in STREAMING. In STREAMING_AND_SDLOGGING it called the driver's version, which reads the response from the socket although it is already in the buffer. Replace it with processInstreamResponseWhileStreaming(), which processPacket() calls in any streaming state. It waits for the whole response, CRC included, parses it from the buffer, and consumes the packet, the response and its CRC exactly once. It completes the queued command in flight only if the response is that command's reply, matched by response opcode through the driver's mBtGetCommandMap. The protocol requires this: log-and-stream-common docs/SHIMMER3_BT_COMMUNICATION_PROTOCOL.md section 5.4, rule 2. The processInstreamResponse() override goes, and so does getDataFromArrayOutputStream(), which only it used. The driver's version still serves the not-streaming path. AAPI_00003_StreamingInstreamResponseTest replays four scenarios with every link CRC mode, and the bytes arriving in reads of every size from 1 to 48. All four fail on the parent commit. Co-Authored-By: Claude Opus 5.5 --- .../com/shimmerresearch/android/Shimmer.java | 224 +++++---- .../AAPI_00002_StreamingBareAckCrcTest.java | 4 +- ...I_00003_StreamingInstreamResponseTest.java | 444 ++++++++++++++++++ 3 files changed, 556 insertions(+), 116 deletions(-) create mode 100644 ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/test/java/com/shimmerresearch/bluetooth/AAPI_00003_StreamingInstreamResponseTest.java 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.length 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); + }); + } +}