C# 用Windows11 API实现 HID蓝牙的链接通信
时间: 2024-03-08 12:50:47 浏览: 113
好的,下面是一个简单的示例代码,可以使用 Windows 11 API 实现 HID 蓝牙的连接和通信:
```csharp
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
namespace BluetoothHidDemo
{
class Program
{
private static GattDeviceService _hidService;
private static GattCharacteristic _inputReport;
private static GattCharacteristic _outputReport;
static async Task Main(string[] args)
{
// 找到 HID Service
var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HumanInterfaceDevice));
if (devices.Count == 0)
{
Console.WriteLine("未找到 HID Service 设备");
return;
}
var device = await BluetoothLEDevice.FromIdAsync(devices[0].Id);
_hidService = device.GetGattService(GattServiceUuids.HumanInterfaceDevice);
// 找到 Input Report 和 Output Report 特征
var characteristics = _hidService.GetAllCharacteristics();
foreach (var characteristic in characteristics)
{
var props = characteristic.CharacteristicProperties;
if (props.HasFlag(GattCharacteristicProperties.Read))
{
_inputReport = characteristic;
}
if (props.HasFlag(GattCharacteristicProperties.Write))
{
_outputReport = characteristic;
}
}
// 订阅 Input Report 特征的通知
var status = await _inputReport.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
_inputReport.ValueChanged += InputReport_ValueChanged;
}
// 发送 Output Report
var buffer = new byte[] { 0x01, 0x02, 0x03 };
var writeResult = await _outputReport.WriteValueAsync(buffer.AsBuffer());
if (writeResult.Status == GattCommunicationStatus.Success)
{
Console.WriteLine("发送成功");
}
else
{
Console.WriteLine($"发送失败,错误代码:{writeResult.ProtocolError}");
}
Console.ReadLine();
}
private static void InputReport_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
var buffer = args.CharacteristicValue;
var data = new byte[buffer.Length];
Marshal.Copy(buffer.Data, data, 0, buffer.Length);
Console.WriteLine($"收到数据:{BitConverter.ToString(data)}");
}
}
}
```
需要注意的是,该代码仅供参考,具体的实现还需要根据具体的 HID 设备和蓝牙模块进行调整。
阅读全文