diff --git a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java index 7a7a47e10..69a1ffc70 100644 --- a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java +++ b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java @@ -293,6 +293,13 @@ public int getNumCrcBytes() { } } + /** + * With a link CRC on, the firmware sends one after a bare ACK too (the reply + * to a SET command). It is the CRC of the single byte 0xFF: F4 65, low byte + * first. + */ + private static final byte[] BARE_ACK_CRC = ShimmerCrc.shimmerUartCrcCalc(new byte[] {ACK_COMMAND_PROCESSED}, 1); + public enum SHIMMER_FEATURE { NONE, RN4678_ERROR_DETECTION, @@ -958,6 +965,30 @@ protected void processPacket() { //Data packet followed by an ACK (suggesting an ACK in response to a SET BT command or else a BT response command) else if(bufferTemp[0]==DATA_PACKET && bufferTemp[getPacketSizeWithCrc()+1]==ACK_COMMAND_PROCESSED){ + + //With a link CRC on, a bare ACK is followed by its own CRC rather than + //by the next packet + if(isBareAckCrcSoFar(bufferTemp)){ + int bareAckEnd = getPacketSizeWithCrc()+2+mBtCommsCrcModeCurrent.getNumCrcBytes(); + if(bufferTemp.lengthgetPacketSizeWithCrc()+2){ if(bufferTemp[getPacketSizeWithCrc()+2]==DATA_PACKET){ @@ -966,16 +997,7 @@ else if(bufferTemp[0]==DATA_PACKET clearSingleDataPacketFromBuffers(bufferTemp, getPacketSizeWithCrc()+2); //Then handle the ACK from the last SET command - if(isKnownSetCommand(mCurrentCommand)){ - stopTimerCheckForAckOrResp(); //cancel the ack timer - mWaitForAck=false; - - processAckFromSetCommand(mCurrentCommand); - - mTransactionCompleted = true; - setInstructionStackLock(false); - } - printLogDataForDebugging("Ack Received for Command: \t\t\t" + btCommandToString(mCurrentCommand)); + processAckWhileStreaming(); } //this is for LogAndStream support, command is transmitted and ack received @@ -1048,6 +1070,10 @@ private static boolean isKnownResponse(byte response) { return mBtResponseMap.containsKey(response); } + /** + * Checks the CRC of the data packet at the start of bufferTemp. It leaves the + * buffers alone, so the caller decides what to discard. + */ public boolean checkCrc(byte[] bufferTemp, int length) { byte[] crcCalc = ShimmerCrc.shimmerUartCrcCalc(bufferTemp, length); @@ -1061,13 +1087,45 @@ public boolean checkCrc(byte[] bufferTemp, int length) { if (mBtCommsCrcModeCurrent == BT_CRC_MODE.TWO_BYTE_CRC) { // + 2 as this is the location of the CRC's MSB if (bufferTemp[getPacketSize() + 2] != crcCalc[1]) { - discardBufferBytesToNextPacket(); return false; } } return true; } + /** + * Whether the bytes received so far after the ACK that follows a data packet + * are the CRC on a bare ACK. Nothing else can start that way: an in-stream + * response starts 0x8A, a data packet 0x00, and no response opcode is 0xF4. + */ + private boolean isBareAckCrcSoFar(byte[] bufferTemp) { + int crcStart = getPacketSizeWithCrc()+2; + int numCrcBytesReceived = Math.min(bufferTemp.length-crcStart, mBtCommsCrcModeCurrent.getNumCrcBytes()); + if(numCrcBytesReceived<=0){ + return false; + } + for(int i=0;i + * No hardware: the parser reads from an in-memory byte queue, one byte at a + * time as the IO thread does. It lives in this package because the parser and + * its state are protected members of ShimmerBluetooth. + * + * @author Mark Nolan + */ +public class API_00027_StreamingBareAckCrcTest { + + /** 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() 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); + } + + private void assertAckProcessed() { + assertFalse("the ACK is taken", mDevice.mWaitForAck); + assertFalse("the next instruction can be sent", mDevice.isInstructionStackLock()); + assertNull("the ACK timer is cancelled, so it cannot clear the instruction queue", mDevice.mTimerCheckForAckOrResp); + } + + /** What is left in the parser's buffer, each byte with its PC timestamp */ + private void assertBuffered(byte... expected) { + assertEquals(hex(expected), hex(mDevice.mByteArrayOutputStream.toByteArray())); + assertEquals("one PC timestamp per buffered byte", expected.length, mDevice.mListofPCTimeStamps.size()); + } + + /** + * startSDLogging() while streaming sends SET_RWC_COMMAND and then + * START_LOGGING_ONLY_COMMAND, and the firmware answers each with a bare ACK + */ + private void startSdLoggingWhileStreaming(BT_CRC_MODE crcMode) { + streamingShimmer3r(crcMode); + mDevice.startSDLogging(); + + sendNextInstruction(); + assertEquals(ShimmerObject.SET_RWC_COMMAND, mDevice.mCurrentCommand); + receive(dataPacket(payload(1), crcMode), bareAck(crcMode), + dataPacket(payload(2), crcMode), dataPacket(payload(3), crcMode)); + assertAckProcessed(); + assertEquals("START_LOGGING_ONLY_COMMAND is still queued", 1, mDevice.getListofInstructions().size()); + + sendNextInstruction(); + assertEquals(ShimmerObject.START_LOGGING_ONLY_COMMAND, mDevice.mCurrentCommand); + receive(dataPacket(payload(4), crcMode), bareAck(crcMode), + dataPacket(payload(5), crcMode), new byte[] {ShimmerObject.DATA_PACKET}); + assertAckProcessed(); + assertTrue(mDevice.getListofInstructions().isEmpty()); + assertTrue(mDevice.isSDLogging()); + assertEquals(BT_STATE.STREAMING_AND_SDLOGGING, mDevice.getBluetoothRadioState()); + + assertParsed(payload(1), payload(2), payload(3), payload(4), payload(5)); + assertBuffered(ShimmerObject.DATA_PACKET); + } + + @Test + public void bareAckWithOneByteCrcWhileStreaming() { + startSdLoggingWhileStreaming(BT_CRC_MODE.ONE_BYTE_CRC); + } + + @Test + public void bareAckWithTwoByteCrcWhileStreaming() { + startSdLoggingWhileStreaming(BT_CRC_MODE.TWO_BYTE_CRC); + } + + /** Already worked: with no CRC the ACK is followed by the next packet's DATA_PACKET */ + @Test + public void bareAckWithoutCrcWhileStreaming() { + startSdLoggingWhileStreaming(BT_CRC_MODE.OFF); + } + + /** Already worked: an in-stream response's 0x8A follows the ACK, and its CRC comes at the end */ + private void inStreamResponseWhileStreaming(BT_CRC_MODE crcMode) { + streamingShimmer3r(crcMode); + mDevice.readBattery(); + sendNextInstruction(); + // [ACK][INSTREAM_CMD_RESPONSE][VBATT_RESPONSE][ADC, LSB first][charger status][CRC] + byte[] vbatt = withCrc(new byte[] {ShimmerObject.ACK_COMMAND_PROCESSED, ShimmerObject.INSTREAM_CMD_RESPONSE, + ShimmerObject.VBATT_RESPONSE, 0x24, 0x0B, (byte) 0x80}, crcMode); + receive(dataPacket(payload(1), crcMode), vbatt, dataPacket(payload(2), crcMode), new byte[] {ShimmerObject.DATA_PACKET}); + assertAckProcessed(); + assertTrue(mDevice.getListofInstructions().isEmpty()); + assertEquals(0x0B24, mDevice.getBattStatusDetails().getBattAdcValue(), 0); + assertParsed(payload(1), payload(2)); + assertBuffered(ShimmerObject.DATA_PACKET); + } + + @Test + public void inStreamResponseWithOneByteCrcWhileStreaming() { + inStreamResponseWhileStreaming(BT_CRC_MODE.ONE_BYTE_CRC); + } + + @Test + public void inStreamResponseWithTwoByteCrcWhileStreaming() { + inStreamResponseWhileStreaming(BT_CRC_MODE.TWO_BYTE_CRC); + } + + /** + * The ACK's own CRC shows it is an ACK, so a corrupt data packet ahead of it + * is dropped without losing the ACK + */ + private void bareAckAfterACorruptPacket(BT_CRC_MODE crcMode, int indexToCorrupt) { + streamingShimmer3r(crcMode); + mDevice.stopSDLogging(); + sendNextInstruction(); + byte[] corrupt = dataPacket(payload(1), crcMode); + corrupt[indexToCorrupt] ^= 0x01; + receive(corrupt, bareAck(crcMode), dataPacket(payload(2), crcMode), new byte[] {ShimmerObject.DATA_PACKET}); + assertAckProcessed(); + assertTrue(mDevice.getListofInstructions().isEmpty()); + assertParsed(payload(2)); + assertBuffered(ShimmerObject.DATA_PACKET); + } + + @Test + public void bareAckWithOneByteCrcAfterACorruptPacket() { + bareAckAfterACorruptPacket(BT_CRC_MODE.ONE_BYTE_CRC, 1); + } + + /** Only the CRC's second byte is wrong, which is checked separately */ + @Test + public void bareAckWithTwoByteCrcAfterACorruptPacket() { + bareAckAfterACorruptPacket(BT_CRC_MODE.TWO_BYTE_CRC, 1+PACKET_SIZE+1); + } + + /** + * After a resync the buffer can already hold bytes beyond the ACK. Exactly + * the packet, the ACK and its CRC are consumed, and the rest stay with their + * timestamps as the start of the next frame. + */ + private void bareAckWithTheNextFrameAlreadyBuffered(BT_CRC_MODE crcMode) throws Exception { + streamingShimmer3r(crcMode); + mDevice.stopSDLogging(); + sendNextInstruction(); + byte[] nextFrameStart = Arrays.copyOf(dataPacket(payload(2), crcMode), 4); + ByteArrayOutputStream buffered = new ByteArrayOutputStream(); + buffered.write(dataPacket(payload(1), crcMode)); + buffered.write(bareAck(crcMode)); + buffered.write(nextFrameStart); + mDevice.mByteArrayOutputStream.write(buffered.toByteArray()); + for(long timestamp=0;timestamp