Skip to content

Commit

Permalink
Improve performance of RIO console reading
Browse files Browse the repository at this point in the history
  • Loading branch information
jwbonner committed Feb 15, 2024
1 parent ead0087 commit 39de1e6
Showing 1 changed file with 18 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.BufferOverflowException;
import java.nio.CharBuffer;

import edu.wpi.first.wpilibj.DriverStation;

Expand All @@ -28,9 +31,7 @@ public class RIOConsoleSource implements ConsoleSource {
private static final String filePath = "/home/lvuser/FRC_UserProgram.log";
private BufferedReader reader = null;

private static final int bufferSize = 10240;
private int writePosition = 0;
private byte[] data = new byte[bufferSize];
private CharBuffer buffer = CharBuffer.allocate(10240);

public RIOConsoleSource() {
try {
Expand All @@ -54,33 +55,28 @@ public String getNewData() {
DriverStation.reportError("Failed to read console file \"" + filePath + "\"", true);
}
if (nextChar != -1) {
data[writePosition] = (byte) nextChar;
writePosition++;
if (writePosition >= bufferSize) {
// Too much data, save any full lines and continue on the next cycle
break;
}
try {
buffer.put((char) nextChar);
} catch (BufferOverflowException e) {}
} else {
break;
}
}

// Read all complete lines
String dataStr = new String(data);
int lastNewline = dataStr.lastIndexOf("\n");
String completeLines;
if (lastNewline != -1) {
completeLines = dataStr.substring(0, lastNewline);
byte[] trimmedData = new byte[bufferSize];
if (lastNewline < bufferSize - 1) {
System.arraycopy(data, lastNewline + 1, trimmedData, 0, bufferSize - lastNewline - 1);
String output = null;
for (int i = buffer.position(); i > 0; i--) {
if (i < buffer.position() && buffer.get(i) == '\n') {
int originalPosition = buffer.position();
output = new String(buffer.array(), 0, i);
buffer.rewind();
buffer.put(buffer.array(), i + 1, buffer.limit() - i - 1);
buffer.position(originalPosition - i - 1);
break;
}
data = trimmedData;
writePosition -= lastNewline + 1;
} else {
completeLines = "";
}
return completeLines;
if (output == null) output = "";
return output;
}

public void close() throws Exception {
Expand Down

0 comments on commit 39de1e6

Please sign in to comment.