Translate

Saturday, May 12, 2018

Developer tips - Android studio

Bluetooth RFCOMM connection problem

If you like me are trying to set up a simple Bluetooth RFCOMM connection and you end up having connection errors, especially : read failed, socket might closed or timeout, read ret: -1
is possible the problem lies in a changed default assignment for the socket.



After Android 4.2 the Bluetooth stack changed and a default value for the port changed.
Now the default is -1 and apparently many devices out there doesn't like that (Raspberry Pi doesn't like it).
The "solution" is to force back a positive value for the port (1 typically).
Of course there is not a direct way to do so.
Many developers simply catch the error and reassign the socket with a different procedure that allows to assign the port but it works also assigning the port immediately.

Normally to assign the socket you could use : device.createRfcommSocketToServiceRecord(uuid);

But this will end up with the wrong port assignment (of course we assuming the uuid is set for the generic universal RFCOMM service ( 00001101-0000-1000-8000-00805f9b34fb) :

To assign the socket you can use this function instead :

   private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        try {
            return (BluetoothSocket) device.getClass().getMethod("createRfcommSocket", \
new Class[] {int.class}).invoke(device,1);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
            return  device.createRfcommSocketToServiceRecord(uuid);
        }
    }

So if you end with the error  read failed, socket might closed or timeout, read ret: -1 be sure to :

  1. retrieve the UUID supported by the peripheral and verify match what the service you want
  2. cancel the discovery of bluetooth devices (cancelDiscovery() function) 
  3. use the socket assignment function in this example
That worked for me.

Note that the Raspberry Pi 3B+ has a default UUID for the RFCOMM set as : 0000110e-0000-1000-8000-00805f9b34fb



No comments:

Post a Comment