I have a while loop that reads from a serial port using a scanner and adds all the data it reads to a List<String>
.
My problem is I don't know how to exit the loop when I receive the data?
The data I receive in the loop is
[***, REPORT, ***, MIB-Series, Currency, Counter, --------------------------------, Mar.6,2022,, 01:26, Station:1, Deposit, No.:, 2, Mixed, Mode, RSD, UV, MG, IR, --------------------------------, DENOM, UNIT, TOTAL, D10, 0, D, 0, D20, 0, D, 0, D50, 0, D, 0, D100, 0, D, 0, D200, 0, D, 0, D500, 0, D, 0, D1000, 0, D, 0, D2000, 0, D, 0, D5000, 0, D, 0, --------------------------------, TOTAL, 0, D, 0, --------------------------------, m3]
And the code that I use is
public static List<String> readFromPort(SerialPort serialPort) {
Scanner sc = new Scanner(serialPort.getInputStream());
List<String> line = new ArrayList<>();
while (sc.hasNextLine()) {
line.add(sc.next());
}
sc.close();
return line;
}
I tried adding this condition to WHILE loop && !line.contains("m3")
but for some reason, I then have to press "Send" on the serial device twice to receive data. If I use some other string from the list it works fine(I press "Send" only once), but then I don't receive the complete data.
Any ideas what else to try?
NOTE: I'm using JSerialComm library.
EDIT: The String at the end of List is like in the screenshot below, the two unrecognized characters are deleted automatically when I post the question.
CodePudding user response:
If you know the unicode code-point for the two characters displayed as squares in the screen capture in your question, then use a literal, for example:
!line.contains(\u03A9m\uFFFF3)
In the above line, the first literal is \u03A9
which precedes the lowercase m and the second literal is \uFFFF
which follows the lowercase m and precedes the digit 3.
CodePudding user response:
java Scanner has several issues when reading new lines or skipping inputs
Scanner is skipping nextLine() after using next() or nextFoo()?
How to use java.util.Scanner to correctly read user input from System.in and act on it?
An better but slower solution involves using BufferedReader for reading any input from any input stream see Scanner vs. BufferedReader
Also taking points from @Abra solution you should use uni code points for non printable characters
\u03A9m\uFFFF3
Full code below
try(BufferedReader reader=new BufferedReader(new InputStreamReader(serialPort.getInputStream()))
{
List<String> lines = new ArrayList<>();
String line;
while((line=reader.readLine())!=null && !line.contains(\u03A9m\uFFFF3))
{
line.add(line);
}
return lines;
}