Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Executing the OBD2 Commands
Pattern WHITESPACE_PATTERN = Pattern.compile("\\s");
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = 0;
read = mmInStream.read(mmBuffer, 0, mmBuffer.length);
baos.write(mmBuffer, 0, read);
baos.flush();
String response = new String(baos.toByteArray(), "UTF-8");
String trimmedResponse = removeAll(WHITESPACE_PATTERN, response);
// Returned value are Hex and need to convert to Integer
int rpm = Integer.parseInt(trimmedResponse.substring(17, 21).trim(), 16 )/4;
int speed = Integer.parseInt(trimmedResponse.substring(23, 25).trim(), 16 )/1.6;
int fuel = Integer.parseInt(trimmedResponse.substring(29, 31).trim(), 16 ) * 0.39;
} catch (Exception e) {
Log.d(TAG, "Input stream was disconnected", e);
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
}
}
}
ConnectedThread c = new ConnectedThread(mmSocket);
String command = "010C0D2F\r";
c.write(command.getBytes());
try {
Thread.sleep(200);
} catch (Exception ex) {
}
c.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.