Windows Moible, Wince 使用.NET Compact Framework的进行蓝牙(Bluetooth)设备配对的开发

.NET Compact Framework下的Bluetooth开发 之 32feet.NET 里讲述了如何使用32feet.net库来进行Bluetooth的开发,天机 同学在使用过程发现设备配对问题,本文讲述如何进行Bluetooth设备配对的开发。

以下是一个Bluetooth配对程序。在配对之前先扫描附近的Bluetooth设备。

bt_pair1

        BluetoothClient client = new BluetoothClient();
        Dictionary
<string, BluetoothAddress> deviceAddresses = new Dictionary<string, BluetoothAddress>();
        
private void menuItem2_Click(object sender, EventArgs e)
        {
            
//Turn on the bluetooth
            BluetoothRadio radio = BluetoothRadio.PrimaryRadio;
            radio.Mode 
= RadioMode.Connectable;

            
//Scan the nearby devices
            BluetoothDeviceInfo[] devices = client.DiscoverDevices();
            listBoxDevices.Items.Clear();
            deviceAddresses.Clear();
            
foreach(BluetoothDeviceInfo device in devices)
            {
                listBoxDevices.Items.Add(device.DeviceName);
                deviceAddresses[device.DeviceName] 
= device.DeviceAddress;
            }
        }

deviceAddresses 用于保存设备名字和设备地址的映射。当点击 Discover 菜单,先修改BluetoothRadio 的 property Mode 来打开Bluetooth设备,然后通过DiscoverDevices() 函数来扫描附近的所有Bluetooth设备。

 bt_pair2

这是扫描的结果, Jake为我的手机, AV890为Bluetooth 耳机。点击AV890 然后点击 Pair 菜单进行配对。AV890的默认配对密码为 0000。

bt_pair3

配对的代码如下:

        private void menuItem3_Click(object sender, EventArgs e)
        {
            
try
            {
                BluetoothAddress deviceAddress 
= deviceAddresses[listBoxDevices.SelectedItem.ToString()];
                client.SetPin(deviceAddress, textBoxPin.Text.Trim());
                client.Connect(deviceAddress, BluetoothService.Handsfree); 
//if connect ot Hands free.
                
//client.Connect(deviceAddress, BluetoothService.SerialPort); //if connect to cell phone and so forth.
                MessageBox.Show("Pair successful.");

                
//transfer data..
            }
            
catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

由于设备有密码,所以配对的时候需要设置密码,使用 SetPin()函数设置对端设备的密码。SetPin() 函数使用了下面的API

[DllImport("btdrt.dll", SetLastError=true)]
public static extern int BthSetPIN(byte[] pba, int cPinLength, byte[] ppin);

 

Connect() 函数的第二个参数十分重要,天机 同学的程序配对失败可能是因为在这里没有设置正确。参数二是服务类型,通信双方必须使用同样的服务类型。如果通信双方的程序都是由我们负责开发,可以使用通用的服务类型,例如BluetoothService.SerialPort。但是如果要与第三方设备进行通信,需要查出该设备的服务类型,在设备端的通信服务类型一般编写在Firmware(固件)里面,而且会按照规范编写,例如Bluetooth耳机会使用BluetoothService.Handsfree。具体的规范可以参考下面文章。http://en.wikipedia.org/wiki/Bluetooth_profile

在32feet.net里使用BluetoothService来定义服务类型,如下:


Code

配对成功后的界面。

bt_pair4

可以在配对成功(connection()函数)后加入相应的通信处理代码。

 

源代码:https://files.cnblogs.com/procoder/BluetoothPairing.rar

运行环境:VS2008 + Windows Mobile 5 Pocket PC SDK  + CF.NET 2.0

 

posted @ 2009-06-17 08:09  Jake Lin  阅读(8339)  评论(41编辑  收藏  举报