c#的winform实现ble的搜索和数据读写功能代码
时间: 2024-03-25 21:37:17 浏览: 54
以下是一个简单的C# WinForms程序,实现BLE设备的搜索和数据读写功能。需要使用NuGet包管理器安装`InTheHand.Net.Personal`和`32feet.NET`两个库。
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
namespace BLETest
{
public partial class Form1 : Form
{
private BluetoothClient _bluetoothClient = new BluetoothClient();
private BluetoothDeviceInfo _selectedDevice;
private BluetoothAddress _selectedAddress;
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
// 搜索周围的BLE设备
BluetoothDeviceInfo[] devices = _bluetoothClient.DiscoverDevices(255, true, true, false, false);
// 将搜索到的设备添加到列表框中
foreach (BluetoothDeviceInfo device in devices)
{
listBox1.Items.Add(device.DeviceName);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// 获取所选设备的地址
_selectedDevice = _bluetoothClient.GetPairedDevices().FirstOrDefault(d => d.DeviceName == listBox1.SelectedItem.ToString());
_selectedAddress = _selectedDevice.DeviceAddress;
btnConnect.Enabled = true;
}
private void btnConnect_Click(object sender, EventArgs e)
{
// 连接所选设备
BluetoothClient client = new BluetoothClient();
BluetoothDeviceInfo device = new BluetoothDeviceInfo(_selectedAddress);
if (device.InstalledServices.Length > 0)
{
// 连接到设备
client.Connect(device.DeviceAddress, device.InstalledServices[0].ServiceClass, BluetoothServiceCapabilities.None);
// 如果连接成功,则读取设备的数据
if (client.Connected)
{
try
{
Stream stream = client.GetStream();
// 读取设备发送的数据
byte[] buffer = new byte[1024];
int count = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, count);
// 将数据显示在文本框中
textBox1.Text = message;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
}
```
在上面的代码中,我们使用`BluetoothClient`类进行BLE设备的搜索和连接,并使用`BluetoothDeviceInfo`类获取设备的信息。在连接成功后,我们通过`GetStream`方法获取设备的数据流,并使用`Read`方法读取设备发送的数据。最后将数据显示在文本框中。