Search code examples
c#visual-studiobluetoothstream32feet

C# read bluetooth stream reliably (InTheHand 32feet)


I have a problem with reliably read a bluetooth stream. It's the first time I worked with bluetooth connections. The application communicates with a Arduino over a bluetooth module. It will send a command and get a response.
For example, the response should look something like this:
100,200,300,400
This is what I get:
1
and if I get another response (also if it should look completely different) I get rest of the response requested before:
00,200,300,400
Sometimes I even get an empty response.

Here is the code I use to read and write to the stream:

    void BluetoothClientConnectCallback(IAsyncResult result)
    {
        try
        {
            BluetoothClient client = (BluetoothClient)result.AsyncState;
            client.EndConnect(result);

            NetworkStream stream = client.GetStream();
            stream.ReadTimeout = 1000;

            _frm.printMsg("Connected!", false);

            byte[] receive = new byte[1024];
            while (true)
            {
                while (!ready) ;

                if (stopConnection == true)
                {
                    return;
                }

                try
                {
                    stream.Write(message, 0, message.Length);
                }
                catch
                {
                    _frm.printMsg("Error occurred while writing stream.", true);
                }
                try
                {
                    if (Commands.awaitresponse == true)
                    {
                        Array.Clear(receive, 0, receive.Length);
                        readMessage = "";
                        do
                        {
                            stream.Read(receive, 0, receive.Length);
                            readMessage += Encoding.ASCII.GetString(receive);
                        }
                        while (stream.DataAvailable);

                        _frm.printMsg("Received: " + readMessage, false);
                        Commands.awaitresponse = false;
                    }
                }
                catch
                {
                    _frm.printMsg("Error occurred while receiving stream.", true);
                }
                ready = false;
            }
        }
        catch
        {
            _frm.printMsg("Error occurred while connecting.", true);
        }
    }

I was looking a while into it, but couldn't come to a solution.


Solution

  • After some more debugging and testing I came to a solution by myself.
    I added 1 secound of delay Thread.Sleep(1000); before reading the stream.
    All packages are now red correctly.