栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

Winform BLE 蓝牙通信

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Winform BLE 蓝牙通信

在网上找了很多资料关于Winform如何使用电脑自带蓝牙与设备(手机、仪器、工具、3C电器等等)的低功耗蓝牙(BLE)进行通信的示例,找了很久都没有一个完整的解决方案,最近终于经过自己的不断研究实现了在Winform上实现了与BLE设备的蓝牙通信。

Winform BLE可在Windows 10/11系统下运行。

这里将几个关键点说明下,供大家参考:

1. 准备工作

添加两个引用:

System.Runtime.WindowsRuntime

Windows

路径:

C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETCorev4.5System.Runtime.WindowsRuntime.dll

C:Program Files (x86)Windows Kits10UnionMetadata10.0.19041.0Windows.winmd

2. 工程中添加命名空间

using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;

添加完成后,BluetoothLEDevice,DeviceWatcher,GattCharacteristic这些类就可以使用了。

3. 搜索蓝牙设备

这里推荐使用DeviceWatcher来查找蓝牙

// Query for extra properties you want returned
                string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.Bluetooth.Le.IsConnectable", "System.Devices.Aep.CanPair", "System.Devices.Aep.IsConnected" };
                DeviceWatcher deviceWatcher =
                            DeviceInformation.CreateWatcher(
                                    BluetoothLEDevice.GetDeviceSelectorFromAppearance(BluetoothLEAppearance.FromParts(BluetoothLEAppearanceCategories.Uncategorized, BluetoothLEAppearanceSubcategories.Generic)),
                                    requestedProperties,
                                    DeviceInformationKind.AssociationEndpoint);

                // Register event handlers before starting the watcher.
                // Added, Updated and Removed are required to get all nearby devices
                deviceWatcher.Added += DeviceWatcher_Added;
                deviceWatcher.Updated += DeviceWatcher_Updated;
                deviceWatcher.Removed += DeviceWatcher_Removed;

                // EnumerationCompleted and Stopped are optional to implement.
                deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
                deviceWatcher.Stopped += DeviceWatcher_Stopped;


                // Clear BLE List
                // Start the watcher.
                deviceWatcher.Start();

4. 连接设备

await BluetoothLEDevice.FromIdAsync(DeviceInformation.Id);

连接状态可通过BluetoothLEDevice.ConnectionStatusChanged事件获得

成功连接状态:(sender.ConnectionStatus == BluetoothConnectionStatus.Connected)

5. 搜索服务和特征值获取

在连接设备后即可进行服务搜索:

BluetoothLEDevice.GetGattServicesAsync().Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    var services = asyncInfo.GetResults().Services;

                    if (services?.Count > 0)
                    {
                        foreach (GattDeviceService serv in services)
                        {
                            GattCharacteristicsResult result = await serv.GetCharacteristicsAsync();

                            foreach (GattCharacteristic gc in result.Characteristics)
                            {
                                //获取到characteristics先存储起来
                            }
                        }
                    }
                    //选择蓝牙通信characteristics使用的特征值
                }
            };

6. 读写数据通信

如果characteristics具备Notify特性,可以使用事件通知方式获取接受数据

Characteristic.ValueChanged += BleCom_NotifyCharacteristic_ValueChanged;

使用:

byte[] dataBuf;
CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out dataBuf);

的方式取出接收到的数据。

使用:

Characteristic.WriteValueAsync

发送数据。

至此,Winform BLE蓝牙通信即可实现!

示例:

示例工程截图:

说明:该Demo Exe程序CSDN链接:BLE_Demo(WinForm).rar-C#文档类资源-CSDN文库

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号