Created
August 28, 2019 23:46
-
-
Save rohanmendon/43f7895fcff7d6f79a108980d4e6b1de to your computer and use it in GitHub Desktop.
Executing the OBD2 Commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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