Surface Pro 3 Windows 8.1的蓝牙API

7

我有一个来自Radius Networks的蓝牙按钮。“添加蓝牙设备”的内置功能每次都可以找到它。

我需要一个API或者是一个堆栈,可以从我的应用程序中使用。我正在使用C#编写。库32 feet不兼容。


https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Dn264587.aspx - ravenx30
1个回答

4
为了枚举连接到设备的RFCOMM蓝牙设备,请执行以下操作:
var DEVICE_ID = new Guid("{00000000-0000-0000-0000-000000000000}"); //Enter your device's RFCOMM service id (try to find it on manufactorer's website
var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(
        RfcommDeviceService.GetDeviceSelector(
            RfcommServiceId.FromUuid(DEVICE_ID)));

要连接到第一个可用设备,请执行以下操作:

if (services.Count > 0) 
{
   var service = await RfcommDeviceService.FromIdAsync(services[0].Id);
   //Open a socket to the bluetooth device for communication. Use the socket to communicate using the device's API
   var socket = new StreamSocket();
   await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName, SocketProtectionLevel
                .BluetoothEncryptionAllowNullAuthentication); //Substitue real BluetoothEncryption
}

要向设备发送数据并读取返回的数据,请执行以下操作:

var BYTE_NUM = 64 as UInt32; //Read this many bytes
IInputStream input = socket.InputStream;
IOutputStream output = socket.OutputStream;
var inputBuffer = new Buffer();
var operation = input.ReadAsync(inputBuffer, BYTE_NUM, InputStreamOptions.none);
while (!operation.Completed) Thread.Sleep(200);
inputBuffer = operation.GetResults();
var resultReader = DataReader.FromBuffer(inputBuffer);
byte[] result = new byte[BYTE_NUM];
resultReader.ReadBytes(result);
resultReader.Dispose();
//Do something with the bytes retrieved. If the Bluetooth device has an api, it will likely specify what bytes will be sent from the device
//Now time to give some data to the device
byte[] outputData = Encoding.ASCII.GetBytes("Hello, Bluetooth Device. Here's some data! LALALALALA");
IBuffer outputBuffer = outputData.AsBuffer(); //Neat method, remember to include System.Runtime.InteropServices.WindowsRuntime
operation = output.WriteAsync(outputBuffer);
while (!operation.Completed) Thread.Sleep(200);
await output.FlushAsync(); //Now the data has really been written

如果你的设备使用蓝牙低功耗,请使用相应的GATT类,而对于所有RFCOMM(正常)蓝牙设备,这个方法都有效。


https://msdn.microsoft.com/zh-cn/library/windows.devices.bluetooth.genericattributeprofile.gattdeviceservice.aspx 看起来你在使用UWP。我想在UWP之外使用它。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接