我在 Java 中编写解码 GPS 的代码,GPS 向我发送我可以在我的代码中看到的继续字符串,但是当我解码它时,只有一个字符串解码并且由于我的字符串必须为下一个字符串为 null 而停止工作我尝试这样做但没有得到成功。 任何人都对这种情况有想法
package communication;
import javax.comm.*;
import java.util.*;
import java.io.*;
import new8.*;
class Serial
{
public static void main(String args[]) throws UnsupportedCommOperationException, IOException, TooManyListenersException
{
int c=1;
String wantedPortName = "COM6";
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
while(portIdentifiers.hasMoreElements())
{
CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
pid.getName().equals(wantedPortName))
{
portId = pid;
break;
}
}
if(portId == null)
{
System.err.println("Could not find serial port " + wantedPortName);
System.exit(1);
}
else
{
System.out.println("system find gps reciever");
}
SerialPort port = null;
try {
port = (SerialPort) portId.open(
"RMC",
1);
System.out.println("all are ok");
} catch(PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(1);
}
port.setSerialPortParams(
4800,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
BufferedReader is = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
System.out.println("data is ok");
} catch (IOException e) {
System.err.println("Can't open input stream: write-only");
is = null;
}
String pt=null;
while(true)
{
is.readLine();
is.readLine();
String st = is.readLine();
System.out.print("("+c+")");
c++;
new8 obj1=new new8();
obj1.decode(st);
System.out.println(st);
st=st.replace(st, "");
}
if (is != null) is.close();
/*if (os != null) os.close();*/
if (port != null) port.close();
}
}
您要实现的是通过COM端口解析来自GPS接收器的NMEA数据。
我在 C(开源项目导航系统"Navit")中看到过这样的代码。
但是我记得串行可能会被破坏,因此,他们检查如果消息中包含"$GP"praeambel。如果 NMEA 行中提供的校验和正确。
我建议你看看那个 Navit 代码(尽管它是 C 语言)。您不是第一个从COM端口解码NMEA的人。
代码应如下所示,以便具有正确的流程。没有说任何关于逻辑的东西。
if (is != null) {
//String pt = null;
while (true) {
String st = is.readLine();
if (st == null) {
break;
}
st = is.readLine();
if (st == null) {
break;
}
st = is.readLine();
if (st == null) {
break;
}
System.out.print("(" + c + ")");
c++;
new8 obj1 = new new8();
obj1.decode(st);
System.out.println(st);
st = st.replace(st, "");
}
is.close();
}