connect blocks if device is borderline in range (no timeout)

Topics: Bluetooth - Microsoft
Jun 3, 2013 at 1:33 PM
hi,

i´m connecting to a bluetooth module on a microcontroller with spp. if the device is at the edge of the range or the reception is very bad, the connect function blocks and doesn´t timeout.

i didn´t have this behaviour in the last 3 years but now that i discovered it it is pretty anoying.

another problem: if i cancel the thread an start another, the 1st connection seems to be still alive. i can´t connect to the device since it can´t handle 2 connections. i get the exception "invalid in this context..."


so now i tried with beginconnect and closing the client after a few seconds, but it doesn´t work, the connection seems to stay alive.

here my code:

try
        {
            int timout = Convert.ToInt32(txttimeout.Text);               
            BluetoothAddress addr = BluetoothAddress.Parse("00126F254CBC");
            Guid serviceClass = new Guid();
            serviceClass = BluetoothService.SerialPort;
            BluetoothEndPoint btEndPoint = new BluetoothEndPoint(addr, serviceClass);

            NetworkClient = TimeOutSocket.Connect(btEndPoint, timout, addr);

            NetworkStream networkstream = NetworkClient.GetStream();
            StreamWriter streamWriter = new StreamWriter(networkstream);

            streamWriter.Write(200);                
            streamWriter.Close();
            networkstream.Close();
            NetworkClient.Close();
            MessageBox.Show("success");
        }
and the TimeOutSocket class:


public static BluetoothClient Connect(BluetoothEndPoint remoteEndPoint, int timeoutMSec, BluetoothAddress addr)
    {
        TimeoutObject.Reset();
        socketexception = null;  

        BluetoothClient btclient = new BluetoothClient();        
        btclient.BeginConnect(remoteEndPoint, new AsyncCallback(CallBackMethod), btclient);

        if (TimeoutObject.WaitOne(timeoutMSec, false))
        {
            if (IsConnectionSuccessful)
            {
                return btclient;
            }
            else
            {
                throw socketexception;
            }
        }
        else
        {
            btclient.Close();
            throw new TimeoutException("TimeOut Exception");
        }
    }
    private static void CallBackMethod(IAsyncResult asyncresult)
    {
        try
        {
            IsConnectionSuccessful = false;
            BluetoothClient tcpclient = asyncresult.AsyncState as BluetoothClient;

            if (tcpclient.Client != null)
            {
                tcpclient.EndConnect(asyncresult);
                IsConnectionSuccessful = true;
                //tcpclient.Close();
            }
        }
        catch (Exception ex)
        {
            IsConnectionSuccessful = false;
            socketexception = ex;
        }
        finally
        {
            TimeoutObject.Set();
        }
    }
hope anyone can help :(