C# Windows 11 提供的 Bluetooth API实现蓝牙的扫描、配对、通信 例程
时间: 2024-03-06 15:48:24 浏览: 172
以下是一个 C# Windows 11 的示例代码,演示如何使用 Bluetooth API 实现蓝牙设备的扫描、配对、通信:
```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
class Program
{
static BluetoothLEDevice device;
static GattCharacteristic characteristic;
static async Task Main(string[] args)
{
// 建立连接前,先扫描设备列表并选择要连接的设备
DeviceInformationCollection devices = await BluetoothLEDevice.GetDeviceSelector().FindAllAsync();
Console.WriteLine("Found devices:");
for (int i = 0; i < devices.Count; i++)
{
Console.WriteLine($"{i + 1}. {devices[i].Name}");
}
string selection = Console.ReadLine();
int selectedIndex;
if (!int.TryParse(selection, out selectedIndex) || selectedIndex < 1 || selectedIndex > devices.Count)
{
Console.WriteLine("Invalid selection.");
return;
}
DeviceInformation selectedDevice = devices[selectedIndex - 1];
// 连接设备并获取服务和特征
device = await BluetoothLEDevice.FromIdAsync(selectedDevice.Id);
GattDeviceServicesResult servicesResult = await device.GetGattServicesAsync();
if (servicesResult.Status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to get services. Status: {servicesResult.Status}");
return;
}
GattDeviceService service = servicesResult.Services[0];
GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync();
if (characteristicsResult.Status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to get characteristics. Status: {characteristicsResult.Status}");
return;
}
characteristic = characteristicsResult.Characteristics[0];
// 订阅特征的值改变事件
characteristic.ValueChanged += Characteristic_ValueChanged;
GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to subscribe to value changes. Status: {status}");
return;
}
// 等待用户输入并向设备写入数据
Console.WriteLine("Connected to device. Enter message to send: ");
string message = Console.ReadLine();
byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
GattWriteResult writeResult = await characteristic.WriteValueAsync(data.AsBuffer());
if (writeResult.Status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to write value. Status: {writeResult.Status}");
return;
}
Console.WriteLine("Data sent. Press any key to exit.");
Console.ReadKey();
// 断开连接并清理资源
characteristic.ValueChanged -= Characteristic_ValueChanged;
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);
device.Dispose();
}
private static void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
byte[] data = args.CharacteristicValue.ToArray();
string message = System.Text.Encoding.UTF8.GetString(data);
Console.WriteLine($"Received message: {message}");
}
}
```
此代码首先扫描蓝牙设备列表并让用户选择要连接的设备。然后它连接设备并获取服务和特征。接下来,它订阅特征值改变事件,并等待用户输入要发送的消息。一旦用户输入消息,它将其转换为字节数组并向特征写入数据。它还打印从设备接收到的任何消息。最后,当用户按下任何键时,它将断开连接并清理资源。
阅读全文