windows 蓝牙开源工具包分析及C#实例

windows 蓝牙开源工具包分析及C#实例


.1.zip>中是使用“Windows Embedded Source Tools for Bluetooth”开发的实例程序。
Bluetooth的应用十分广泛,基于Bluetooth的通信程序开发主要有以下几个步骤:
服务端
* 设置本设备为可发现。
* 公开服务给其他Bluetooth设备访问。
* 接受其他Bluetooth设备的链接。
* 与链接上的Bluetooth设备进行通信。
客户端
* 发现周边Bluetooth设备。
* 主动与被发现的设备发起连接。
* 与链接上的Bluetooth设备进行通信。
在.NET Compact Framework下进行Bluetooth开发有几个可选解决方案
* 可以P/Invoke直接调用Bluetooth的API(btdrt.dll)
* 使用MS的Windows Embedded Source Tools for Bluetooth
* 使用32feet.NET库

这篇文章讲述基于Windows Embedded Source Tools for Bluetooth的开发,点击 链接 下载Windows Embedded Source Tools for Bluetooth,安装后在目录 C:\Program Files\Microsoft\Windows Embedded Source Tools会找到源码以及编译后的DLL。
Windows Embedded Source Tools for Bluetooth提供的API总结如下:
BluetoothRadio.cs
分析:
public enum BluetoothRadioMode : int
    {
        Off,        On,        Discoverable
    };

API:
bool Dispose()     设置蓝牙设备运行被发现或读取当前蓝牙设备是否允许被发现
BluetoothRadioMode BluetoothRadioMode()     设置或去读当前蓝牙状态
BluetoothDeviceCollection PairedDevices()    获取配对设备集
class BluetoothRadio :BluetoothRadio()    初始化蓝牙系统构造类

BluetoothEndPoint.cs
分析:
class BluetoothEndPoint    蓝牙端点构造类。
构造时包含deviceAddress ,serviceGuid,port三个值。

BluetoothService.cs
分析:
class BluetoothService:BluetoothService(Guid serviceGuid)    蓝牙服务端构造类,执行该构造类的应该是蓝牙通信中的主设备。
void Start()    启动服务
void Stop()    停止服务
bool Started    获取服务状态,启动或停止
bool ConnectionPending     指示是否有一个客户端等待连接到本服务上。
NetworkStream AcceptConnection()    接受一个连接,执行该函数后,该函数会挂起直到一个客户端连接上来。
Guid ServiceGuid    返回本服务的GUID

StandardServices.cs
分析:
class StandardServices:StandardServices()    
标准的蓝牙服务列表的GUID
Guid     SerialPortServiceGuid    返回串口服务对应的GUID

Registry.cs
分析:
class Registry    封装的注册表操作类。

SafeNativeMethods.cs
分析:
class SafeNativeMethods    构造类。

导入以下类库的API:
const string BTHUTIL_DLL = "bthutil.dll";
const string BTDRT_DLL = "btdrt.dll";
const string WINSOCK_DLL = "Ws2.dll";
const string CORE_DLL = "coredll.dll";

BluetoothDeviceCollection.cs
分析:
class BluetoothDeviceCollection    蓝牙设备集类,实际为一个ArrayList();

实测程序例子:

服务器端:
private void SetRadioMode()
        {
            BluetoothRadio br = new BluetoothRadio();
            //WriteMessage("Radio Mode:" + br.BluetoothRadioMode);

            if (br.BluetoothRadioMode != BluetoothRadioMode.Discoverable)
            {
                br.BluetoothRadioMode = BluetoothRadioMode.Discoverable;
                //WriteMessage("Radio Mode:" + br.BluetoothRadioMode);
            }
        }
        private void StartService()
        {
            Guid guid = StandardServices.SerialPortServiceGuid;
            BluetoothService service = new BluetoothService(guid);
            service.Start();
            //WriteMessage("Service started!");
            System.Net.Sockets.NetworkStream ns = service.AcceptConnection(); //Warning: this is blocking code 
            //WriteMessage("Got a request!");
            string dataToSend = "Hello from service!";
            // Convert dataToSend into a byte array
            byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(dataToSend);
            // Output data to stream
            ns.Write(dataBuffer, 0, dataBuffer.Length);
            byte[] buffer = new byte[2000];
            while (service.Started )//&& !stop)
            {
                if (ns.DataAvailable)
                {
                    ns.Read(buffer, 0, 50);
                    string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 50);
                   // WriteMessage("Receiving data:" + data);
                }
            }
            // Clear and close stream
            ns.Flush();
            ns.Close();
        }
