I do read serial interface file in Linux via Java. Sometimes I just need to discard all data and read only what is new.
Explanation: There is loads of data and new is coming so I do have to discard existing buffer and start to wait for new data. External board just keeps sending. And I end up reading old data, just in few iterations I have current value. I need just skip to end and wait for new data set only instead reading all old crap.
String file = "/dev/ttyO1";
FileInputStream inputStream = new FileInputStream(file);
private static byte[] readUntil(InputStream in, int timeout) throws IOException {
// long lastTime = System.currentTimeMillis();
while (true) {
if (in.available() > 0) {
if (in.read() == 83)
break;
}
try { Thread.sleep(20); } catch (Exception e) {}
}
byte[] text = new byte[10];
for (int i = 0; i < 10; i++) {
text[i] = (byte) in.read();
if (text[i]=="E".getBytes()[0]) break;
try { Thread.sleep(20); } catch (Exception e) {}
}
in.read(); // just read last one
return text;
}
I just cannot figure out how to discard the existing data and read only new coming.