1

At the moment I have a working Bluetooth connection with my gamecontroller. Now I am trying to catch the button events, but it's not that easy. I have the following code:

    private Stream mmInStream;
    private Stream mmOutStream;

    public BluetoothController()
    {

    }

    public void Read(BluetoothSocket socket)
    {
        Stream tmpIn = null;
        Stream tmpOut = null;

        try
        {
            tmpIn = socket.InputStream;
            tmpOut = socket.OutputStream;
        }
        catch (IOException ex)
        {
            throw ex;
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

        Thread thread = new Thread(new ThreadStart(Run));
        thread.Start();
    }

    protected void Run()
    {
        byte[] buffer = new byte[1024];
        int bytes;

        while (true)
        {
            try
            {
                // Thanks to @spaceplane
                if (mmInStream.IsDataAvailable())
                {
                    // Read from the InputStream
                    bytes = mmInStream.Read(buffer, 0, buffer.Length);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

When I press a button on the gamecontroller, it's not going inside the next line:

if (mmInStream.IsDataAvailable())

What's wrong here?

Jamie
  • 363
  • 7
  • 19
  • It's solved, check my post here: http://stackoverflow.com/questions/18657427/ioexception-read-failed-socket-might-closed-bluetooth-on-android-4-3/36412975#36412975 – Jamie Jun 03 '16 at 09:14

2 Answers2

1

mmInStream.read() blocks if there is currently no data available in the stream to read. So if there is no data it will just get stuck there waiting. You should check if there is any data available before reading from the stream. Change

bytes = mmInStream.Read(buffer, 0, buffer.Length);

to

if(mmInStream.available() > 0) {
  bytes = mmInStream.Read(buffer, 0, buffer.Length);
}
spaceplane
  • 607
  • 1
  • 12
  • 27
  • Thank you @spaceplane. That's working right now! But when I press a button on the gamecontroller, then it's not going inside that if statement... But it should be possible to read data from a gamecontroller using a Stream, right? – Jamie Apr 01 '16 at 09:23
0

The problem is solved. I didn't need a Bluetooth socket. I just used the override methods "KeyDown" and "KeyUp". It works great now :)

If you need a socket and you've got an exception like IOException: read failed, socket might closed then you should read my fix here:

IOException: read failed, socket might closed - Bluetooth on Android 4.3

Jamie
  • 363
  • 7
  • 19