views:

548

answers:

2

I am trying to read data off of a Windows serial port through Java. I have the javax.comm libraries and am able to get some data but not correct data. When I read the port into a byte array and convert it to text I get a series of characters but no real text string. I have tried to specify the byte array as being both "UTF-8" and "US-ASCII". Does anyone know how to get real text out of this?

Here is my code:

while (inputStream.available() > 0) {
 int numBytes = inputStream.read(readBuffer);
 System.out.println("Reading from " + portId.getName() + ": ");
 System.out.println("Read " + numBytes + " bytes");
}

System.out.println(new String(readBuffer));
System.out.println(new String(readBuffer, "UTF-8"));
System.out.println(new String(readBuffer, "US-ASCII"));

the output of the first three lines will not let me copy and paste (I assume because they are not normal characters). Here is the output of the Hex: 78786000e67e9e60061e8606781e66e0869e98e086f89898861878809e1e9880

I am reading from a Hollux GPS device which does output in string format. I know this for sure because I did it through C#.

The settings that I am using for communication which I know are right from the work in the C# app are: Baud Rate: 9600 Databits: 8 Stop bit: 1 parity: none

+1  A: 

It's likely that the connected device doesn't use a text protocol. Many devices use a binary message format that may have text embedded in it, but represents other information with more compact codes.

Please edit your question and provide more information, such as the device that you're communicating with through the serial port, and the output that you get from the code you have running. Another helpful output to add would be something that prints a hexadecimal representation of the data you've read. A quick-and-dirty method for that is the following:

import java.math.BigInteger;
...
System.out.println(new BigInteger(1, readBuffer).toString(16));


I haven't worked with Holux GPS, but I have written a Garmin interface with javax.comm. In that case, the unit uses a proprietary (binary) Garmin protocol by default, but the (text-based) NMEA 0183 protocol can be enabled on the device. Is it possible that you are receiving a proprietary Holux message format, and need to use some command on the GPS unit to switch protocols?

erickson
+1  A: 

I can't tell from your code, but it looks like you're using java.io.InputStream to read the object. You should use either java.io.BufferedReader or java.io.InputSreamReader.

There are many ways to do this, but this is what we use:

javax.comm.SerialPort port = ...{initialize your serial port}
BufferedReader portReader = 
    new BufferedReader(new InputStreamReader(port.getInputStream()));

try {
    String line = portReader.readLine();
} catch(IOException e) { ... }
rtperson