2

我正在开发用于连接到 ELM327 用于车载 Wifi 的 Andorid 应用程序(我的适配器: http ://www.obdinnovations.com/mini-vgate-elm327-wifi-obd2-auto-diagnostics-scanner )。我应该如何连接到这个 OBD2 适配器然后发送一些信号?

OutputStream outStream = null;
InputStream inStream = null;
Socket socket = null;
InetAddress serverAddr = null;
String serverProtocol = "http";
String serverIpAddress = "192.168.0.10";
public static final int SERVERPORT = 35000;

try {
    serverAddr = InetAddress.getByName(serverIpAddress);
    socket = new Socket(serverAddr, SERVERPORT);
    socket.setKeepAlive(true);
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

sendDataToOBD(socket1, "ATZ\r");    
Log.e("OBD: ATZ", readDataFromOBD(socket));

public void sendDataToOBD(Socket socket1, String paramString) {
    try {
        outStream = socket1.getOutputStream();
        byte[] arrayOfBytes = paramString.getBytes();
        outStream.write(arrayOfBytes);
    } catch (Exception localIOException1) {
        localIOException1.printStackTrace();
    }
}

public String readDataFromOBD(Socket socket1) {
    while (true) {
        try {
            inStream = socket1.getInputStream();
            String str1 = "";
            char c = (char) inStream.read();
            str1 = str1 + c;
            if (c == '>') {
                String datafromOBD = str1.substring(0, -2 + str1.length()).replaceAll(" ", "").trim();

                return datafromOBD;
            }
        } catch (IOException localIOException) {
            return localIOException.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我也尝试:

URL url = null;
try {
    url = new URL(serverProtocol, serverIpAddress, SERVERPORT, "");
} catch (MalformedURLException e) {
    e.printStackTrace();
}
HttpURLConnection connection = null;
try {
    connection = (HttpURLConnection) url.openConnection();
    connection.connect();
} catch (IOException e) {
    e.printStackTrace();
}

方法参数是 HttpURLConnection 连接而不是 Socket socket1。

但是我收不到任何信号。我的代码有什么问题?有什么建议么?

4

0 回答 0