在尝试使用c# 进行BLE蓝牙通讯时,由于我个人技术十分垃圾, 综合网上几个大佬的帖子,cv后,在实际使用中遇到种种问题,最后成功。此贴仅为了同样小白的玩家,参考。
本人使用的是笔记本电脑,通过硬件查询确认支持BLE通讯。
然后参考网上其他老师的帖子,几个老师都提供了一个BleCore的类,但cv过来发现存在各种引用问题,整个痛苦的过程,就不描述了,综合网上其他资料直接上结果。
首先需要引用下面这三个文件:
参考:
百度网盘 提取码:m7ty
在项目中添加引用,在预览中将下载到的文件加入进去,然后引用
之后参考Jerrt-J老师的帖子cv了老师的类和引用
C# BLE蓝牙开发之使用Windows.Devices.Bluetooth获取小米体重秤的体重_Jerrt-J的博客-CSDN博客
代码都是cv老师的,但老师没有提供BleCore类上的引用,下面补充:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Test;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.UI.Text;
按照老师的说法,我们要在DeviceWatcherChanged方法中,修改蓝牙的名字或者地址来进行连接,之后根据UUID获取服务。
直接执行老师的代码,选择想要连接的蓝牙名字或者地址,把名字或地址卸载老师留好的位置上,就能获得服务的UUID。
例如:if (currentDevice.Name.Equals(ESP32 BLE) || currentDevice.DeviceId.Contains("a0:b7:65:dc:0e:c6"))
通过名字或地址都可以连接成功,会获得服务的UUID如下图:
6e400003是写入,6e400002是广播,因此我们要使用两次setoperon方法来获取服务。
/// <summary>
/// 搜索并连接
/// </summary>
/// <param name="currentDevice"></param>
private static void DeviceWatcherChanged(BluetoothLEDevice currentDevice)
{
byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
Array.Reverse(_Bytes1);
string address = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
Console.WriteLine("发现设备:<" + currentDevice.Name + "> address:<" + address + ">");
//if (currentDevice.Name.Equals(name) || currentDevice.DeviceId.Contains("a0:b7:65:dc:0e:c6"))
if (currentDevice.Name.Equals(name))
{
ConnectDevice(currentDevice);
GattCharacteristic gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("6e400002-b5a3-f393-e0a9-e50e24dcca9e")); });
bleCore.SetOpteron(gattCharacteristic);
gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("6e400003-b5a3-f393-e0a9-e50e24dcca9e")); });
bleCore.SetOpteron(gattCharacteristic);
Console.WriteLine("连接成功");
}
//指定一个对象,使用下面方法去连接设备
//ConnectDevice(currentDevice);
}
再次执行代码,会发现程序可以给ESP32发送信息,但是ESP32发送的信息我们无法收到,原因是老师源代码可能使用的服务是write|Notify,我实际使用需要将这两个服务分开,因此单独跳入Notify的if判断中时,没有注册接事件。所以,根据需要我将代码进行了修改,将老师下面的代码复制了一份放在上面。
if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Notify)
{
this.CurrentNotifyCharacteristic = gattCharacteristic;
this.CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
this.CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
this.CurrentDevice.ConnectionStatusChanged += this.CurrentDevice_ConnectionStatusChanged;
this.EnableNotifications(CurrentNotifyCharacteristic);
}
再次执行,程序可以发送也可以接收。