Skip to content
This repository has been archived by the owner on Sep 21, 2020. It is now read-only.

Commit

Permalink
[rfxcom] Improved message receiving (#6143)
Browse files Browse the repository at this point in the history
1. Fix IndexOutOfBoundsException if first read byte value (message len)
is 255.
2. Bridge state is updated if uncaught exception occurs.
3. Improved logging.

Signed-off-by: Pauli Anttila <pauli.anttila@gmail.com>
  • Loading branch information
paulianttila authored and martinvw committed Sep 28, 2019
1 parent 927b76f commit 27a6157
Showing 1 changed file with 8 additions and 6 deletions.
Expand Up @@ -30,13 +30,15 @@
public class RFXComStreamReader extends Thread {
private final Logger logger = LoggerFactory.getLogger(RFXComStreamReader.class);
private static final int MAX_READ_TIMEOUTS = 4;
private static final int MAX_RFXCOM_MESSAGE_LEN = 256;

private RFXComBaseConnector connector;

private class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
logger.error("Connector died: ", throwable);
logger.debug("Connector died: ", throwable);
connector.sendErrorToListeners("Connector died: " + throwable.getMessage());
}
}

Expand All @@ -48,7 +50,7 @@ public RFXComStreamReader(RFXComBaseConnector connector) {
@Override
public void run() {
logger.debug("Data listener started");
byte[] buf = new byte[Byte.MAX_VALUE];
byte[] buf = new byte[MAX_RFXCOM_MESSAGE_LEN];

// The stream has (or SHOULD have) a read timeout set. Taking a
// read timeout (read returns 0) between packets gives us a chance
Expand All @@ -62,6 +64,7 @@ public void run() {
int packetLength = buf[0];

if (bytesRead > 0 && packetLength > 0) {
logger.trace("Message length is {} bytes", packetLength);
processMessage(buf, packetLength);
connector.sendMsgToListeners(Arrays.copyOfRange(buf, 0, packetLength + 1));
}
Expand All @@ -78,13 +81,12 @@ private void processMessage(byte[] buf, int packetLength) throws IOException, RF
// Now read the rest of the packet
int bufferIndex = 1;
int readTimeoutCount = 1;
int bytesRead;
while (bufferIndex <= packetLength) {
int bytesRemaining = packetLength - bufferIndex + 1;

bytesRead = connector.read(buf, bufferIndex, bytesRemaining);

logger.trace("Waiting remaining {} bytes from the message", bytesRemaining);
int bytesRead = connector.read(buf, bufferIndex, bytesRemaining);
if (bytesRead > 0) {
logger.trace("Received {} bytes from the message", bytesRead);
bufferIndex += bytesRead;
readTimeoutCount = 1;
} else if (readTimeoutCount++ == MAX_READ_TIMEOUTS) {
Expand Down

0 comments on commit 27a6157

Please sign in to comment.