Michielvk Michielvk - 7 months ago 48
Java Question

Receive string via Bluetooth android (without line feed or Carriage Return)

There are a lot of questions on stack overflow on how to receive data (string) from a Bluetooth device but I have never seen a question on how to receive data (string) without checking for LF or CR.

This code works perfectly when the device send a LF at the end of the String:

final Handler handler = new Handler();
final byte delimiter = 10; //ASCII code for Line Feed

stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];

try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}



Thread workerThread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = inStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
//test
textview1.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();


But the device that sends the string does not send a Line feed neither a CR at the end. I have tried many things (also the Bluetooth guide from Google (http://developer.android.com/guide/topics/connectivity/bluetooth.html)). I want to receive all the data that is send to the app (and for testing display the received String in a textview).

Thanks in advance,
Michielvk

Answer

Assuming all strings start with a "1" character, you should be able to read the second to last string by replacing final byte delimiter = 10; by final byte delimiter = 49; (since 49 is decimal representation of "1" in ASCII table).

There's no way to read the last string (and assert you're reading the full string, not only a part) if there's no suffix delimiter.

EDIT :

You gave the protocol's documentation in this comment feed. The doc says : The result string [...] consists of 38 ASCII characters.

According to the fact that each response consists of 38 ASCII characters, you should be able to read all messages by replacing : if (b == delimiter) { with : if (readBufferPosition >= 37) {

Comments