2

When I attempt to retrieve a value from the device via Bluetooth, it comes out in ASCII, as a null terminated big-endian value. The device software is written in C. I want to retrieve the decimal value, i.e. 0 instead of 48, 1 instead of 49, 9 instead of 57, etc.

@Throws(IOException::class)
fun receiveData(socket: BluetoothSocket ? ): Int {
 val buffer = ByteArray(4)
 val input = ByteArrayInputStream(buffer)
 val inputStream = socket!!.inputStream
 inputStream.read(buffer)

 println("Value: " + input.read().toString()) // Value is 48 instead of 0, for example.

 return input.read()
}

How can I retrieve the value I want?

Martin Erlic
  • 5,467
  • 22
  • 81
  • 153
  • 1
    This will _definitely_ depend on the encoding of the string written in C. – Louis Wasserman Dec 08 '18 at 04:09
  • It will, but I used a stock bluetooth chat app to receive the signal and it does receive all 5 integers. I only receive 1 with my application. I suppose I need to know how it is encoded in order to decode it... – Martin Erlic Dec 08 '18 at 07:43

2 Answers2

1

It's easy to do with bufferedReader:

val buffer = ByteArray(4) { index -> (index + 48).toByte() }     // 1
val input = ByteArrayInputStream(buffer)

println(input.bufferedReader().use { it.readText() })            // 2
// println(input.bufferedReader().use(BufferedReader::readText)) // 3

Will output "0123".

1. Just stubs the content of a socket using an init function that sets first element of the buffer to 48, second to 49, third to 50 and fourth to 51.

2. The default charset is UTF-8, that is a "superset" of ASCII.

3. It's just another style of calling { it.readText() }.

madhead
  • 31,729
  • 16
  • 153
  • 201
1

My function ultimately took the following form. This allowed me to retrieve all 5 digits in decimal form:

@Throws(IOException::class)
fun receiveData(socket: BluetoothSocket ? ): String {
 val buffer = ByteArray(5)
  (socket!!.inputStream).read(buffer)
 println("Value: " + String(buffer))
 return String(buffer)
}

For my particular problem, the input variable was being created before reading the data into the buffer. Since the read method is called for every index in the data, I was only getting the first digit.

See the Java method public int read() for an explanation:

Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

Martin Erlic
  • 5,467
  • 22
  • 81
  • 153