Bluetooth Socket is blocked on Read

I´m working in a project about an app for Android and iOS (with Xamarin Forms).

This app will be able to discover and connect with a OBD2 and communicate with it for get some data about a car.

My problem is the next; in Android, when I start to send and receive data from the device, the first communication is ok, I sent a ASCII code and device responds to me. But next, I sent another ASCII code and when I want to Read, the method BluetoothSocket.InputStream.IsDataAvailable() is false, so I can´t read more, and I don´t know how can do for "unblock" this read for read next reponse. It´s the first time that I work with Bluetooth Device and Bluetooth Socket so probably I´m doing something wrong.

My code:

To get the Bluetooth Socket.-

socket = device.CreateRfcommSocketToServiceRecord(uuid.Uuid); //if first fails socket = device.CreateInsecureRfcommSocketToServiceRecord(uuid.Uuid);

To send information to the Device (first calls):

`byte[] cmd = new byte[6];
cmd[0] = 02;
cmd[1] = 65;
cmd[2] = 84;
cmd[3] = 32;
cmd[4] = 90;
cmd[5] = 03;
//cmd[6] = 04;

    socket.OutputStream.Write(cmd, 0, cmd.Length);
    if (Read().Equals("")){ 
        throw new System.Exception();
    }
    socket.OutputStream.Flush();

    cmd[0] = 02;
    cmd[1] = 65;
    cmd[2] = 84;
    cmd[3] = 32;
    cmd[4] = 68;
    cmd[5] = 03;
    //cmd = Encoding.ASCII.GetBytes("AT Z");
    socket.OutputStream.Write(cmd, 0, cmd.Length);

    Console.WriteLine("After second write InputStream.IsDataAvailable="+socket.InputStream.IsDataAvailable()); //Always false
    if (Read().Equals("")){
        throw new System.Exception();
    }
    socket.OutputStream.Flush();`

To Read the response:

`private string Read()
{
//También probado con BufferedReader.ready() para comprobar si el stream está listo para leer; mismo resultado.

    string data = ""; 
    try

    {               
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        char c;
        byte a;
        byte[] buffer = new byte[1024];
        //Este tipo de socket no soporta Timeouts
        if (socket.InputStream.IsDataAvailable()) //only entry first time
        {                                       
            int bytes = socket.InputStream.Read(buffer, 0, buffer.Length);

            //while (((a = (byte)socket.InputStream.ReadByte()) > -1))
            for (int i = 0; i < bytes; i++)
            {
                a = buffer[i];

                c = (char)a;
                if (c.Equals('\r')) //Comprobado \r es el último caracter, no llega a  ETX
                {

                    break;

                }
                builder.Append(c);
            }
            data = builder.ToString();
            Console.WriteLine("Información: " + data);

            socket.InputStream.Flush();



        }

        else
        {
            Console.WriteLine("Input Stream no disponible");
        }

    }
    catch (System.Exception e)
    {
        Console.WriteLine("Error de lectura :"+e.Message);

    }

    return data;

}`

I would like to resolv this, because I have to sent a lot of information to the device without waiting.

Thank you.

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Take a look to https://github.com/acaliaro/TestBth/blob/master/Droid/Bth.cs

    I use this to read Bluetooth sockets

    I don't use InputStream but I do something like

    var mReader = new InputStreamReader(BthSocket.InputStream);
    var buffer = new BufferedReader(mReader);
    

    then I evaluate

    if(buffer.Ready ()){
        // I read...
        char[] chr = new char[100];
        await buffer.ReadAsync(chr);
    }
    
  • NeroCntNeroCnt ESMember
    edited September 2017

    Hi Alessandro, and thank you for you reply.

    I try it with your solution, but I have simmilar issues.

    When the app start to communicate, the first call to await buffer.ReadAsync(chr); jump then the for to analyze the response and, in the second call, buffer.Ready() is false again, like InputStream, so it goes to else, where is _await buffer.ReadLineAsync();__ but never excecutes. Besides, due to waiting with "await", the app keep running until the end, but I don´t have the results of communication with the device, so it ends wrongs (even sometimes the app crash).

    I guess the problem is in releasing buffer/inputstream after ends of first read, but I don´t know how it´s posible.

  • caiolcfcaiolcf Member
    Anybody got this?
    I have the same problem.
Sign In or Register to comment.