Smart Connect

Topics: Bluetooth - Other
Jul 13, 2012 at 10:55 PM

Might not sound bright, but...

Say I have n bt devices pre-paired to my computer. And of those n, only one will be waiting for connections. I am looking for alternate faster way to identify that 1 in n and connect() to it, rather than, looping all n, trying to connect to each etc until I reach the active one. Any suggestions?

Developer
Jul 14, 2012 at 2:37 PM

At the API level one can certainly shorten the time one waits for a Connect to complete -- probably using BeginConnect. So something like (completely untested/uncompiled):

    var listOfAddresses = ...;
    foreach (var addr in listOfAddresses) {
        var cli = new BluetoothClient();
        var ar = cli.BeginConnect(addr, null, null);
        var completed = ar.AsyncWaitHandle.WaitOne(MyTimeout);
        if (completed) {
            try {
                cli.EndConnect(ar);
                // Success. Connected.
                break;
            } catch (SocketException soex) { // The connect failed
                 // todo check the error code
            }
        } else {
           // it took longer than our timeout
           cli.Close();
           // Following .NET rules carefully, we should call EndConnect here.....
        }
    }//for

 

On one could even try running connects in parallel with similar -- but more complex -- code.

 

Either might work.  It might depend on the dongle and how the underlying Bluetooth stack handle the Close and/or multiple connects at a time...

Jul 16, 2012 at 4:32 PM

Thank you very much Alan! Will try.