From a0a7b5a444d1145e51ed8770e86c24ae5d10649b Mon Sep 17 00:00:00 2001 From: JongChern Date: Thu, 22 Oct 2026 20:28:01 +0800 Subject: [PATCH] DEV-1306: a stop's reply no longer retires the wrong instruction Every reply path retires the command in flight with removeInstruction(0), taking the head of the instruction list to be the command answered. Two things broke that around a stop: - operationPrepare() cleared the list while the STOP was still in flight. The stop handling, which sleeps 400 ms on the first byte after the STOP, then removed the head in the STOP's place: the first SET_INFOMEM of a configuration started straight after stopStreaming(), the chunk that holds the sampling rate. The unit kept its old rate. operationPrepare() now waits, for up to 3 s, until a command already in flight has been answered and retired, then clears the list. mTransactionCompleted is volatile, so the waiting thread sees it. - The stop handling then let the same byte go on to the ACK processing. When that byte was the unit's ACK, it retired the next instruction as well, a command queued after the stop that was never sent. The stop handling now returns once the stop is handled, and logs when it was answered by its ACK. API_00031_ConfigureStraightAfterStopTest runs the IOThread over an in-memory radio. Without the fix the stop-window configuration sends only chunks 0x0080 and 0x0100, and the command queued behind an ACK-first stop is never sent; with it both pass, as does a configuration after the stop has finished. Co-Authored-By: Claude Opus 5.5 --- .../bluetooth/ShimmerBluetooth.java | 62 ++++- ..._00031_ConfigureStraightAfterStopTest.java | 225 ++++++++++++++++++ 2 files changed, 284 insertions(+), 3 deletions(-) create mode 100644 ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00031_ConfigureStraightAfterStopTest.java diff --git a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java index b02a5339d..00998a855 100644 --- a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java +++ b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java @@ -186,7 +186,7 @@ public String toString() { protected byte mCurrentCommand; protected boolean mWaitForAck=false; // This indicates whether the device is waiting for an acknowledge packet from the Shimmer Device protected boolean mWaitForResponse=false; // This indicates whether the device is waiting for a response packet from the Shimmer Device - protected boolean mTransactionCompleted=true; // Variable is used to ensure a command has finished execution prior to executing the next command (see initialize()) + protected volatile boolean mTransactionCompleted=true; // Variable is used to ensure a command has finished execution prior to executing the next command (see initialize()). Volatile: operationPrepare() waits on it from an app thread transient protected IOThread mIOThread; transient protected ProcessingThread mPThread; @Deprecated // mContinousSync doesn't do anything @@ -858,13 +858,21 @@ private void processNotStreamingWaitForAck() { clearSerialBuffer(); - hasStopStreaming(); + hasStopStreaming(); removeInstruction(0); removeAllNulls(); if (mCurrentCommand==STOP_SDBT_COMMAND){ - eventLogAndStreamStatusChanged(mCurrentCommand); + eventLogAndStreamStatusChanged(mCurrentCommand); } setInstructionStackLock(false); + // The stop is handled and the STOP retired. The byte that started the handling + // must not also go on to the ACK processing below: when it was the unit's ACK, + // that retired the next instruction as well, a command queued straight after + // stopStreaming() that was never sent (DEV-1306) + if((byte)byteBuffer[0]==ACK_COMMAND_PROCESSED){ + printLogDataForDebugging("Stop handled on its ACK, the first byte back"); + } + return; } // //TODO: ACK is probably now working for STOP_STREAMING_COMMAND so merge in with others? // if(mCurrentCommand==STOP_SDBT_COMMAND) { //due to not receiving the ack from stop streaming command we will skip looking for it. @@ -2989,6 +2997,14 @@ public void setSendProgressReport(boolean state) { public void operationPrepare(){ stopAllTimers(); + // Let a command already sent finish first. Clearing the list now would remove it while it is + // still in flight, and its reply, which retires the head of the list (removeInstruction(0)), + // would then remove this operation's first instruction in its place. After stopStreaming() the + // STOP is in flight for about 400 ms, as its stop handling sleeps that long, so a configuration + // started straight after a stop lost its first SET_INFOMEM, the chunk that holds the sampling + // rate (DEV-1306). + waitForInstructionInFlight(OPERATION_PREPARE_WAIT_MS); + //make sure no more instructions //shouldnt matter since the configuration are being rewritten by consensys //used in initializeshimmer3 (this class) and BluetoothManager class @@ -6065,6 +6081,46 @@ public void enableCheckifAlive(boolean set){ } } + /** How long operationPrepare() waits for a command in flight: past its 2 s ACK timeout */ + private static final long OPERATION_PREPARE_WAIT_MS = 3000; + + /** + * Waits until the instruction at the head of the list, if it has been sent and is waiting for its + * reply, has been answered and retired, or until the timeout. Returns at once on the IOThread, + * which is the thread that would retire it. + */ + private void waitForInstructionInFlight(long timeoutMs) { + byte[] inFlight; + synchronized(mListofInstructions){ + inFlight = (!mTransactionCompleted && !mListofInstructions.isEmpty()) ? mListofInstructions.get(0) : null; + } + if(inFlight==null || Thread.currentThread()==mIOThread){ + return; + } + long end = System.currentTimeMillis()+timeoutMs; + while(System.currentTimeMillis() + * The STOP stays at the head of the instruction list, in flight, until its stop handling retires it: + * the first byte after it (stream data, while streaming) starts that handling, which sleeps 400 ms, + * then removes the head of the list (removeInstruction(0)). A configuration's operationPrepare() + * clears the list, so inside that window it removed the STOP, the operation queued its chunks, and + * the stop handling then removed the first chunk in the STOP's place. + *

+ * No hardware: the IOThread runs as connect() starts it, over an in-memory radio that acknowledges + * every SET_INFOMEM as the firmware does. It lives in this package because mIOThread is a protected + * member of ShimmerBluetooth. + */ +public class API_00031_ConfigureStraightAfterStopTest { + + /** Three 128-byte chunks, as a Shimmer3 or Shimmer3R configuration is written */ + private static final int CONFIG_BYTES = 384; + + private static class AnsweringRadio implements ByteCommunication { + final ConcurrentLinkedDeque rx = new ConcurrentLinkedDeque(); + final List written = Collections.synchronizedList(new ArrayList()); + final CountDownLatch stopSent = new CountDownLatch(1); + + void queue(byte... bytes) { + for(byte b:bytes){ + rx.add(b); + } + } + + /** The address of each SET_INFOMEM written: [0x8C, length, address LSB, address MSB, data...] */ + List infoMemAddressesWritten() { + List addresses = new ArrayList(); + synchronized(written){ + for(byte[] w:written){ + if(w[0]==ShimmerObject.SET_INFOMEM_COMMAND){ + addresses.add((w[2]&0xFF) | ((w[3]&0xFF)<<8)); + } + } + } + return addresses; + } + + boolean wrote(byte command) { + synchronized(written){ + for(byte[] w:written){ + if(w[0]==command){ + return true; + } + } + } + return false; + } + + @Override + public boolean writeBytes(byte[] buffer) { + written.add(buffer.clone()); + if(buffer[0]==ShimmerObject.STOP_STREAMING_COMMAND){ + // Its reply is the test's to send, so the test controls when the stop handling starts + stopSent.countDown(); + } + else { + // Every other command here is a SET, which the firmware acknowledges + queue(ShimmerObject.ACK_COMMAND_PROCESSED); + } + return true; + } + + @Override + public byte[] readBytes(int byteCount, int timeout) throws SerialPortTimeoutException { + if(rx.size() waitForChunks(AnsweringRadio radio, int count, long timeoutMs) throws InterruptedException { + long end = System.currentTimeMillis()+timeoutMs; + while(radio.infoMemAddressesWritten().size() chunks = waitForChunks(radio, ALL_THREE_CHUNKS.length, 5000); + assertEquals("the SET_INFOMEM chunks sent, by address", java.util.Arrays.asList(ALL_THREE_CHUNKS), chunks); + } + + /** + * When the unit's ACK is the first byte after the STOP, with no data packet in flight, the stop + * handling retired the STOP and the same byte then went on as an ACK and retired the next + * instruction too: here a plain SET queued straight after stopStreaming(), with no configuration + * operation at all. + */ + @Test + public void aCommandQueuedAfterTheStopIsSentWhenTheAckComesFirst() throws Exception { + AnsweringRadio radio = streamingShimmer3r(); + mDevice.stopStreaming(); + mDevice.writeAccelRange(1); + assertTrue("the STOP was sent", radio.stopSent.await(2, TimeUnit.SECONDS)); + startStopHandling(radio, ShimmerObject.ACK_COMMAND_PROCESSED); + + long end = System.currentTimeMillis()+3000; + while(!radio.wrote(ShimmerObject.SET_ACCEL_SENSITIVITY_COMMAND) && System.currentTimeMillis() chunks = waitForChunks(radio, ALL_THREE_CHUNKS.length, 5000); + assertEquals("the SET_INFOMEM chunks sent, by address", java.util.Arrays.asList(ALL_THREE_CHUNKS), chunks); + } +}