Pair Bluetooth Devices to a Computer with 32Feet .Net Bluetooth Library

Pair bluetooth devices to a computer with 32feet .NET Bluetooth library

I figured out how to solve my problems and my knowledge about Bluetooth connections is a bit bigger now. If someone else has problems with that, I provide my solution. The code examples represent the C# implementation of a bluetooth controller with the 32feet Bluetooth library.

Scanning

This means that devices in range are detected. My code:

// mac is mac address of local bluetooth device
BluetoothEndPoint localEndpoint = new BluetoothEndPoint(mac, BluetoothService.SerialPort);
// client is used to manage connections
BluetoothClient localClient = new BluetoothClient(localEndpoint);
// component is used to manage device discovery
BluetoothComponent localComponent = new BluetoothComponent(localClient);
// async methods, can be done synchronously too
localComponent.DiscoverDevicesAsync(255, true, true, true, true, null);
localComponent.DiscoverDevicesProgress += new EventHandler<DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress);
localComponent.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete);

private void component_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
{
// log and save all found devices
for (int i = 0; i < e.Devices.Length; i++)
{
if (e.Devices[i].Remembered)
{
Print(e.Devices[i].DeviceName + " (" + e.Devices[i].DeviceAddress + "): Device is known");
}
else
{
Print(e.Devices[i].DeviceName + " (" + e.Devices[i].DeviceAddress + "): Device is unknown");
}
this.deviceList.Add(e.Devices[i]);
}
}

private void component_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
{
// log some stuff
}

Pairing

This means that devices get coupled with the local bluetooth device. This needs to be done once by entering a code of both sides. Can be done via code so that the user doesn't even notice that a device was added. My code for this purpose:

// get a list of all paired devices
BluetoothDeviceInfo[] paired = localClient.DiscoverDevices(255, false, true, false, false);
// check every discovered device if it is already paired
foreach (BluetoothDeviceInfo device in this.deviceList)
{
bool isPaired = false;
for (int i = 0; i < paired.Length; i++)
{
if (device.Equals(paired[i]))
{
isPaired = true;
break;
}
}

// if the device is not paired, pair it!
if (!isPaired)
{
// replace DEVICE_PIN here, synchronous method, but fast
isPaired = BluetoothSecurity.PairRequest(device.DeviceAddress, DEVICE_PIN);
if (isPaired)
{
// now it is paired
}
else
{
// pairing failed
}
}
}

Connecting

This means establishing a connection and exchanging of data. Again some code:

// check if device is paired
if (device.Authenticated)
{
// set pin of device to connect with
localClient.SetPin(DEVICE_PIN);
// async connection method
localClient.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), device);
}

// callback
private void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
// client is connected now :)
}
}

If you keep the order scan, pair, connect, everything should work fine. To send or receive data, use the GetStream() method of the BluetoothClient. It provides a network stream that can be manipulated.

Receiving a connection

If you want another device to connect with your device you need to listen to incoming connection requests. This only works if the device have already been paired before. My code:

BluetoothListener l = new BluetoothListener(LOCAL_MAC, BluetoothService.SerialPort);
l.Start(10);
l.BeginAcceptBluetoothClient(new AsyncCallback(AcceptConnection), l);

void AcceptConnection(IAsyncResult result){
if (result.IsCompleted){
BluetoothClient remoteDevice = ((BluetoothListener)result.AsyncState).EndAcceptBluetoothClient(result);
}
}

Replace LOCAL_MAC with a valid BluetoothAddress (e.g. by using BluetoothAddress.Parse();). After the devices are connected they can exchange messages via the underlying stream. If the connection does not work there might be authentication issues, so try setting the local device pin in the listener (l.SetPin(LOCAL_MAC, MY_PASSWORD);

32Feet.NET. How to pair PC with a device?

You are trying to connect without pairing.Your code is not working because you have to pair before connecting.

replace

client = new BluetoothClient();

client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);

by

BluetoothSecurity.PairRequest(Device.DeviceAddress,"123456");

Check out http://mrbikash.com/bluetooth-discovery-pairing-32feet-net/#pairing for a more detailed explanation.

32feet.net howto discover nearby bluetooth devices async in c#

This is not an answer, but I wasn't able to put this much code on comment section. Change these lines of code:

//continue listening for other broadcasting devices
listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener);

// create a connection to the device that's just been found
BluetoothClient client = listener.EndAcceptBluetoothClient();

to

// create a connection to the device that's just been found
BluetoothClient client = listener.EndAcceptBluetoothClient();

// continue listening for other broadcasting devices
listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallback, listener);

Basically, change the sequence of code..
As for every call to BeginXXXX method must have next EndXXXX. And all above code, you are trying to BeginAcceptBluetoothClient over already began "BeginAcceptBluetoothClient".

Hope you understand.

Find 32Feet BluetoothAddress of local Bluetooth adapter in C#

Posting this answer for others who may face similar scenario.

Basically to create a Bluetooth endpoint you need a valid Bluetooth mac address of the adapter. To get the local Bluetooth mac address of local machine just use

BluetoothRadio.PrimaryRadio.LocalAddress

so the above code will need to be changed to

  public static BluetoothAddress GetBTMacAddress()
{

BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;
if (myRadio == null)
{
// Console.WriteLine("No radio hardware or unsupported software stack");
return null;
}

return myRadio.LocalAddress;
}


Related Topics



Leave a reply



Submit