一、前言
本文将会详细介绍如何使用C#语言在PC上实现蓝牙设备的搜索与数据传输。在使用之前我们需要先安装对应的.net Framework和Win32 API支持库文件。
二、搜索蓝牙设备
1. 使用WMI查找
我们可以使用WMI对象获取当前计算机中的所有蓝牙设备并进行遍历。搜索蓝牙设备可以通过以下代码实现:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity where DeviceID like '%_VID_%%%' or DeviceID like '%_vid_%%%'");
foreach (ManagementObject device in searcher.Get())
{
String HardwareID = (string[])device["HardwareID"] ?? new string[0];
if (HardwareID.Length < 1)
continue;
if (HardwareID[0].ToLower().Contains("vid_0489")) //根据蓝牙设备的厂家VID判断是否为蓝牙设备
{
String id = (string)device["PNPDeviceID"];
}
}
- 使用API查找
除了WMI,我们还可以通过Win32 API函数来进行查找蓝牙设备。其中主要的API有BluetoothFindFirstRadio和BluetoothFindNextRadio函数。搜索蓝牙设备可以通过以下代码实现:
public static Guid BLUETOOTH_DEVICE_GUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
public static Guid BLUETOOTH_SERVICE_BROWSE_GUID = new Guid("{00000000-0000-0000-0000-000000000000}");
[DllImport("BluetoothAPIs.dll", SetLastError = true)]
public static extern IntPtr BluetoothFindFirstRadio(ref BLUETOOTH_FIND_RADIO_PARAMS pbtfrp, ref IntPtr phRadio);
[DllImport("BluetoothAPIs.dll", SetLastError = true)]
public static extern bool BluetoothFindNextRadio(IntPtr hFind, ref IntPtr phRadio);
[DllImport("BluetoothAPIs.dll", SetLastError = true)]
public static extern bool BluetoothFindDeviceClose(IntPtr hFind);
[DllImport("BluetoothAPIs.dll", SetLastError = true)]
public static extern IntPtr BluetoothFindFirstDevice(ref BLUETOOTH_DEVICE_SEARCH_PARAMS pbtsp, ref BLUETOOTH_DEVICE_INFO pbtdi);
[DllImport("BluetoothAPIs.dll", SetLastError = true)]
public static extern bool BluetoothFindNextDevice(IntPtr hFind, ref BLUETOOTH_DEVICE_INFO pbtdi);
[DllImport("BluetoothAPIs.dll", SetLastError = true)]
public static extern bool BluetoothSetServiceState(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, ref Guid pGuidService, uint dwServiceFlags);
public static void SearchBluetoothDevices()
{
BLUETOOTH_FIND_DEVICE_SEARCH_PARAMS searchParams = new BLUETOOTH_FIND_DEVICE_SEARCH_PARAMS();
searchParams.fReturnAuthenticated = true;
searchParams.fReturnRemembered = true;
searchParams.fReturnUnknown = true;
searchParams.fReturnConnected = true;
searchParams.fIssueInquiry = true;
searchParams.cTimeoutMultiplier = 4;
searchParams.hRadio = IntPtr.Zero;
BLUETOOTH_DEVICE_INFO deviceInfo = new BLUETOOTH_DEVICE_INFO();
deviceInfo.dwSize = Marshal.SizeOf(deviceInfo);
IntPtr hFind = BluetoothFindFirstDevice(ref searchParams, ref deviceInfo);
while (hFind.ToInt64() != -1)
{
Debug.WriteLine(deviceInfo.szName);
BluetoothFindNextDevice(hFind, ref deviceInfo);
}
BluetoothFindDeviceClose(hFind.ToInt64());
}
三、实现数据传输
当我们找到了需要连接的蓝牙设备之后,接下来便是实现数据的传输。蓝牙数据传输的方式一般有两种,采用RFCOMM协议或采用SPP协议。这里我们以RFCOMM协议为例,提供以下两个示例代码。
- 基本数据传输
在RFCOMM协议下,我们需要使用BluetoothSerialPort类来进行数据的发送和接收。这里提供一个基本的代码示例。
using System.IO.Ports;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Devices.Enumeration;
//...
//创建蓝牙socket并连接蓝牙设备
private async Task<bool> ConnectAsync(string deviceId, Guid serviceUuid)
{
var startupTask = StartupTask.GetAsync("MyStartupTaskId");
RfcommDeviceService rfcommService;
try
{
//建立设备
DeviceInformation allPairedDevices =
await DeviceInformation.CreateFromIdAsync(deviceId);
rfcommService =
await RfcommDeviceService.FromIdAsync(allPairedDevices.Id);
if (rfcommService == null)
{
Debug.WriteLine("此设备无法进行无线通讯。");
return false;
}
//创建蓝牙socket并连接蓝牙设备
socket = new StreamSocket();
await socket.ConnectAsync(
rfcommService.ConnectionHostName,
rfcommService.ConnectionServiceName,
SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
DataReader reader = new DataReader(socket.InputStream);
DataWriter writer = new DataWriter(socket.OutputStream);
while (true)
{
//发送数据
writer.WriteBytes(new byte[] { 0x30, 0x31, 0x32, 0x33, 0x34 });
await writer.StoreAsync();
//读取响应数据
await reader.LoadAsync(1024);
byte[] responseBytes = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(responseBytes);
Debug.WriteLine($"响应:{Encoding.UTF8.GetString(responseBytes)}");
await Task.Delay(1000);
}
}
catch (Exception e)
{
Debug.WriteLine($"发生异常:{e.Message}");
return false;
}
}
- 创建虚拟串口
我们可以使用第三方类库“32feet.NET”来创建虚拟串口。首先我们需要通过该类库创建一个蓝牙客户端,通过客户端的Stream属性进行数据的读写操作。代码示例如下:
string selectDeviceName = "<Your Device Name>";
string serviceString = BluetoothService.SerialPort.ToString();
BluetoothAddress selectDeviceAddress = BluetoothAddress.None;
BluetoothClient bluetoothClient = new BluetoothClient();
BluetoothDeviceInfo selectDevice = null;
Stream btStream = null;
//查找并连接蓝牙设备
BluetoothDeviceInfo[] devices = bluetoothClient.DiscoverDevices();
foreach (BluetoothDeviceInfo device in devices)
{
if (device.DeviceName.Equals(selectDeviceName))
{
selectDevice = device;
break;
}
}
if (selectDevice == null)
{
//未找到目标蓝牙
}
else
{
//创建RFCOMM蓝牙服务
BluetoothClient bc = new BluetoothClient();
bc.Connect(selectDevice.DeviceAddress, new Guid("{00001101-0000-1000-8000-00805F9B34FB}"));
//打开串口
btStream = bc.GetStream();
if (btStream == null)
{
//无法打开串口
}
//开始读取数据
bool startExecuted = false;
byte[] buffer = new byte[4096];
while (true)
{
if (btStream != null && btStream.CanRead)
{
int bytesRead = btStream.Read(buffer,0,buffer.Length);
//...
}
Thread.Sleep(100)
}
}
以上就是使用C#语言在PC上实现蓝牙设备的搜索与数据传输的详细攻略。本文提供了两种蓝牙设备的搜索方式和两种RFCOMM协议下的数据传输方式。我们可以根据实际的需求进行选择和优化。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:如何用C#在PC上查找连接蓝牙设备并实现数据传输 - Python技术站