Reputation: 113
I write an application for Windows Form. I have a problem with pairing a device with PC. Now the program works next way: switch on the divece, start the program, add divece to Bluetooth device, push connect button. I use the next functions:
public BluetoothClient client = new BluetoothClient();
public string selectedItem { get; set; }
public BluetoothDeviceInfo[] AllDevices;
public void GetDevices()
{
AllDevices = client.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if(Device.DeviceName.Contains("Kortes"))
onSetDevices(Device.DeviceName); // event to get device name and add it to ComoBox element on form
}
onSetProgress(); // event, that all devices were found, set progress bar and etc.
}
public void GoConnect()
{
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if (Device.DeviceName.Equals(selectedItem)) // item from ComboBox
{
if (!client.Connected)
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
break;
}
else
{
MessageBox.Show("Choose the device");
}
}
}
private void BluetoothClientConnectCallback(IAsyncResult ar)
{
//Have no problem with this
}
These functions work very well. I can find and connect with needed device. But the problem is that firstly I need to add my device to Bluetooth device in OS and enter PIN code. How can I improve my code to solve this problem?
I don't want to add device. I want to work with it directly. Which methods can I use to enter PIN code programmatically? The program must work the next way: switch on the device, start the program, and push connect button.
Upvotes: 0
Views: 6246
Reputation: 277
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.
Upvotes: 4