From 3de20a7cd69d70f12ec6af09f166eb213440d4c1 Mon Sep 17 00:00:00 2001 From: JongChern Date: Fri, 13 Nov 2026 15:11:43 +0800 Subject: [PATCH 1/2] DEV-971: fix four parser defects in the event channel found in review Each was first reproduced by a test that failed on the unchanged code (API_00044_EventStreamReviewReproTest), then fixed: 1. Idle: event records right behind an in-stream reply were lost. After an unsolicited status push ([ACK][0x8A][0x71]), sent on a dock, an undock or a press that starts logging, clearSerialBuffer() wiped the records queued behind it (0 of 2 arrived). With the event channel on, the bytes after the reply are now left for the next pass. A record frame after a stray ACK no longer has link-CRC bytes cleared after it either: it carries its own CRC. 2. Streaming: an ACK nobody waited for, before a record frame, re-ran the ACK handling of the SET that went last. It is now taken only while an ACK is awaited. 3. Streaming with no link CRC: the packet before a 0x8A was taken as a packet even when the 0x8A was a data byte after a lost byte, so misframed bytes reached the app as a sample. It is now taken only once the frame after it passes its own CRC; otherwise the bytes are discarded as before. 4. readEventChannelStatus() could be queued behind a start of streaming not yet acknowledged, and its unwrapped reply, [ACK][0xBA][9], was then not taken between data packets and the command timed out. It is now refused while a start of streaming is queued, and a reply that still arrives between packets is taken. ShimmerDriver 219/219 and ShimmerDriverPC 154/154 pass; the Java 8 MATLAB jar builds. Co-Authored-By: Claude Opus 5.5 --- .../bluetooth/ShimmerBluetooth.java | 124 ++++++- .../API_00044_EventStreamReviewReproTest.java | 339 ++++++++++++++++++ 2 files changed, 444 insertions(+), 19 deletions(-) create mode 100644 ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00044_EventStreamReviewReproTest.java diff --git a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java index e2df1cef4..ffad2b160 100644 --- a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java +++ b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java @@ -1104,10 +1104,17 @@ else if(byteBuffer[0]==ACK_COMMAND_PROCESSED) { } if(byteBuffer!=null && byteBuffer[0]==INSTREAM_CMD_RESPONSE){ processResponseCommand(INSTREAM_CMD_RESPONSE); + /* The reply was read whole. With the event channel on, records + * may already be queued behind it (a status push when a press + * starts logging, say), so they are left for the next pass + * rather than cleared (DEV-971). */ + if(mEventFramesPossible) { + return; + } } } } - + clearSerialBuffer(); } } @@ -1170,7 +1177,32 @@ else if(bufferTemp[0]==DATA_PACKET //Then handle the ACK from the last SET command processAckWhileStreaming(); } - + + //The event channel status, [ACK][0xBA][9], which is not wrapped in 0x8A: + //readEventChannelStatus() is not sent while streaming, but one sent just + //before a stream started is answered once packets flow (DEV-971) + else if(bufferTemp[getPacketSizeWithCrc()+2]==EVENT_CHANNEL_STATUS_RESPONSE + && mWaitForAck && mCurrentCommand==GET_EVENT_CHANNEL_STATUS_COMMAND){ + byte[] responseData = readBytes(EventChannelStatus.LENGTH, EVENT_CHANNEL_STATUS_RESPONSE); + stopTimerCheckForAckOrResp(); //cancel the ack timer + mWaitForAck=false; + mWaitForResponse=false; + if(responseData!=null){ + if(mBtCommsCrcModeCurrent != BT_CRC_MODE.OFF){ + clearCrcBytesFromBuffer(EVENT_CHANNEL_STATUS_RESPONSE); + } + takeEventChannelStatus(responseData); + } + processDataPacket(bufferTemp); + if(getListofInstructions().size()>0){ + removeInstruction(0); + } + mTransactionCompleted=true; + setInstructionStackLock(false); + clearBuffers(); + return; + } + //this is for LogAndStream support, command is transmitted and ack received else if(isSupportedInStreamCmds() && bufferTemp[getPacketSizeWithCrc()+2]==INSTREAM_CMD_RESPONSE){ printLogDataForDebugging("COMMAND TXed and ACK RECEIVED IN STREAM"); @@ -1187,7 +1219,13 @@ else if(isSupportedInStreamCmds() && bufferTemp[getPacketSizeWithCrc()+2]==INSTR if(mEventFramesPossible && inStreamResponseCommand!=null && inStreamResponseCommand[0]==EVENT_RECORD_RESPONSE){ processDataPacket(bufferTemp); - processAckWhileStreaming(); + if(mWaitForAck){ + processAckWhileStreaming(); + } + else { + // Nothing waits for an ACK, so the SET that went last must not be acknowledged again + printLogDataForDebugging("ACK with no command awaiting it, before an event record - ignored"); + } readEventFrameRestFromPort(); clearBuffers(); return; @@ -1238,12 +1276,30 @@ else if(isSupportedInStreamCmds() && bufferTemp[getPacketSizeWithCrc()+2]==INSTR else if(mEventFramesPossible && bufferTemp[0]==DATA_PACKET && bufferTemp[getPacketSizeWithCrc()+1]==INSTREAM_CMD_RESPONSE){ - if (mBtCommsCrcModeCurrent != BT_CRC_MODE.OFF && !checkCrc(bufferTemp, getPacketSize() + 1)) { - discardBufferBytesToNextPacket(); - return; + int packetEnd = getPacketSizeWithCrc()+1; + if (mBtCommsCrcModeCurrent != BT_CRC_MODE.OFF) { + //The packet's own CRC confirms it + if (!checkCrc(bufferTemp, getPacketSize() + 1)) { + discardBufferBytesToNextPacket(); + return; + } + } + else { + //With no link CRC, a 0x8A where the next packet should start is + //only a frame, and the packet before it only a packet, once the + //frame's own CRC checks out. Otherwise the boundary is wrong (a + //byte lost, say), and the bytes are discarded as before. + int frameLength = EventFrame.getFrameLength(bufferTemp, packetEnd, bufferTemp.length-packetEnd); + if (frameLength==EventFrame.NEED_MORE) { + return; //wait for the rest of the frame + } + if (frameLength==EventFrame.NOT_A_FRAME) { + discardBufferBytesToNextPacket(); + return; + } } processDataPacket(bufferTemp); - clearBytesFromStartOfBuffers(bufferTemp, getPacketSizeWithCrc()+1); + clearBytesFromStartOfBuffers(bufferTemp, packetEnd); } //Data packet followed by a NACK (a command refused while streaming, e.g. //any SET blocked by the firmware because it is sensing, or a log start the @@ -2164,7 +2220,14 @@ else if(responseCommand==RWC_RESPONSE) { } } else if(responseCommand==INSTREAM_CMD_RESPONSE) { - processInstreamResponse(false); + byte[] inStreamResponseCommand = readBytes(1, INSTREAM_CMD_RESPONSE); + if(inStreamResponseCommand!=null){ + processInstreamResponse(inStreamResponseCommand[0], false); + if(inStreamResponseCommand[0]==EVENT_RECORD_RESPONSE && mEventFramesPossible){ + // An event record frame carries its own CRC and never the link CRC (DEV-971) + responseWasParsed = false; + } + } } else if(responseCommand==LSM303DLHC_ACCEL_LPMODE_RESPONSE) { byte[] responseData = readBytes(1, responseCommand); @@ -2327,16 +2390,7 @@ else if(responseCommand==BT_FW_VERSION_STR_RESPONSE) { else if(responseCommand==EVENT_CHANNEL_STATUS_RESPONSE) { byte[] responseData = readBytes(EventChannelStatus.LENGTH, responseCommand); if(responseData!=null){ - EventChannelStatus status = EventChannelStatus.parse(responseData, 0); - mEventChannelStatus = status; - printLogDataForDebugging("Event channel status:\t" + status); - for(EventChannelListener listener:getEventChannelListeners()){ - try { - listener.onEventChannelStatus(this, status); - } catch (RuntimeException e) { - printLogDataForDebugging("Event channel listener threw: " + e); - } - } + takeEventChannelStatus(responseData); } } @@ -5510,13 +5564,31 @@ public boolean isEventStreamRequested() { * @return whether it was sent */ public boolean readEventChannelStatus() { - if(!Boolean.TRUE.equals(isEventChannelSupported()) || isStreaming()) { + if(!Boolean.TRUE.equals(isEventChannelSupported()) || isStreaming() || isStreamStartQueued()) { return false; } writeInstruction(new byte[]{GET_EVENT_CHANNEL_STATUS_COMMAND}); return true; } + /** + * Whether a start of streaming is queued or in flight: the instruction list + * keeps a command until it is answered, and isStreaming() turns true only + * then. A status read queued behind it would be answered between data packets. + */ + private boolean isStreamStartQueued() { + List instructions = getListofInstructions(); + synchronized(instructions){ + for(byte[] instruction:instructions){ + if(instruction!=null && instruction.length>0 + && (instruction[0]==START_STREAMING_COMMAND || instruction[0]==START_SDBT_COMMAND)){ + return true; + } + } + } + return false; + } + /** The last answer to {@link #readEventChannelStatus()}, or null */ public EventChannelStatus getEventChannelStatus() { return mEventChannelStatus; @@ -5626,6 +5698,20 @@ private void readEventFrameRestFromPort() { dispatchEventRecord(record); } + /** Keeps the event channel status's 9 bytes and hands them to each listener */ + private void takeEventChannelStatus(byte[] responseData) { + EventChannelStatus status = EventChannelStatus.parse(responseData, 0); + mEventChannelStatus = status; + printLogDataForDebugging("Event channel status:\t" + status); + for(EventChannelListener listener:getEventChannelListeners()){ + try { + listener.onEventChannelStatus(this, status); + } catch (RuntimeException e) { + printLogDataForDebugging("Event channel listener threw: " + e); + } + } + } + private void dispatchEventRecord(EventRecord record) { mEventFramesReceived++; printLogDataForDebugging("Event record:\t" + record); diff --git a/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00044_EventStreamReviewReproTest.java b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00044_EventStreamReviewReproTest.java new file mode 100644 index 000000000..f1272c148 --- /dev/null +++ b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00044_EventStreamReviewReproTest.java @@ -0,0 +1,339 @@ +package com.shimmerresearch.bluetooth; + +import static org.junit.Assert.*; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedDeque; + +import org.junit.After; +import org.junit.Test; + +import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_CRC_MODE; +import com.shimmerresearch.bluetooth.ShimmerBluetooth.BT_STATE; +import com.shimmerresearch.bluetooth.ShimmerBluetooth.EventChannelListener; +import com.shimmerresearch.bluetooth.ShimmerBluetooth.SHIMMER_FEATURE; +import com.shimmerresearch.comms.wiredProtocol.ShimmerCrc; +import com.shimmerresearch.driver.ShimmerObject; +import com.shimmerresearch.driver.shimmer2r3.EventChannelStatus; +import com.shimmerresearch.driver.shimmer2r3.EventRecord; +import com.shimmerresearch.driverUtilities.ShimmerVerDetails.FW_ID; +import com.shimmerresearch.driverUtilities.ShimmerVerDetails.HW_ID; +import com.shimmerresearch.driverUtilities.ShimmerVerObject; +import com.shimmerresearch.driverUtilities.UtilShimmer; +import com.shimmerresearch.pcDriver.ShimmerPC; +import com.shimmerresearch.shimmer3.communication.ByteCommunication; +import com.shimmerresearch.verisense.communication.ByteCommunicationListener; + +import jssc.SerialPortTimeoutException; + +/** + * Repro tests for the review findings on #348, written before any fix. Each + * asserts the behaviour the protocol needs; a failure here confirms the + * finding on the unchanged code. + */ +public class API_00044_EventStreamReviewReproTest { + + private static final int PACKET_SIZE = 9; + private static final ShimmerVerObject S3R = new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25); + + private static byte[] frame(int type, int seq, long ticks, int channel, int state) { + byte[] f = new byte[21]; + f[0] = (byte) 0x8A; + f[1] = (byte) 0xBB; + f[2] = 16; + f[3] = (byte) type; + f[5] = (byte) seq; + f[6] = (byte) (seq>>8); + for(int i=0;i<8;i++) { + f[7+i] = (byte) (ticks>>(8*i)); + } + f[15] = (byte) channel; + f[16] = (byte) state; + byte[] crc = ShimmerCrc.shimmerUartCrcCalc(f, 19); + f[19] = crc[0]; + f[20] = crc[1]; + return f; + } + + private static final byte[] PRESS = frame(EventRecord.TYPE_EDGE, 1, 0x357237185333L, EventRecord.CHANNEL_BUTTON, 1); + private static final byte[] RELEASE = frame(EventRecord.TYPE_EDGE, 2, 0x357237186333L, EventRecord.CHANNEL_BUTTON, 0); + + private static class Collected implements EventChannelListener { + final List records = Collections.synchronizedList(new ArrayList()); + final List statuses = Collections.synchronizedList(new ArrayList()); + @Override public void onEventRecord(ShimmerBluetooth shimmer, EventRecord record) { records.add(record); } + @Override public void onEventChannelStatus(ShimmerBluetooth shimmer, EventChannelStatus status) { statuses.add(status); } + } + + private final Collected mCollected = new Collected(); + private final List mAcksProcessed = Collections.synchronizedList(new ArrayList()); + + // ------------------------------------------------------------------ + // Streaming parser, fed one byte at a time + // ------------------------------------------------------------------ + + private static class QueueRadio implements ByteCommunication { + final Deque rx = new ArrayDeque(); + void queue(byte... bytes) { for(byte b:bytes) rx.add(b); } + @Override public byte[] readBytes(int n, int timeout) throws SerialPortTimeoutException { + if(rx.size() parsed() { + List out = new ArrayList(); + ShimmerBluetooth d = mStreaming; + for(RawBytePacketWithPCTimeStamp p:d.mABQPacketByeArray) out.add(UtilShimmer.bytesToHexStringWithSpacesFormatted(p.mDataArray)); + return out; + } + + @After + public void stopTimers() { + if(mStreaming!=null) { + mStreaming.stopTimerCheckForAckOrResp(); + mStreaming.stopTimerReadStatus(); + } + if(mIdle!=null) { + mIdle.stopTimerCheckForAckOrResp(); + mIdle.disconnectNoException(); + } + } + + /** + * Finding 2: an ACK with no command waiting for it, then a frame. The SET + * that went last must not have its ACK handling run a second time. + */ + @Test + public void finding2_anAckNobodyWaitsForBeforeAFrameDoesNotReRunTheLastSetsAck() { + streamingShimmer3r(BT_CRC_MODE.OFF); + alreadyOptedIn(); + // The last command was a SET that completed long ago + mStreaming.mCurrentCommand = ShimmerObject.SET_SAMPLING_RATE_COMMAND; + receive(dataPacket(payload(1), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.ACK_COMMAND_PROCESSED}, PRESS, + dataPacket(payload(2), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); + assertEquals("the record is taken", 1, mCollected.records.size()); + assertEquals("no SET's ACK is processed: none was in flight", Collections.emptyList(), mAcksProcessed); + } + + /** + * Finding 3: no link CRC, opted in, and a byte lost from a packet, so the + * parser's boundary falls one byte late and lands on a data byte of 0x8A. + * The misframed bytes must not be handed on as a packet; before #348 they + * were discarded to the next packet boundary. + */ + @Test + public void finding3_withoutACrcAMisframedPacketBeforeA0x8ADataByteIsNotTakenAsAPacket() { + streamingShimmer3r(BT_CRC_MODE.OFF); + alreadyOptedIn(); + byte[] good = dataPacket(payload(1), BT_CRC_MODE.OFF); + // Packet 2 loses its 4th byte on the link, and its 2nd byte happens to be 0x8A + byte[] p2 = new byte[] {0x20, (byte) 0x8A, 0x01, 0x02, 0x07, 0x05, 0x08, 0x3F, 0x09}; + byte[] p2Lost = new byte[1+p2.length-1]; + p2Lost[0] = ShimmerObject.DATA_PACKET; + System.arraycopy(p2, 0, p2Lost, 1, 3); + System.arraycopy(p2, 4, p2Lost, 4, p2.length-4); + byte[] p3 = dataPacket(new byte[] {(byte) 0x8A, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x00}, BT_CRC_MODE.OFF); + receive(good, p2Lost, p3, dataPacket(payload(4), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); + List got = parsed(); + // The bytes the parser framed as packet 2: 8 of p2's and the next packet's 0x00 header + byte[] misframed = new byte[PACKET_SIZE]; + System.arraycopy(p2Lost, 1, misframed, 0, p2Lost.length-1); + misframed[PACKET_SIZE-1] = ShimmerObject.DATA_PACKET; + assertFalse("misframed bytes " + UtilShimmer.bytesToHexStringWithSpacesFormatted(misframed) + " were taken as a packet: " + got, + got.contains(UtilShimmer.bytesToHexStringWithSpacesFormatted(misframed))); + } + + /** + * Finding 5, the consequence: a status reply, [ACK][0xBA][9], arriving + * between data packets is not taken, so the command never completes. + */ + @Test + public void finding5_aStatusReplyBetweenDataPacketsIsTaken() { + streamingShimmer3r(BT_CRC_MODE.OFF); + mStreaming.mCurrentCommand = ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND; + mStreaming.getListofInstructions().add(new byte[] {ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND}); + mStreaming.setInstructionStackLock(true); + mStreaming.mWaitForAck = true; + byte[] reply = new byte[] {ShimmerObject.ACK_COMMAND_PROCESSED, ShimmerObject.EVENT_CHANNEL_STATUS_RESPONSE, + 0x03, 0x0B, 0x02, 0x05, 0x00, 0x02, 0x00, 0x01, 0x00}; + receive(dataPacket(payload(1), BT_CRC_MODE.OFF), reply, dataPacket(payload(2), BT_CRC_MODE.OFF), + dataPacket(payload(3), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); + assertEquals("the status reply is taken", 1, mCollected.statuses.size()); + assertFalse("the command completes", mStreaming.mWaitForAck); + } + + /** + * Finding 5, the precondition: readEventChannelStatus() is queued behind a + * start of streaming that has not been acknowledged yet, so its reply comes + * once packets flow. + */ + @Test + public void finding5_theStatusIsNotQueuedBehindAStartOfStreaming() throws Exception { + ShimmerPC s = new ShimmerPC("COM98"); + s.setShimmerVersionObjectAndCreateSensorMap(S3R); + // As the probe leaves it on a unit with the event channel + java.lang.reflect.Method m = com.shimmerresearch.driver.ShimmerObject.class.getDeclaredMethod("setEventChannelSupported", Boolean.class); + m.setAccessible(true); + m.invoke(s, Boolean.TRUE); + s.startStreaming(); + boolean sent = s.readEventChannelStatus(); + boolean queuedAfterStart = false; + boolean startSeen = false; + for(byte[] ins:s.getListofInstructions()) { + if(ins[0]==ShimmerObject.START_STREAMING_COMMAND) startSeen = true; + if(startSeen && ins[0]==ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND) queuedAfterStart = true; + } + s.stopTimerCheckForAckOrResp(); + s.stopTimerReadStatus(); + assertFalse("the status is queued after a start of streaming (sent=" + sent + ")", queuedAfterStart); + } + + // ------------------------------------------------------------------ + // Idle, with the IOThread running + // ------------------------------------------------------------------ + + private static class AnsweringRadio implements ByteCommunication { + final ConcurrentLinkedDeque rx = new ConcurrentLinkedDeque(); + void queue(byte... bytes) { for(byte b:bytes) rx.add(b); } + @Override public boolean writeBytes(byte[] buffer) { queue(ShimmerObject.ACK_COMMAND_PROCESSED); return true; } + @Override public byte[] readBytes(int n, int timeout) throws SerialPortTimeoutException { + if(rx.size() Date: Fri, 13 Nov 2026 15:29:39 +0800 Subject: [PATCH 2/2] DEV-971: tests with a link CRC, race-free idle radios; keep records behind a bare ACK's CRC From the review of #349: - The idle tests' radios now take each burst whole and let reads wait for their bytes, as a serial port does (WaitingTestRadio), so the IOThread can no longer race the test's writes. API_00043's idle tests use it too. - The status-push, frame-after-ACK and status-reply tests now run with no link CRC, a 1-byte and a 2-byte one. - The misframing test checks that the good packets after the damaged one still arrive; the status-reply test that the command is retired, the lock released, the timer cancelled and the packets either side parsed. The CRC runs reproduced one more defect, which is fixed here: with a link CRC on (the driver turns it on at connect where the firmware has it), the records sent in the same burst as the opt-in's ACK were lost, 0 of 2. The bare ACK's link CRC is left after the ACK is taken; the idle path read it as an unknown byte and cleared the whole serial buffer, records included. With the event channel on, the idle path now drops only the bytes it read. All 7 tests in API_00044 fail on #348's code and pass here. ShimmerDriver 219/219, ShimmerDriverPC 155/155; the Java 8 MATLAB jar builds. Co-Authored-By: Claude Opus 5.5 --- .../bluetooth/ShimmerBluetooth.java | 18 +- .../bluetooth/API_00043_EventStreamTest.java | 58 ++--- .../API_00044_EventStreamReviewReproTest.java | 218 +++++++++++------- .../bluetooth/WaitingTestRadio.java | 114 +++++++++ 4 files changed, 279 insertions(+), 129 deletions(-) create mode 100644 ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/WaitingTestRadio.java diff --git a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java index ffad2b160..befd46761 100644 --- a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java +++ b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java @@ -1104,18 +1104,20 @@ else if(byteBuffer[0]==ACK_COMMAND_PROCESSED) { } if(byteBuffer!=null && byteBuffer[0]==INSTREAM_CMD_RESPONSE){ processResponseCommand(INSTREAM_CMD_RESPONSE); - /* The reply was read whole. With the event channel on, records - * may already be queued behind it (a status push when a press - * starts logging, say), so they are left for the next pass - * rather than cleared (DEV-971). */ - if(mEventFramesPossible) { - return; - } } } } - clearSerialBuffer(); + /* With the event channel on, records can be queued behind + * anything read here: behind a status push (when a press starts + * logging, say), or behind the link CRC a bare ACK leaves (the + * opt-in's ACK, whose first record follows at once). So only the + * bytes just read are dropped, and the rest are left for the next + * pass; clearing the buffer would wipe the records with them + * (DEV-971). */ + if(!mEventFramesPossible) { + clearSerialBuffer(); + } } } diff --git a/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00043_EventStreamTest.java b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00043_EventStreamTest.java index 80bdb05ac..455613db1 100644 --- a/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00043_EventStreamTest.java +++ b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00043_EventStreamTest.java @@ -331,73 +331,45 @@ public void framesAreNotParsedWithoutAnOptIn() { // Not streaming, with the IOThread running // ------------------------------------------------------------------ - /** Answers as LogAndStream_Shimmer3R v1.01.026 does */ - private static class AnsweringRadio implements ByteCommunication { - final ConcurrentLinkedDeque rx = new ConcurrentLinkedDeque(); - final List written = Collections.synchronizedList(new ArrayList()); + /** Answers as LogAndStream_Shimmer3R v1.01.026 does, each reply one burst */ + private static class AnsweringRadio extends WaitingTestRadio { /** Sent ahead of the next command's ACK, as a record already queued would be */ volatile byte[] beforeNextAck = null; /** Sent between the next status command's ACK and its reply */ volatile byte[] betweenAckAndReply = null; - void queue(byte... bytes) { - for(byte b:bytes){ - rx.add(b); - } - } - @Override - public boolean writeBytes(byte[] buffer) { - written.add(buffer.clone()); + byte[] answer(byte[] buffer) { + java.io.ByteArrayOutputStream reply = new java.io.ByteArrayOutputStream(); byte[] early = beforeNextAck; if(early!=null) { beforeNextAck = null; - queue(early); + reply.write(early, 0, early.length); } if(buffer[0]==ShimmerObject.SET_FEATURE && buffer[1]==(byte) SHIMMER_FEATURE.EVENT_STREAM.ordinal()){ - queue(ShimmerObject.ACK_COMMAND_PROCESSED); + reply.write(ShimmerObject.ACK_COMMAND_PROCESSED); if(buffer[2]!=0) { // The first record at the opt-in, then one already made - queue(INITIAL_STATE); - queue(MARKER_PRESS); + reply.write(INITIAL_STATE, 0, INITIAL_STATE.length); + reply.write(MARKER_PRESS, 0, MARKER_PRESS.length); } } else if(buffer[0]==ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND){ - queue(ShimmerObject.ACK_COMMAND_PROCESSED); + reply.write(ShimmerObject.ACK_COMMAND_PROCESSED); byte[] between = betweenAckAndReply; if(between!=null) { betweenAckAndReply = null; - queue(between); + reply.write(between, 0, between.length); } - queue(ShimmerObject.EVENT_CHANNEL_STATUS_RESPONSE); - queue(hex("03 0B 02 05 00 02 00 01 00")); + reply.write(ShimmerObject.EVENT_CHANNEL_STATUS_RESPONSE); + byte[] status = hex("03 0B 02 05 00 02 00 01 00"); + reply.write(status, 0, status.length); } else { - queue(ShimmerObject.ACK_COMMAND_PROCESSED); + reply.write(ShimmerObject.ACK_COMMAND_PROCESSED); } - return true; + return reply.toByteArray(); } - - @Override - public byte[] readBytes(int byteCount, int timeout) throws SerialPortTimeoutException { - if(rx.size() + * The streaming tests hand the parser one byte at a time on the test's thread. + * The idle tests run the IOThread over {@link WaitingTestRadio}, whose bursts + * arrive whole and whose reads wait, so the driver's reads cannot race the + * test's writes. */ public class API_00044_EventStreamReviewReproTest { private static final int PACKET_SIZE = 9; private static final ShimmerVerObject S3R = new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25); + private static final BT_CRC_MODE[] CRC_MODES = {BT_CRC_MODE.OFF, BT_CRC_MODE.ONE_BYTE_CRC, BT_CRC_MODE.TWO_BYTE_CRC}; private static byte[] frame(int type, int seq, long ticks, int channel, int state) { byte[] f = new byte[21]; @@ -60,14 +66,24 @@ private static byte[] frame(int type, int seq, long ticks, int channel, int stat return f; } + private static final byte[] INITIAL_STATE = frame(EventRecord.TYPE_INITIAL_STATE, 0, 0x357237100000L, EventRecord.CHANNEL_NONE, 0); private static final byte[] PRESS = frame(EventRecord.TYPE_EDGE, 1, 0x357237185333L, EventRecord.CHANNEL_BUTTON, 1); private static final byte[] RELEASE = frame(EventRecord.TYPE_EDGE, 2, 0x357237186333L, EventRecord.CHANNEL_BUTTON, 0); + /** A reply as the firmware frames it on a link with {@code crcMode}: its bytes, then the link CRC over them */ + private static byte[] withLinkCrc(byte[] bytes, BT_CRC_MODE crcMode) { + byte[] crc = ShimmerCrc.shimmerUartCrcCalc(bytes, bytes.length); + byte[] out = Arrays.copyOf(bytes, bytes.length+crcMode.getNumCrcBytes()); + System.arraycopy(crc, 0, out, bytes.length, crcMode.getNumCrcBytes()); + return out; + } + private static class Collected implements EventChannelListener { final List records = Collections.synchronizedList(new ArrayList()); final List statuses = Collections.synchronizedList(new ArrayList()); @Override public void onEventRecord(ShimmerBluetooth shimmer, EventRecord record) { records.add(record); } @Override public void onEventChannelStatus(ShimmerBluetooth shimmer, EventChannelStatus status) { statuses.add(status); } + void clear() { records.clear(); statuses.clear(); } } private final Collected mCollected = new Collected(); @@ -101,6 +117,12 @@ private static class QueueRadio implements ByteCommunication { private QueueRadio mQueue; private void streamingShimmer3r(BT_CRC_MODE crcMode) { + if(mStreaming!=null) { + mStreaming.stopTimerCheckForAckOrResp(); + mStreaming.stopTimerReadStatus(); + } + mCollected.clear(); + mAcksProcessed.clear(); mStreaming = new ShimmerPC("COM99") { private static final long serialVersionUID = 1L; @Override @@ -142,16 +164,17 @@ private static byte[] dataPacket(byte[] payload, BT_CRC_MODE crcMode) { byte[] f = new byte[1+payload.length]; f[0] = ShimmerObject.DATA_PACKET; System.arraycopy(payload, 0, f, 1, payload.length); - byte[] crc = ShimmerCrc.shimmerUartCrcCalc(f, f.length); - byte[] out = Arrays.copyOf(f, f.length+crcMode.getNumCrcBytes()); - System.arraycopy(crc, 0, out, f.length, crcMode.getNumCrcBytes()); - return out; + return withLinkCrc(f, crcMode); + } + + private static String hex(byte[] b) { + return UtilShimmer.bytesToHexStringWithSpacesFormatted(b); } private List parsed() { List out = new ArrayList(); ShimmerBluetooth d = mStreaming; - for(RawBytePacketWithPCTimeStamp p:d.mABQPacketByeArray) out.add(UtilShimmer.bytesToHexStringWithSpacesFormatted(p.mDataArray)); + for(RawBytePacketWithPCTimeStamp p:d.mABQPacketByeArray) out.add(hex(p.mDataArray)); return out; } @@ -169,7 +192,9 @@ public void stopTimers() { /** * Finding 2: an ACK with no command waiting for it, then a frame. The SET - * that went last must not have its ACK handling run a second time. + * that went last must not have its ACK handling run a second time. No link + * CRC: with one, a bare ACK goes through the older bare-ACK branch, which + * acknowledges unguarded for a data packet too (not changed here). */ @Test public void finding2_anAckNobodyWaitsForBeforeAFrameDoesNotReRunTheLastSetsAck() { @@ -181,59 +206,72 @@ public void finding2_anAckNobodyWaitsForBeforeAFrameDoesNotReRunTheLastSetsAck() dataPacket(payload(2), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); assertEquals("the record is taken", 1, mCollected.records.size()); assertEquals("no SET's ACK is processed: none was in flight", Collections.emptyList(), mAcksProcessed); + assertEquals(Arrays.asList(hex(payload(1)), hex(payload(2))), parsed()); } /** * Finding 3: no link CRC, opted in, and a byte lost from a packet, so the * parser's boundary falls one byte late and lands on a data byte of 0x8A. - * The misframed bytes must not be handed on as a packet; before #348 they - * were discarded to the next packet boundary. + * The misframed bytes must not be handed on as a packet, and the parser must + * resync so that the good packets after them still arrive. */ @Test public void finding3_withoutACrcAMisframedPacketBeforeA0x8ADataByteIsNotTakenAsAPacket() { streamingShimmer3r(BT_CRC_MODE.OFF); alreadyOptedIn(); byte[] good = dataPacket(payload(1), BT_CRC_MODE.OFF); - // Packet 2 loses its 4th byte on the link, and its 2nd byte happens to be 0x8A + // Packet 2 loses its 4th byte on the link byte[] p2 = new byte[] {0x20, (byte) 0x8A, 0x01, 0x02, 0x07, 0x05, 0x08, 0x3F, 0x09}; byte[] p2Lost = new byte[1+p2.length-1]; p2Lost[0] = ShimmerObject.DATA_PACKET; System.arraycopy(p2, 0, p2Lost, 1, 3); System.arraycopy(p2, 4, p2Lost, 4, p2.length-4); - byte[] p3 = dataPacket(new byte[] {(byte) 0x8A, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x00}, BT_CRC_MODE.OFF); - receive(good, p2Lost, p3, dataPacket(payload(4), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); - List got = parsed(); - // The bytes the parser framed as packet 2: 8 of p2's and the next packet's 0x00 header + // Packet 3's first data byte is 0x8A, where the late boundary lands + byte[] p3Payload = new byte[] {(byte) 0x8A, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x01}; + receive(good, p2Lost, dataPacket(p3Payload, BT_CRC_MODE.OFF), dataPacket(payload(4), BT_CRC_MODE.OFF), + dataPacket(payload(5), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); byte[] misframed = new byte[PACKET_SIZE]; System.arraycopy(p2Lost, 1, misframed, 0, p2Lost.length-1); misframed[PACKET_SIZE-1] = ShimmerObject.DATA_PACKET; - assertFalse("misframed bytes " + UtilShimmer.bytesToHexStringWithSpacesFormatted(misframed) + " were taken as a packet: " + got, - got.contains(UtilShimmer.bytesToHexStringWithSpacesFormatted(misframed))); + List got = parsed(); + assertFalse("misframed bytes " + hex(misframed) + " were taken as a packet: " + got, got.contains(hex(misframed))); + assertEquals("the good packets either side arrive, the damaged one does not", + Arrays.asList(hex(payload(1)), hex(p3Payload), hex(payload(4)), hex(payload(5))), got); } /** - * Finding 5, the consequence: a status reply, [ACK][0xBA][9], arriving - * between data packets is not taken, so the command never completes. + * Finding 5, the consequence, with each link CRC: a status reply, + * [ACK][0xBA][9], between data packets is taken, the command retired, the + * lock released and the packets either side parsed. */ @Test public void finding5_aStatusReplyBetweenDataPacketsIsTaken() { - streamingShimmer3r(BT_CRC_MODE.OFF); - mStreaming.mCurrentCommand = ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND; - mStreaming.getListofInstructions().add(new byte[] {ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND}); - mStreaming.setInstructionStackLock(true); - mStreaming.mWaitForAck = true; - byte[] reply = new byte[] {ShimmerObject.ACK_COMMAND_PROCESSED, ShimmerObject.EVENT_CHANNEL_STATUS_RESPONSE, - 0x03, 0x0B, 0x02, 0x05, 0x00, 0x02, 0x00, 0x01, 0x00}; - receive(dataPacket(payload(1), BT_CRC_MODE.OFF), reply, dataPacket(payload(2), BT_CRC_MODE.OFF), - dataPacket(payload(3), BT_CRC_MODE.OFF), new byte[] {ShimmerObject.DATA_PACKET}); - assertEquals("the status reply is taken", 1, mCollected.statuses.size()); - assertFalse("the command completes", mStreaming.mWaitForAck); + for(BT_CRC_MODE crcMode:CRC_MODES) { + streamingShimmer3r(crcMode); + mStreaming.mCurrentCommand = ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND; + mStreaming.getListofInstructions().add(new byte[] {ShimmerObject.GET_EVENT_CHANNEL_STATUS_COMMAND}); + mStreaming.setInstructionStackLock(true); + mStreaming.mWaitForAck = true; + mStreaming.startTimerCheckForAckOrResp(2); + byte[] reply = withLinkCrc(new byte[] {ShimmerObject.ACK_COMMAND_PROCESSED, ShimmerObject.EVENT_CHANNEL_STATUS_RESPONSE, + 0x03, 0x0B, 0x02, 0x05, 0x00, 0x02, 0x00, 0x01, 0x00}, crcMode); + receive(dataPacket(payload(1), crcMode), reply, dataPacket(payload(2), crcMode), + dataPacket(payload(3), crcMode), new byte[] {ShimmerObject.DATA_PACKET}); + String m = crcMode + ": "; + assertEquals(m + "the status reply is taken", 1, mCollected.statuses.size()); + assertEquals(m + "its values", 5, mCollected.statuses.get(0).getNextSequenceNumber()); + assertFalse(m + "no longer waits for the ACK", mStreaming.mWaitForAck); + assertTrue(m + "the command is retired", mStreaming.getListofInstructions().isEmpty()); + assertFalse(m + "the next instruction can be sent", mStreaming.isInstructionStackLock()); + assertNull(m + "the ACK timer is cancelled", mStreaming.mTimerCheckForAckOrResp); + assertEquals(m + "the packets either side are parsed", + Arrays.asList(hex(payload(1)), hex(payload(2)), hex(payload(3))), parsed()); + } } /** - * Finding 5, the precondition: readEventChannelStatus() is queued behind a - * start of streaming that has not been acknowledged yet, so its reply comes - * once packets flow. + * Finding 5, the precondition: readEventChannelStatus() is not queued + * behind a start of streaming that has not been acknowledged yet. */ @Test public void finding5_theStatusIsNotQueuedBehindAStartOfStreaming() throws Exception { @@ -253,41 +291,46 @@ public void finding5_theStatusIsNotQueuedBehindAStartOfStreaming() throws Except } s.stopTimerCheckForAckOrResp(); s.stopTimerReadStatus(); - assertFalse("the status is queued after a start of streaming (sent=" + sent + ")", queuedAfterStart); + assertFalse("refused", sent); + assertFalse("the status is queued after a start of streaming", queuedAfterStart); } // ------------------------------------------------------------------ // Idle, with the IOThread running // ------------------------------------------------------------------ - private static class AnsweringRadio implements ByteCommunication { - final ConcurrentLinkedDeque rx = new ConcurrentLinkedDeque(); - void queue(byte... bytes) { for(byte b:bytes) rx.add(b); } - @Override public boolean writeBytes(byte[] buffer) { queue(ShimmerObject.ACK_COMMAND_PROCESSED); return true; } - @Override public byte[] readBytes(int n, int timeout) throws SerialPortTimeoutException { - if(rx.size() + *
  • {@link #queue(byte[]...)} adds a burst whole, under the same lock reads + * take, so the IOThread never sees half of it;
  • + *
  • a read waits up to its timeout for the bytes it asks for, as a serial + * port does, rather than failing the moment they are short.
  • + * + * Subclasses answer what the driver writes by overriding {@link #answer(byte[])}. + */ +abstract class WaitingTestRadio implements ByteCommunication { + + private final Deque mRx = new ArrayDeque(); + final List written = Collections.synchronizedList(new ArrayList()); + + /** Adds the chunks as one burst: a read sees all of it or none of it */ + void queue(byte[]... chunks) { + synchronized(mRx) { + for(byte[] chunk:chunks) { + for(byte b:chunk) { + mRx.add(b); + } + } + } + } + + /** Adds single bytes as one burst */ + void queueBytes(byte... bytes) { + queue(bytes); + } + + /** The reply to one command the driver wrote, as one burst; empty for none */ + abstract byte[] answer(byte[] command); + + @Override + public boolean writeBytes(byte[] buffer) { + written.add(buffer.clone()); + byte[] reply = answer(buffer.clone()); + if(reply!=null && reply.length>0) { + queue(reply); + } + return true; + } + + @Override + public byte[] readBytes(int byteCount, int timeout) throws SerialPortTimeoutException { + long end = System.currentTimeMillis()+Math.max(timeout, 1); + while(true) { + synchronized(mRx) { + if(mRx.size()>=byteCount) { + byte[] out = new byte[byteCount]; + for(int i=0;i=end) { + throw new SerialPortTimeoutException("TEST", "readBytes", timeout); + } + try { + Thread.sleep(2); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new SerialPortTimeoutException("TEST", "readBytes", timeout); + } + } + } + + @Override + public int getInputBufferBytesCount() { + synchronized(mRx) { + return mRx.size(); + } + } + + @Override public boolean isOpened() { return true; } + @Override public boolean closePort() { return true; } + @Override public boolean openPort() { return true; } + @Override public boolean setParams(int i, int j, int k, int l) { return true; } + @Override public boolean purgePort(int i) { return true; } + @Override public void setByteCommunicationListener(ByteCommunicationListener byteCommListener) { } + @Override public void removeRadioListenerList() { } + + /** The bytes of several chunks, in order */ + static byte[] concat(byte[]... chunks) { + int n = 0; + for(byte[] c:chunks) { + n += c.length; + } + byte[] out = new byte[n]; + int at = 0; + for(byte[] c:chunks) { + System.arraycopy(c, 0, out, at, c.length); + at += c.length; + } + return out; + } + +}