使用DataInputStream / socket从GPS设备读取数据

时间:2013-06-28 13:45:40

标签: java sockets gps port

如何从GPS设备读取数据?

我正在使用socket& amp ;;来读取GPS设备的数据。 DataInputStream但是当我获取数据时,我得到一些ASCII编码的字符串,在该字符串的末尾,我有我想要使用的答案字符串。那么如何在没有这种复杂字符集的情况下连续获取数据并获得精确的字符串。我也尝试过使用串口。

这是我尝试过的。

//Using Serial Port //

CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portname);
System.out.println("fired");
// Open port
// Requires owner name and timeout
CommPort port = portId.open("Java Printing", 3000);

// Setup reading from file
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);

// Setup output
OutputStream os = port.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);

int c;
while ((c = bis.read()) != -1) 
{
bos.write(c);
System.out.print((char)c);
}

// Close
bos.close();`enter code here`
bis.close();
port.close();

//Using Normal Socket //

char[] inputChars = new char[1024];
byte[] data = new byte[1024];
int charsRead = 0;
BufferedReader inputStream = null;

System.out.println("1 1 1 1 1");
InputStreamReader isr = new InputStreamReader( s1.getInputStream() );
System.out.println("2 2 2 2 2 2");
inputStream = new BufferedReader( isr );

//Read 1024 characters. Note: This will pause the thread when stream is empty.

System.out.println("Reading from stream:");
while ((charsRead =  inputStream.read(inputChars)) != -1)
{
System.out.println("Chars read from stream: " + charsRead);  
System.out.println("inputChars = "+inputChars);
data = new String(inputChars).getBytes("US-ASCII");
System.out.flush();
}
byte[] decodedBytes = Base64.encodeBase64(data);
System.out.println("decodedBytes " + new String(decodedBytes));

1 个答案:

答案 0 :(得分:0)

您可以使用标准NMEA格式或使用芯片制造商自定义二进制协议与GPS芯片进行通信。
确保已正确设置波特率和(虚拟)COM端口。

默认协议1始终是NMEA。 NMEA消息以“$”开头。 你总是应该得到$ GPRMC消息