C#如何在Windows上接入蓝牙设备

44 篇文章 0 订阅
6 篇文章 0 订阅

最近研究了下怎么在windows上连接蓝牙设备,并获取蓝牙设备的消息以及如何向蓝牙设备写入消息。该方法同样适用于Unity引擎。

本质上还是获取windows的底层API接口进行调用,连接蓝牙设备的流程大概是:

  1. 搜索蓝牙设备列表,并获取蓝牙设备的属性,其中有属性值有isConnectable、name等等
  2. 选择蓝牙地址进行连接,等待连接成功
  3. 搜索蓝牙设备的Services列表
  4. 搜索某个Service的Characteristics
  5. 订阅Characteristics
  6. 接收消息/写入消息

至于如何接入,微软官方有个示例工程,可以下载查看,在那基础上改即可,里面有C#,C++两种语言的。C#编译后是个uwp应用,可以编译后测试下流程。

该方法适用于接入小米手环、华为手环、其他蓝牙设备等等,然后根据协议格式解析即可。

微软官方示例工程:Bluetooth Low Energy sample - Code Samples | Microsoft Docs

GitHub封装好的Unity工程:https://github.com/adabru/BleWinrtDll

希望对大家有帮助。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
要使用C# Windows 11 API实现HID蓝牙连接,可以按照以下步骤进行: 1. 确认蓝牙适配器已经连接到计算机上,并且已经打开。 2. 使用Windows.Devices.Bluetooth命名空间中的BluetoothLEDevice.FromBluetoothAddressAsync方法获取蓝牙设备对象。 3. 使用Windows.Devices.Enumeration命名空间中的DeviceInformation.FindAllAsync方法查找设备服务。 4. 使用Windows.Devices.Bluetooth.GenericAttributeProfile命名空间中的GattDeviceService.GetCharacteristicsAsync方法获取设备特性。 5. 使用Windows.Devices.Bluetooth.GenericAttributeProfile命名空间中的GattCharacteristic.WriteValueAsync方法写入数据。 示例代码如下: ```csharp using Windows.Devices.Bluetooth; using Windows.Devices.Enumeration; using Windows.Devices.Bluetooth.GenericAttributeProfile; using System; using System.Threading.Tasks; namespace BluetoothHID { class Program { static async Task Main(string[] args) { var deviceSelector = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected); var deviceInformationCollection = await DeviceInformation.FindAllAsync(deviceSelector); if (deviceInformationCollection.Count > 0) { var bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInformationCollection[0].Id); if (bluetoothLeDevice != null) { var servicesResult = await bluetoothLeDevice.GetGattServicesAsync(); if (servicesResult.Status == GattCommunicationStatus.Success) { foreach (var service in servicesResult.Services) { var characteristicsResult = await service.GetCharacteristicsAsync(); if (characteristicsResult.Status == GattCommunicationStatus.Success) { foreach (var characteristic in characteristicsResult.Characteristics) { if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteString("Hello World"); var result = await characteristic.WriteValueAsync(writer.DetachBuffer()); if (result == GattCommunicationStatus.Success) { Console.WriteLine("Data written successfully"); } } } } } } } } } } } ``` 需要注意的是,要使用Windows 11 API实现HID蓝牙连接需要在Windows 11操作系统中运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼蛋-Felix

如果对你有用,可以请我喝杯可乐

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值