I have the following function to send data over bluetooth to a bluetooth serial monitor running on my laptop.
private fun sendData(mSocket: BluetoothSocket?, data: String) { //mSocket: "XX:XX:XX:XX:6E:D0" data hello world!
if (mSocket == null) {
return
}
val outputStream: OutputStream
try {
outputStream = mSocket.outputStream //mSocket: "XX:XX:XX:XX:6E:D0"
} catch (e: IOException) {
Log.d("Outputstream", "Error occurred when creating output stream: ${e.message}")
return
}
try {
val dataWithNewline = "$datan"
outputStream.write(dataWithNewline.toByteArray())
outputStream.flush()
Log.d("sendData", "Data sent: $data")
} catch (e: IOException) {
Log.d("sendData", "Error occurred when sending data: ${e.message}")
}
}
The bluetooth socket is created and connected succesfully, however when I try to send data, nothing happens. No IOException is thrown either. In Logcat I see “Data sent: hellow world!” indicating the data got sent over. On the receiving end however I dont see anything. In the comments in my code I wrote down some variable values when I put a breakpoint at the end of the function. Why does my MAC address show up truncated: “XX:XX:XX:XX:6E:D0”? After inspecting mSocket I do see the full MAC address under the mAddress variable.
This is the function to connect to my device:
fun connectOBDDevice(deviceItem: BluetoothDeviceItem) {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val device: BluetoothDevice? = mBluetoothAdapter.getRemoteDevice(deviceItem.address)
try {
val createInsecureRfcommSocket = BluetoothDevice::class.java.getMethod("createInsecureRfcommSocket", Int::class.javaPrimitiveType)
mSocket = createInsecureRfcommSocket.invoke(device, 1) as BluetoothSocket
} catch (e: Exception) {
// e.printStackTrace();
Log.d("connectOBDDevice", "createInsecureRfcommSocket failed")
}
if(mSocket != null)
{
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.BLUETOOTH_CONNECT
) == PackageManager.PERMISSION_GRANTED
) {
try {
mSocket.connect()
val receiveThread = BluetoothReceiveThread(mSocket)
receiveThread.start()
Toast.makeText(context, "Device connected successfully!", Toast.LENGTH_SHORT).show()
}
catch (e: IOException)
{
Toast.makeText(context, "Connection Failed", Toast.LENGTH_SHORT).show()
}
}
}
}
Any help would be appreciated!
I tried using the “Serial Bluetooth” app on my phone to test the connection and while using this everything works fine.