private void StartService() { Guid guid = StandardServices.SerialPortServiceGuid; 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(); }
代码1 SetRadioMode检查本端Bluetooth设备是否为可发现,如果不可发现就设置为可发现。本地Bluetooth设备的状态分成三种:On,Off,Discoverable。在Windows Embedded Source Tools for Bluetooth库里面查询和设置设备RadioMode的函数有点问题,只能用在Windows Mobile里面,如果在Wince里使用,需要对SafeNativeMethods.cs进行以下的修改: //It does not support Wince 5 since Wince 5 does not include bthutil.dll //[DllImport(BTHUTIL_DLL)] //public static extern int BthGetMode(ref BluetoothRadioMode mode); //[DllImport(BTHUTIL_DLL)] //public static extern int BthSetMode(BluetoothRadioMode mode);
public static int BthGetMode(ref BluetoothRadioMode mode) { int mask = 0; int ret = BthReadScanEnableMask(ref mask); switch (mask) { case 0x0: mode = BluetoothRadioMode.Off; break; case 0x2: mode = BluetoothRadioMode.On; break; case 0x3: mode = BluetoothRadioMode.Discoverable; break; } return ret; }
public static int BthSetMode(BluetoothRadioMode mode) { int mask = 0; switch (mode) { case BluetoothRadioMode.Off: mask = 0x0; break; case BluetoothRadioMode.On: mask = 0x2; break; case BluetoothRadioMode.Discoverable: mask = 0x3; break; } return BthWriteScanEnableMask(mask); }
[DllImport(BTDRT_DLL)] public static extern int BthReadScanEnableMask(ref int mask);
[DllImport(BTDRT_DLL)] public static extern int BthWriteScanEnableMask(int mask);
从上面的例子看Windows Embedded Source Tools for Bluetooth的功能不是很完整,没有自动发现功能,也就是通信双方在通信之前需要配对成功,因此这样很不方便。而且Windows Embedded Source Tools for Bluetooth只是支持 Microsoft windows stack,不支持broadcom stack,后面文章会介绍另外一个的开源库32feet.NET。这个库支持自发现功能,同时部分支持broadcom stack。
文章评论(0条评论)
登录后参与讨论