From 4561b05480626dc1bb3bc21cc74092081caa070e Mon Sep 17 00:00:00 2001 From: Mark Nolan Date: Tue, 10 Nov 2026 00:53:51 +0000 Subject: [PATCH] DEV-1431: a log start the device refuses (NACK) ends at once, idle or mid-stream Firmware that cannot start a log (no SD card or a bad one, docked, on USB power, logging turned off in its configuration) is to NACK START_LOGGING_ONLY_COMMAND (0x92) and START_SDBT_COMMAND (0x70) and start nothing, including when 0x92 is sent in the middle of a stream. On master the driver dropped the 0xFE: when idle the ACK timer took START_LOGGING_ONLY for started and dropped the connection for START_SDBT; mid-stream the NACK went with the packet in front of it and the timer again took the device for logging. Built on DEV-982's NACK handling (processNackFromCommand), which unwinds the refused command and keeps the link. On top of it: - A refused log start is taken for a log that did not start (processLogStartRefused): the device is left not logging, the status reads startDataLogAndStreaming() stopped start again after START_SDBT, and eventLogStartRefused(command), a new protected hook, is called before eventCommandRefused. By default it passes LOG_START_REFUSED_MESSAGE to sendStatusMSGtoUI, which Android shows as a toast; ShimmerPC's is empty. - While streaming, a NACK after a data packet waits for its own link CRC (C5, or C5 56) and checks it, as a bare ACK's is: exactly the packet, the NACK and its CRC are consumed, and what follows stays as the next frame. DEV-982 cleared the whole buffer at the NACK, so the CRC landed where the next header should be and bytes already buffered were lost. A packet whose CRC fails is dropped without losing the NACK; a 0xFE whose CRC does not match is not a NACK; a NACK with no command in flight is ignored, as it is when not streaming. - processNackFromCommand() is protected, for ShimmerAndroidAPI's Shimmer, whose own streaming parser has to fail the command the same way. Tests: - API_00036_LogStartRefusedTest (idle, IOThread over an in-memory radio): refused log-only and combined starts, no CRC, 1- and 2-byte CRC, each handled at once with the next command answered; an ACKed start still logs. The radio now appends real CRCs. - API_00037_StreamingLogStartRefusedTest (the streaming parser): a 0x92 refused between two packets with no CRC, 1- and 2-byte CRC; still not logging after the ACK timer would have run; a corrupt packet before the NACK; the next frame already buffered; a 0xFE with the wrong CRC; a NACK with no command in flight. Against master's parser 9 of the 10 fail; against DEV-982's, 6. ShimmerDriver 178/178, ShimmerDriverPC 118/118. Co-Authored-By: Claude Opus 5.5 --- .../bluetooth/ShimmerBluetooth.java | 123 ++++++- .../API_00036_LogStartRefusedTest.java | 242 +++++++++++++ ...PI_00037_StreamingLogStartRefusedTest.java | 334 ++++++++++++++++++ 3 files changed, 685 insertions(+), 14 deletions(-) create mode 100644 ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00036_LogStartRefusedTest.java create mode 100644 ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00037_StreamingLogStartRefusedTest.java diff --git a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java index 1c980b362..c343d9eb8 100644 --- a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java +++ b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java @@ -304,6 +304,9 @@ public int getNumCrcBytes() { * first. */ private static final byte[] BARE_ACK_CRC = ShimmerCrc.shimmerUartCrcCalc(new byte[] {ACK_COMMAND_PROCESSED}, 1); + + /** The same for a NACK, the refusal of a command: the CRC of 0xFE is C5 56. */ + private static final byte[] BARE_NACK_CRC = ShimmerCrc.shimmerUartCrcCalc(new byte[] {NACK_COMMAND_PROCESSED}, 1); public enum SHIMMER_FEATURE { NONE, @@ -1132,23 +1135,42 @@ else if(isSupportedInStreamCmds() && bufferTemp[getPacketSizeWithCrc()+2]==INSTR } //Data packet followed by a NACK (a command refused while streaming, e.g. - //any SET blocked by the firmware because it is sensing) + //any SET blocked by the firmware because it is sensing, or a log start the + //device cannot carry out, DEV-1431) else if(bufferTemp[0]==DATA_PACKET && bufferTemp[getPacketSizeWithCrc()+1]==NACK_COMMAND_PROCESSED){ - - if (mBtCommsCrcModeCurrent != BT_CRC_MODE.OFF && !checkCrc(bufferTemp, getPacketSize() + 1)) { + + //With a link CRC on, the NACK is followed by its own CRC, as a bare ACK + //is, rather than by the next packet + if(!isBareNackCrcSoFar(bufferTemp)){ + printLogDataForDebugging("0xFE after a data packet is not a NACK: its CRC does not match"); discardBufferBytesToNextPacket(); return; } - - //Handle the data packet first, then fail the command in flight - processDataPacket(bufferTemp); - processNackFromCommand(); - - /* clearBuffers() rather than clearSingleDataPacketFromBuffers(), - * because the NACK is a single byte with no payload behind it and that - * helper would push it back as the next packet header. */ - clearBuffers(); + int bareNackEnd = getPacketSizeWithCrc()+2+mBtCommsCrcModeCurrent.getNumCrcBytes(); + if(bufferTemp.lengthA refused log start is also taken for a log that did not start + * ({@link #processLogStartRefused(byte)}). + * + *

Protected because ShimmerAndroidAPI's Shimmer has its own streaming + * parser, which needs to fail the command in flight the same way. */ - private void processNackFromCommand() { + protected void processNackFromCommand() { stopTimerCheckForAckOrResp(); //cancel the ack timer printLogDataForDebugging("NACK Received for Command: \t\t" + btCommandToString(mCurrentCommand)); @@ -2222,7 +2267,10 @@ private void processNackFromCommand() { mTransactionCompleted=true; setInstructionStackLock(false); - + + if(refusedCommand==START_LOGGING_ONLY_COMMAND || refusedCommand==START_SDBT_COMMAND){ + processLogStartRefused(refusedCommand); + } eventCommandRefused(refusedCommand); } @@ -3419,6 +3467,53 @@ else if(mCurrentCommand==GET_SHIMMER_VERSION_COMMAND_NEW){ //in case the new com // //NOT USED // } + /** + * A log start the device refused with a NACK (DEV-1431), its transaction already unwound by + * {@link #processNackFromCommand()}. + *

+ * The firmware starts a log only when the device is undocked, off USB power, has an SD card in + * with no file error and has logging turned on in its configuration, and firmware that refuses + * a start it cannot carry out starts nothing: after START_SDBT the device is not streaming + * either. It refuses START_LOGGING_ONLY in the middle of a stream the same way, the NACK then + * coming between two data packets. Earlier firmware ACKs such a start instead and does + * nothing, so there the status bits are what tell. + *

+ * Without this, a refusal ended as an unanswered start does: the ACK timer's special case + * (checkForAckOrRespTask) took START_LOGGING_ONLY for started. Here the device is left not + * logging, the status reads that startDataLogAndStreaming() stopped start again, and + * {@link #eventLogStartRefused(byte)} says so. + * + * @param refused the start that was refused + */ + private void processLogStartRefused(byte refused) { + printLogDataForDebugging(btCommandToString(refused) + " refused: the device cannot log now"); + setIsSDLogging(false); + if(refused==START_SDBT_COMMAND){ + // After the refused start is retired: the first read is immediate, and skipped while + // any instruction is still queued + startTimerReadStatus(); + } + eventLogStartRefused(refused); + } + + /** What {@link #eventLogStartRefused(byte)} passes to {@link #sendStatusMSGtoUI(String)} by default. */ + public static final String LOG_START_REFUSED_MESSAGE = "The Shimmer refused to start logging to its SD card. " + + "It logs only when undocked, off USB power, with an SD card in and no SD file error, " + + "and with logging turned on in its configuration."; + + /** + * The device refused a log start (START_LOGGING_ONLY_COMMAND or START_SDBT_COMMAND) with a NACK: + * it is not logging. After START_SDBT it is not streaming either; a stream that was running when + * START_LOGGING_ONLY was sent goes on. {@link #eventCommandRefused(byte)} is called for it too, + * after this. By default the reason goes to + * {@link #sendStatusMSGtoUI(String)}; override to tell the user another way. + * + * @param command the start that was refused + */ + protected void eventLogStartRefused(byte command) { + sendStatusMSGtoUI(LOG_START_REFUSED_MESSAGE); + } + private void killConnection(){ printLogDataForDebugging("Killing Connection"); stop(); //If command fail exit device diff --git a/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00036_LogStartRefusedTest.java b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00036_LogStartRefusedTest.java new file mode 100644 index 000000000..305c6ffbc --- /dev/null +++ b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00036_LogStartRefusedTest.java @@ -0,0 +1,242 @@ +package com.shimmerresearch.bluetooth; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Collections; +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.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.pcDriver.ShimmerPC; +import com.shimmerresearch.shimmer3.communication.ByteCommunication; +import com.shimmerresearch.verisense.communication.ByteCommunicationListener; + +import jssc.SerialPortTimeoutException; + +/** + * DEV-1431: firmware that cannot start a log (no SD card or a bad one, docked, on USB power, logging + * turned off in its configuration) NACKs START_LOGGING_ONLY_COMMAND and START_SDBT_COMMAND and starts + * nothing. The driver had no NACK handling: it dropped the 0xFE as a stray byte and waited out the ACK + * timer, which then took START_LOGGING_ONLY for started (checkForAckOrRespTask's Consensys special + * case) and dropped the connection for START_SDBT. + *

+ * Now either NACK retires its command at once: the device is left not logging (and not streaming), + * eventLogStartRefused() is called, the connection is kept and the next command goes out. The same + * refusal in the middle of a stream is API_00037_StreamingLogStartRefusedTest. + *

+ * No hardware: the IOThread runs as connect() starts it, over an in-memory radio that answers as the + * firmware does. It lives in this package because mIOThread is a protected member of ShimmerBluetooth. + */ +public class API_00036_LogStartRefusedTest { + + /** Idle on a Shimmer3R: an SD card in, the clock set, not sensing; status byte 1 empty */ + private static final byte[] STATUS_IDLE = {0x24, 0x00}; + + private static class AnsweringRadio implements ByteCommunication { + final ConcurrentLinkedDeque rx = new ConcurrentLinkedDeque(); + final List written = Collections.synchronizedList(new ArrayList()); + /** What a log start gets: an ACK, or a NACK as firmware that refuses it sends */ + volatile byte startReply = ShimmerObject.NACK_COMMAND_PROCESSED; + /** How many bytes of link CRC the firmware appends to every reply */ + volatile int crcBytes = 0; + + void reply(byte... bytes) { + for(byte b:bytes){ + rx.add(b); + } + byte[] crc = ShimmerCrc.shimmerUartCrcCalc(bytes, bytes.length); + for(int i=0;i mRefused = Collections.synchronizedList(new ArrayList()); + + @After + public void tearDown() { + if(mDevice!=null){ + mDevice.stopTimerCheckForAckOrResp(); + mDevice.stopTimerReadStatus(); + mDevice.disconnectNoException(); + } + } + + /** An initialised, idle Shimmer3R on LogAndStream, its IOThread running as connect() starts it */ + private AnsweringRadio idleShimmer3r(BT_CRC_MODE crc) { + AnsweringRadio radio = new AnsweringRadio(); + radio.crcBytes = crc.getNumCrcBytes(); + mDevice = new ShimmerPC("COM99") { + @Override + protected void eventLogStartRefused(byte command) { + mRefused.add(command); + super.eventLogStartRefused(command); + } + }; + mDevice.setTestRadio(radio); + mDevice.setShimmerVersionObjectAndCreateSensorMap(new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25)); + mDevice.setCurrentBtCommsCrcMode(crc); + mDevice.setIsInitialised(true); + mDevice.setBluetoothRadioState(BT_STATE.CONNECTED); + mDevice.mIOThread = mDevice.new IOThread(); + mDevice.mIOThread.start(); + return radio; + } + + private void waitFor(long timeoutMs, java.util.function.BooleanSupplier done) throws InterruptedException { + long end = System.currentTimeMillis()+timeoutMs; + while(!done.getAsBoolean() && System.currentTimeMillis() !mRefused.isEmpty()); + long took = System.currentTimeMillis()-sentAt; + assertEquals("eventLogStartRefused, once, for the start sent", Collections.singletonList(command), mRefused); + assertTrue("refused at once, not after the ACK timer (" + took + " ms)", took < 1500); + assertFalse("the device is not taken to be logging", mDevice.isSDLogging()); + assertFalse("nor streaming", mDevice.isStreaming()); + assertNotEquals("the connection is kept", BT_STATE.CONNECTION_LOST, mDevice.getBluetoothRadioState()); + + // The next command goes out and is answered: nothing is left waiting on the refused start + mDevice.writeAccelRange(1); + waitFor(3000, () -> radio.wrote(ShimmerObject.SET_ACCEL_SENSITIVITY_COMMAND) && mDevice.getListofInstructions().isEmpty()); + assertTrue("the next command was sent", radio.wrote(ShimmerObject.SET_ACCEL_SENSITIVITY_COMMAND)); + assertTrue("and acknowledged", mDevice.getListofInstructions().isEmpty()); + assertNotEquals("the connection is still kept", BT_STATE.CONNECTION_LOST, mDevice.getBluetoothRadioState()); + } + + @Test + public void aRefusedLogOnlyStartLeavesTheDeviceNotLogging() throws Exception { + AnsweringRadio radio = idleShimmer3r(BT_CRC_MODE.OFF); + long sentAt = System.currentTimeMillis(); + mDevice.startSDLogging(); + waitFor(2000, () -> radio.wrote(ShimmerObject.START_LOGGING_ONLY_COMMAND)); + assertTrue("START_LOGGING_ONLY was sent", radio.wrote(ShimmerObject.START_LOGGING_ONLY_COMMAND)); + assertRefusedAtOnce(radio, ShimmerObject.START_LOGGING_ONLY_COMMAND, sentAt); + } + + /** + * The NACK's CRC (C5, or C5 56) is left unread, as an ACK's is when not streaming, and the reply + * to the next command is found past it + */ + private void aRefusedLogOnlyStartWithALinkCrc(BT_CRC_MODE crc) throws Exception { + AnsweringRadio radio = idleShimmer3r(crc); + long sentAt = System.currentTimeMillis(); + mDevice.startSDLogging(); + waitFor(2000, () -> radio.wrote(ShimmerObject.START_LOGGING_ONLY_COMMAND)); + assertRefusedAtOnce(radio, ShimmerObject.START_LOGGING_ONLY_COMMAND, sentAt); + } + + @Test + public void aRefusedLogOnlyStartWithAOneByteCrcLetsTheNextCommandThrough() throws Exception { + aRefusedLogOnlyStartWithALinkCrc(BT_CRC_MODE.ONE_BYTE_CRC); + } + + @Test + public void aRefusedLogOnlyStartWithATwoByteCrcLetsTheNextCommandThrough() throws Exception { + aRefusedLogOnlyStartWithALinkCrc(BT_CRC_MODE.TWO_BYTE_CRC); + } + + @Test + public void aRefusedStreamAndLogStartStartsNothingAndKeepsTheConnection() throws Exception { + AnsweringRadio radio = idleShimmer3r(BT_CRC_MODE.OFF); + long sentAt = System.currentTimeMillis(); + mDevice.startDataLogAndStreaming(); + waitFor(2000, () -> radio.wrote(ShimmerObject.START_SDBT_COMMAND)); + assertTrue("START_SDBT was sent", radio.wrote(ShimmerObject.START_SDBT_COMMAND)); + assertRefusedAtOnce(radio, ShimmerObject.START_SDBT_COMMAND, sentAt); + // startDataLogAndStreaming() stopped the status reads; the refusal starts them again + waitFor(2000, () -> radio.wrote(ShimmerObject.GET_STATUS_COMMAND)); + assertTrue("the status is read again", radio.wrote(ShimmerObject.GET_STATUS_COMMAND)); + } + + /** An ACKed start is unchanged: the device is taken to be logging, as before */ + @Test + public void anAcknowledgedLogOnlyStartStillLogs() throws Exception { + AnsweringRadio radio = idleShimmer3r(BT_CRC_MODE.OFF); + radio.startReply = ShimmerObject.ACK_COMMAND_PROCESSED; + mDevice.startSDLogging(); + waitFor(2000, () -> mDevice.isSDLogging()); + assertTrue("logging after the ACK", mDevice.isSDLogging()); + assertTrue("no refusal", mRefused.isEmpty()); + } +} diff --git a/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00037_StreamingLogStartRefusedTest.java b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00037_StreamingLogStartRefusedTest.java new file mode 100644 index 000000000..1d5c9f446 --- /dev/null +++ b/ShimmerDriverPC/src/test/java/com/shimmerresearch/bluetooth/API_00037_StreamingLogStartRefusedTest.java @@ -0,0 +1,334 @@ +package com.shimmerresearch.bluetooth; + +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +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 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.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; +import com.shimmerresearch.pcDriver.ShimmerPC; +import com.shimmerresearch.shimmer3.communication.ByteCommunication; +import com.shimmerresearch.verisense.communication.ByteCommunicationListener; + +import jssc.SerialPortTimeoutException; + +/** + * DEV-1431, while streaming: firmware that cannot start a log refuses START_LOGGING_ONLY_COMMAND in + * the middle of a stream as it does when idle (docked or on USB power, no SD card or a bad one, + * logging turned off in its configuration), and its NACK comes between two data packets, followed + * by its own link CRC when the link has one (C5, or C5 56). + *

+ * On master the NACK was thrown away with the packet in front of it, and 2 s later the ACK timer's + * special case took the device for logging. DEV-982's branch for a data packet followed by a NACK + * did not wait for the NACK's CRC: it cleared the whole buffer at the NACK, so the CRC arrived + * where the next packet's header should be (a parse error, then a resync), and any bytes already + * buffered after the NACK went with it. A data packet whose CRC failed took the NACK with it, a + * 0xFE whose CRC did not match was still taken for one, and a NACK with no command in flight + * refused whichever command had gone last. Nor was a refused log start told apart from any other + * refusal. + *

+ * Now the packet before the NACK is kept, the NACK's CRC is checked and consumed, the refusal + * retires the command, the device is not taken to be logging, the stream goes on, and + * eventLogStartRefused() is called. + *

+ * No hardware: the parser reads from an in-memory byte queue, one byte at a time as the IO thread + * does, as in API_00027_StreamingBareAckCrcTest. + * + * @author Mark Nolan + */ +public class API_00037_StreamingLogStartRefusedTest { + + /** Bytes after the DATA_PACKET byte: a 3-byte timestamp and three 2-byte channels */ + private static final int PACKET_SIZE = 9; + + 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 byteCount, int timeout) throws SerialPortTimeoutException { + if(rx.size() mLogStartsRefused = Collections.synchronizedList(new ArrayList()); + private final List mCommandsRefused = Collections.synchronizedList(new ArrayList()); + + @After + public void stopTimers() { + if(mDevice!=null){ + mDevice.stopTimerCheckForAckOrResp(); + mDevice.stopTimerReadStatus(); + } + } + + /** A Shimmer3R on LogAndStream v1.01.025 part way through streaming PACKET_SIZE-byte packets */ + private void streamingShimmer3r(BT_CRC_MODE crcMode) { + mDevice = new ShimmerPC("COM99") { + @Override + protected void eventLogStartRefused(byte command) { + mLogStartsRefused.add(command); + super.eventLogStartRefused(command); + } + + @Override + protected void eventCommandRefused(byte command) { + mCommandsRefused.add(command); + } + }; + mRadio = new QueueRadio(); + mDevice.setTestRadio(mRadio); + mDevice.setShimmerVersionObjectAndCreateSensorMap(new ShimmerVerObject(HW_ID.SHIMMER_3R, FW_ID.LOGANDSTREAM, 1, 1, 25)); + mDevice.setPacketSize(PACKET_SIZE); + mDevice.setCurrentBtCommsCrcMode(crcMode); + mDevice.setIsStreaming(true); + mDevice.setBluetoothRadioState(BT_STATE.STREAMING); + // Queue each parsed packet rather than build an ObjectCluster from it + mDevice.mUseProcessingThread = true; + } + + /** startSDLogging() while streaming, and the IO thread sending its START_LOGGING_ONLY */ + private void startSdLoggingWhileStreaming() { + mDevice.startSDLogging(); + assertEquals("only START_LOGGING_ONLY_COMMAND is queued", 1, mDevice.getListofInstructions().size()); + mDevice.mCurrentCommand = mDevice.getListofInstructions().get(0)[0]; + assertEquals(ShimmerObject.START_LOGGING_ONLY_COMMAND, mDevice.mCurrentCommand); + mDevice.setInstructionStackLock(true); + mDevice.mWaitForAck = true; + mDevice.startTimerCheckForAckOrResp(2); + } + + /** Hands the bytes to the streaming parser one at a time, as the IO thread does */ + private void receive(byte[]... frames) { + for(byte[] frame:frames){ + mRadio.queue(frame); + } + while(!mRadio.rx.isEmpty()){ + mDevice.processWhileStreaming(); + } + } + + /** Has a 0x00, a 0xFE and a 0xFF in it, which a resync would take for the start of a frame */ + private static byte[] payload(int i) { + return new byte[] {(byte) (0x10*i), 0x00, 0x01, (byte) 0xFF, 0x07, (byte) 0xFE, 0x08, 0x3F, 0x09}; + } + + private static byte[] dataPacket(byte[] payload, BT_CRC_MODE crcMode) { + byte[] frame = new byte[1+payload.length]; + frame[0] = ShimmerObject.DATA_PACKET; + System.arraycopy(payload, 0, frame, 1, payload.length); + return withCrc(frame, crcMode); + } + + /** The firmware's refusal, with its link CRC */ + private static byte[] bareNack(BT_CRC_MODE crcMode) { + return withCrc(new byte[] {ShimmerObject.NACK_COMMAND_PROCESSED}, crcMode); + } + + /** The frame followed by the link CRC over all of it, low byte first */ + private static byte[] withCrc(byte[] frame, BT_CRC_MODE crcMode) { + byte[] crc = ShimmerCrc.shimmerUartCrcCalc(frame, frame.length); + byte[] framed = Arrays.copyOf(frame, frame.length+crcMode.getNumCrcBytes()); + System.arraycopy(crc, 0, framed, frame.length, crcMode.getNumCrcBytes()); + return framed; + } + + private static String hex(byte[] bytes) { + return UtilShimmer.bytesToHexStringWithSpacesFormatted(bytes); + } + + private void assertParsed(byte[]... expectedPayloads) { + List expected = new ArrayList(); + for(byte[] payload:expectedPayloads){ + expected.add(hex(payload)); + } + List parsed = new ArrayList(); + // Package-private, so ShimmerPC does not inherit it + ShimmerBluetooth device = mDevice; + for(RawBytePacketWithPCTimeStamp packet:device.mABQPacketByeArray){ + parsed.add(hex(packet.mDataArray)); + } + assertEquals("every good data packet is parsed, once and in order", expected, parsed); + } + + /** What is left in the parser's buffer */ + private void assertBuffered(byte... expected) { + assertEquals(hex(expected), hex(mDevice.mByteArrayOutputStream.toByteArray())); + } + + /** The start retired as refused, the device not logging and still streaming */ + private void assertRefused() { + assertFalse("the NACK is taken", mDevice.mWaitForAck); + assertFalse("the next instruction can be sent", mDevice.isInstructionStackLock()); + assertNull("the ACK timer is cancelled, so its special case cannot take the device for logging", + mDevice.mTimerCheckForAckOrResp); + assertTrue("the refused start is retired", mDevice.getListofInstructions().isEmpty()); + assertFalse("the device is not taken to be logging", mDevice.isSDLogging()); + assertTrue("the stream goes on", mDevice.isStreaming()); + assertEquals(BT_STATE.STREAMING, mDevice.getBluetoothRadioState()); + assertEquals("eventLogStartRefused, once", Collections.singletonList(ShimmerObject.START_LOGGING_ONLY_COMMAND), + mLogStartsRefused); + assertEquals("eventCommandRefused, once", Collections.singletonList(ShimmerObject.START_LOGGING_ONLY_COMMAND), + mCommandsRefused); + } + + private void refusedBetweenTwoPackets(BT_CRC_MODE crcMode) { + streamingShimmer3r(crcMode); + startSdLoggingWhileStreaming(); + receive(dataPacket(payload(1), crcMode), bareNack(crcMode), + dataPacket(payload(2), crcMode), dataPacket(payload(3), crcMode), new byte[] {ShimmerObject.DATA_PACKET}); + assertRefused(); + assertParsed(payload(1), payload(2), payload(3)); + assertBuffered(ShimmerObject.DATA_PACKET); + } + + @Test + public void aLogStartRefusedMidStreamWithoutACrc() { + refusedBetweenTwoPackets(BT_CRC_MODE.OFF); + } + + @Test + public void aLogStartRefusedMidStreamWithAOneByteCrc() { + refusedBetweenTwoPackets(BT_CRC_MODE.ONE_BYTE_CRC); + } + + @Test + public void aLogStartRefusedMidStreamWithATwoByteCrc() { + refusedBetweenTwoPackets(BT_CRC_MODE.TWO_BYTE_CRC); + } + + /** The refusal is not left to the ACK timer, which would take the device for logging 2 s on */ + @Test + public void theAckTimerDoesNotLaterTakeTheDeviceForLogging() throws Exception { + refusedBetweenTwoPackets(BT_CRC_MODE.ONE_BYTE_CRC); + Thread.sleep(2500); + assertFalse("still not logging after the ACK timer would have run out", mDevice.isSDLogging()); + } + + /** + * The NACK's own CRC shows it is a NACK, so a corrupt data packet ahead of it is dropped without + * losing the refusal + */ + private void refusedAfterACorruptPacket(BT_CRC_MODE crcMode, int indexToCorrupt) { + streamingShimmer3r(crcMode); + startSdLoggingWhileStreaming(); + byte[] corrupt = dataPacket(payload(1), crcMode); + corrupt[indexToCorrupt] ^= 0x01; + receive(corrupt, bareNack(crcMode), dataPacket(payload(2), crcMode), new byte[] {ShimmerObject.DATA_PACKET}); + assertRefused(); + assertParsed(payload(2)); + assertBuffered(ShimmerObject.DATA_PACKET); + } + + @Test + public void aRefusalWithAOneByteCrcAfterACorruptPacket() { + refusedAfterACorruptPacket(BT_CRC_MODE.ONE_BYTE_CRC, 1); + } + + /** Only the packet CRC's second byte is wrong, which is checked separately */ + @Test + public void aRefusalWithATwoByteCrcAfterACorruptPacket() { + refusedAfterACorruptPacket(BT_CRC_MODE.TWO_BYTE_CRC, 1+PACKET_SIZE+1); + } + + /** + * After a resync the buffer can already hold bytes beyond the NACK. Exactly the packet, the + * NACK and its CRC are consumed, and the rest stay as the start of the next frame. + */ + private void refusedWithTheNextFrameAlreadyBuffered(BT_CRC_MODE crcMode) throws Exception { + streamingShimmer3r(crcMode); + startSdLoggingWhileStreaming(); + byte[] nextFrameStart = Arrays.copyOf(dataPacket(payload(2), crcMode), 4); + ByteArrayOutputStream buffered = new ByteArrayOutputStream(); + buffered.write(dataPacket(payload(1), crcMode)); + buffered.write(bareNack(crcMode)); + buffered.write(nextFrameStart); + mDevice.mByteArrayOutputStream.write(buffered.toByteArray()); + for(long timestamp=0;timestamp