I'm unable to fetch all data from inputstream while connected via bluetooth hc-05 on my android app. Here is my code:
val knownUUIDForDevice = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
val remoteDevice: BluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress)
val btSocket: BluetoothSocket = remoteDevice.createRfcommSocketToServiceRecord(knownUUIDForDevice)
btSocket.connect()
connectedThread = ConnectedThread(btSocket, rawDataMessageCallback)
connectedThread.start()
My connectedThread code:
class ConnectedThread(private val btSocket: BluetoothSocket)
: Thread() {
private var inStream: InputStream? = null
internal var outStream: OutputStream? = null
init {
inStream = btSocket.inputStream
outStream = btSocket.outputStream
}
override fun run() {
val buffer = ByteArray(512)
inStream = btSocket.inputStream
outStream = btSocket.outputStream
while (true) {
try {
inStream!!.read(buffer)
} catch (e: IOException) {
println(e)
break
}
}
}
}
When I tested connection between my device & realterm app, I was able to see all data. Application above is capable of receiving only about 80% of data. I'm sure it is not fault of device, because I'm able to see all data in realterm app. What I've tried:
1) Add sleep before/after read method
2) wrap inputStream into buffered stream
3) used inStream!!.readBytes() instead of inStream!!.read(buffer) -> thread freezed up on this method (inside there was call to read method())
4) checking available data with available method(), but it gave me incorrect results - i.e. when stream was going to end, it shows 50 bytes were available, but actually I saw it was 200 bytes available in buffer... Anyway, according to documentation, I should never rely on this method.
5) Used IOUtils from apache commons & Bytestreams from guava -> result the same as in 3rd point, thread freeze
6) Changed size of buffer: tried 1, 10, 100, 256, 512, 1024, 10000 7
Question is: is it possible of loss of data in inputStream?