//////////////////////////////////////////
int main()
{
    SetRadioMode();
    StartService();
}

客户端:

private void PairedDevices()
        {
            BluetoothRadio br = new BluetoothRadio();
            BluetoothDeviceCollection devices = br.PairedDevices;
            foreach (BluetoothDevice device in devices)
            {
                WriteMessage("ID:" + device.Address[5].ToString("X2") + "-"
                    + device.Address[4].ToString("X2") + "-"
                    + device.Address[3].ToString("X2") + "-"
                    + device.Address[2].ToString("X2") + "-"
                    + device.Address[1].ToString("X2") + "-"
                    + device.Address[0].ToString("X2") + ", Name:" + device.Name);
            }
            ConnectService(devices[0] as BluetoothDevice);
        }
        private void ConnectService(BluetoothDevice device)
        {
            Guid guid = StandardServices.SerialPortServiceGuid;
            // Create network stream object
            // Connect to the device service (via the GUID)
            System.Net.Sockets.NetworkStream ns = device.Connect(guid);
            // Create storage for receiving data
            byte[] buffer = new byte[2000];
            byte[] SendBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes("DT\r");
            ns.Write(SendBuffer, 0, SendBuffer.Length);
            // Read Data
            ns.Read(buffer, 0, 50);
            // Convert Data to String
            string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 50);
            WriteMessage("Receiving data: " + data);
            ////////////////////////////////////////////////////////////
            SendBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes("TD\r");
            ns.Write(SendBuffer, 0, SendBuffer.Length);
            // Read Data
            ns.Read(buffer, 0, 50);
            // Convert Data to String
            data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 50);
            WriteMessage("Receiving data: " + data);
            ////////////////////////////////////////////////////////////
            int i = 0;
            while (true )
            {
                WriteMessage("Writing: " + i.ToString());
                byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(i.ToString());
                ns.Write(dataBuffer, 0, dataBuffer.Length);
                ++i;
                if (i >= int.MaxValue)
                {
                    i = 0;
                }
                System.Threading.Thread.Sleep(500);
            }
            // Close network stream
            ns.Close();
        }

int main()
{
    PairedDevices();
}


特别说明:
Windows Embedded Source Tools for Bluetooth不支持自发现功能,所以在客户端的设备首先要和服务端的设备进行配对,所谓配对就是把对端的信息写入注册表里面。PairedDevices()取出配对信息,其实就是从注册表里面取信息,Windows Embedded Source Tools for Bluetooth这个功能也写得不好,如果在wince下使用需要修改BluetoothRadio.cs文件的PairedDevices属性。
//const string BT_DEVICE_KEY_NAME = "Software\\Microsoft\\Bluetooth\\Device";
const string BT_DEVICE_KEY_NAME = "Software\\Microsoft\\Bluetooth\\Device\\pan"; //wince 5
代码4
在wince下,注册表的位置取决于配对设备的类型,见下图。

图1
不同类型的配对设备放在不同的目录下。
但是在Windows Mobile下,所有配对信息存放于Software\\Microsoft\\Bluetooth\\Device下。

图2
ConnectService()的功能是链接服务端的设备。链接前同样选择串口服务,服务端和客户端需要使用统一的服务类型才能通信。在例子中连接后从服务端接收欢迎信息,然后不断往服务端发送数据。
从上面的例子看Windows Embedded Source Tools for Bluetooth的功能不是很完整,没有自动发现功能,也就是通信双方在通信之前需要配对成功,因此这样很不方便。而且Windows Embedded Source Tools for Bluetooth只是支持 Microsoft windows stack,不支持broadcom stack,后面文章会介绍另外一个的开源库32feet.NET。这个库支持自发现功能,同时部分支持broadcom stack。


以上参考来源: for Bluetooth|中国IT实验室>

你可能感兴趣的:(windows)