diff --git a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java index e2df1cef4..befd46761 100644 --- a/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java +++ b/ShimmerDriver/src/main/java/com/shimmerresearch/bluetooth/ShimmerBluetooth.java @@ -1107,8 +1107,17 @@ else if(byteBuffer[0]==ACK_COMMAND_PROCESSED) { } } } - - 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(); + } } } @@ -1170,7 +1179,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 +1221,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 +1278,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 +2222,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 +2392,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 +5566,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 +5700,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_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]; + 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[] 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(); + 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(hex(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. 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() { + 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); + 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, 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 + 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); + // 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; + 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, 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() { + 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 not queued + * behind a start of streaming that has not been acknowledged yet. + */ + @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("refused", sent); + assertFalse("the status is queued after a start of streaming", queuedAfterStart); + } + + // ------------------------------------------------------------------ + // Idle, with the IOThread running + // ------------------------------------------------------------------ + + /** Answers every command with an ACK, with its link CRC, then {@link #afterOptInAck} for the opt-in, all in one burst */ + private static class AckingRadio extends WaitingTestRadio { + volatile BT_CRC_MODE crcMode = BT_CRC_MODE.OFF; + volatile byte[] afterOptInAck = new byte[0]; + + @Override + byte[] answer(byte[] command) { + byte[] ack = withLinkCrc(new byte[] {ShimmerObject.ACK_COMMAND_PROCESSED}, crcMode); + if(command[0]==ShimmerObject.SET_FEATURE && command[1]==(byte) SHIMMER_FEATURE.EVENT_STREAM.ordinal() && command[2]!=0) { + return concat(ack, afterOptInAck); + } + return ack; + } + } + + private ShimmerPC mIdle; + private AckingRadio mAcking; + + /** Connected over a link with {@code crcMode}, not streaming, opted in; {@code afterOptInAck} comes in the opt-in's ACK's burst */ + private void idleOptedIn(BT_CRC_MODE crcMode, byte[] afterOptInAck) throws InterruptedException { + if(mIdle!=null) { + mIdle.stopTimerCheckForAckOrResp(); + mIdle.disconnectNoException(); + } + mCollected.clear(); + mAcking = new AckingRadio(); + mAcking.crcMode = crcMode; + mAcking.afterOptInAck = afterOptInAck; + mIdle = new ShimmerPC("COM97"); + mIdle.setTestRadio(mAcking); + mIdle.setShimmerVersionObjectAndCreateSensorMap(S3R); + mIdle.setCurrentBtCommsCrcMode(crcMode); + mIdle.setIsInitialised(true); + mIdle.addEventChannelListener(mCollected); + mIdle.mIOThread = mIdle.new IOThread(); + mIdle.mIOThread.start(); + assertTrue(mIdle.writeEventStream(true)); + long end = System.currentTimeMillis()+2000; + while((!mIdle.getListofInstructions().isEmpty() || mIdle.isInstructionStackLock()) && System.currentTimeMillis() + *
  • {@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; + } + +}