用C#写一个蓝牙4.0搜索、连接、接收、发送功能的demo
时间: 2023-12-27 07:02:22 浏览: 45
以下是一个简单的C#蓝牙4.0搜索、连接、接收、发送功能的示例代码。请注意,此代码仅供参考,具体实现可能因操作系统版本、硬件设备等因素而有所不同。
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
namespace BluetoothDemo
{
class Program
{
private static readonly Guid ServiceUUID = new Guid("0000fff0-0000-1000-8000-00805f9b34fb");
private static readonly Guid CharacteristicUUID = new Guid("0000fff1-0000-1000-8000-00805f9b34fb");
static async Task Main(string[] args)
{
Console.WriteLine("Searching for Bluetooth devices...");
var deviceInformationCollection = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector());
if (deviceInformationCollection.Count == 0)
{
Console.WriteLine("No devices found.");
return;
}
Console.WriteLine("Select a device to connect:");
for (int i = 0; i < deviceInformationCollection.Count; i++)
{
Console.WriteLine($"{i}: {deviceInformationCollection[i].Name} - {deviceInformationCollection[i].Id}");
}
int selectedIndex = int.Parse(Console.ReadLine());
var selectedDevice = await BluetoothLEDevice.FromIdAsync(deviceInformationCollection[selectedIndex].Id);
Console.WriteLine($"Connecting to device {selectedDevice.Name}...");
var gattServicesResult = await selectedDevice.GetGattServicesAsync();
if (gattServicesResult.Status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to get GATT services. Status: {gattServicesResult.Status}");
return;
}
var service = gattServicesResult.Services.FirstOrDefault(s => s.Uuid == ServiceUUID);
if (service == null)
{
Console.WriteLine($"Service {ServiceUUID} not found.");
return;
}
var characteristicsResult = await service.GetCharacteristicsAsync();
if (characteristicsResult.Status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to get characteristics. Status: {characteristicsResult.Status}");
return;
}
var characteristic = characteristicsResult.Characteristics.FirstOrDefault(c => c.Uuid == CharacteristicUUID);
if (characteristic == null)
{
Console.WriteLine($"Characteristic {CharacteristicUUID} not found.");
return;
}
Console.WriteLine("Connected!");
characteristic.ValueChanged += Characteristic_ValueChanged;
var status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status != GattCommunicationStatus.Success)
{
Console.WriteLine($"Failed to configure characteristic for notifications. Status: {status}");
return;
}
Console.WriteLine("Waiting for notifications...");
while (true)
{
await Task.Delay(1000);
}
}
private static void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
var data = Encoding.UTF8.GetString(args.CharacteristicValue.ToArray());
Console.WriteLine($"Received data: {data}");
}
}
}
```
在这个示例中,我们首先搜索可用的蓝牙设备,然后让用户选择要连接的设备。连接后,我们获取设备的GATT服务和特性,并将特性配置为可以接收通知。最后,我们等待特性的值改变事件,并读取从设备接收到的数据。
请注意,此示例在Windows 10操作系统上测试通过,需要使用Visual Studio开发环境和Windows.Devices.Bluetooth.GenericAttributeProfile和Windows.Devices.Bluetooth命名空间。同时,还需要确保操作系统支持蓝牙4.0,并且硬件设备已经正确安装和配置。