C# ble 4.0 低能耗 蓝牙交互

使用C#进行低功耗蓝牙BLE开发 本人在Windows11+Vs2022环境中实测,编译时无法通过,会出现无法引用System.Runtime.dll组件、IDisposable 没有实现等错误。2.引用 Windows.Devices、Windows.Foundation、Windows.Security、Windows.Services、Windows.Storage等组件进行环境搭建的。解决方案里引用处,右键选择管理NuGet程序包,浏览->搜索 Microsoft.Windows.SDK.Contracts并安装。 阅读详情
AI摘要

本文详细介绍了在Universal Windows SDK环境下,使用C#进行蓝牙低功耗(BLE)设备的搜索、匹配、连接及数据交互的技术实现。针对蓝牙搜索速度慢的问题,提出并实现了改进方案,同时分享了两种蓝牙设备连接的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Networking;
using Windows.Networking.Proximity;
using Windows.Networking.Sockets;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;

namespace BleSolution
{
    public class BleCore
    {
        private Boolean asyncLock = false;

        /// <summary>
        /// 搜索蓝牙设备对象
        /// </summary>
        private DeviceWatcher deviceWatcher;

        /// <summary>
        /// 当前连接的服务
        /// </summary>
        public GattDeviceService CurrentService { get; set; }

        /// <summary>
        /// 当前连接的蓝牙设备
        /// </summary>
        public BluetoothLEDevice CurrentDevice { get; set; }

        /// <summary>
        /// 写特征对象
        /// </summary>
        public GattCharacteristic CurrentWriteCharacteristic { get; set; }

        /// <summary>
        /// 通知特征对象
        /// </summary>
        public GattCharacteristic CurrentNotifyCharacteristic { get; set; }

        /// <summary>
        /// 特性通知类型通知启用
        /// </summary>
        private const GattClientCharacteristicConfigurationDescriptorValue CHARACTERISTIC_NOTIFICATION_TYPE = GattClientCharacteristicConfigurationDescriptorValue.Notify;

        /// <summary>
        /// 存储检测到的设备
        /// </summary>
        private List<BluetoothLEDevice> DeviceList = new List<BluetoothLEDevice>();

        /// <summary>
        /// 定义搜索蓝牙设备委托
        /// </summary>
        public delegate void DeviceWatcherChangedEvent(MsgType type, BluetoothLEDevice bluetoothLEDevice);

        /// <summary>
        /// 搜索蓝牙事件
        /// </summary>
        public event DeviceWatcherChangedEvent DeviceWatcherChanged;

        /// <summary>
        /// 获取服务委托
        /// </summary>
        public delegate void GattDeviceServiceAddedEvent(GattDeviceService gattDeviceService);

        /// <summary>
        /// 获取服务事件
        /// </summary>
        public event GattDeviceServiceAddedEvent GattDeviceServiceAdded;

        /// <summary>
        /// 获取特征委托
        /// </summary>
        public delegate void CharacteristicAddedEvent(GattCharacteristic gattCharacteristic);

        /// <summary>
        /// 获取特征事件
        /// </summary>
        public event CharacteristicAddedEvent CharacteristicAdded;

        /// <summary>
        /// 提示信息委托
        /// </summary>
        public delegate void MessAgeChangedEvent(MsgType type, string message, byte[] data = null);

        /// <summary>
        /// 提示信息事件
        /// </summary>
        public event MessAgeChangedEvent MessAgeChanged;

        /// <summary>
        /// 当前连接的蓝牙Mac
        /// </summary>
        private string CurrentDeviceMAC { get; set; }

        public BleCore()
        {

        }

        /// <summary>
        /// 搜索蓝牙设备
        /// </summary>
        public void StartBleDeviceWatcher()
        {
            string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };
            string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";

            this.deviceWatcher =
                    DeviceInformation.CreateWatcher(
                        aqsAllBluetoothLEDevices,
                        requestedProperties,
                        DeviceInformationKind.AssociationEndpoint);

            // Register event handlers before starting the watcher.
            this.deviceWatcher.Added += this.DeviceWatcher_Added;
            this.deviceWatcher.Stopped += this.DeviceWatcher_Stopped;
            this.deviceWatcher.Start();
            string msg = "自动发现设备中..";

            this.MessAgeChanged(MsgType.NotifyTxt, msg);
        }

        /// <summary>
        /// 停止搜索蓝牙
        /// </summary>
        public void StopBleDeviceWatcher()
        {
            this.deviceWatcher.Stop();
        }

        /// <summary>
        /// 获取发现的蓝牙设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            this.MessAgeChanged(MsgType.NotifyTxt, "发现设备:" + args.Id);
            this.Matching(args.Id);
        }

        /// <summary>
        /// 停止搜索蓝牙设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
        {
            string msg = "自动发现设备停止";
            this.MessAgeChanged(MsgType.NotifyTxt, msg);
        }

        /// <summary>
        /// 匹配
        /// </summary>
        /// <param name="Device"></param>
        public void StartMatching(BluetoothLEDevice Device)
        {
            this.CurrentDevice = Device;
        }

        /// <summary>
        /// 获取蓝牙服务
        /// </summary>
        public async void FindService()
        {
            var GattServices = this.CurrentDevice.GattServices;
            foreach (GattDeviceService ser in GattServices)
            {
                this.GattDeviceServiceAdded(ser);
            }
        }

        /// <summary>
        /// 获取特性
        /// </summary>
        public async void FindCharacteristic(GattDeviceService gattDeviceService)
        {
            this.CurrentService = gattDeviceService;
            foreach (var c in gattDeviceService.GetAllCharacteristics())
            {
                this.CharacteristicAdded(c);
            }
        }

        /// <summary>
        /// 获取操作
        /// </summary>
        /// <returns></returns>
        public async Task SetOpteron(GattCharacteristic gattCharacteristic)
        {
            if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Write)
            {
                this.CurrentWriteCharacteristic = gattCharacteristic;
            }
            if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Notify)
            {
                this.CurrentNotifyCharacteristic = gattCharacteristic;
            }
            if ((uint)gattCharacteristic.CharacteristicProperties == 26)
            { }

            if (gattCharacteristic.CharacteristicProperties == (GattCharacteristicProperties.Notify | GattCharacteristicProperties.Read | GattCharacteristicProperties.Write))
            {
                this.CurrentWriteCharacteristic = gattCharacteristic;

                this.CurrentNotifyCharacteristic = gattCharacteristic;
                this.CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
                this.CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                await this.EnableNotifications(CurrentNotifyCharacteristic);
            }

            this.Connect();
        }

        /// <summary>
        /// 连接蓝牙
        /// </summary>
        /// <returns></returns>
        private async Task Connect()
        {
            byte[] _Bytes1 = BitConverter.GetBytes(this.CurrentDevice.BluetoothAddress);
            Array.Reverse(_Bytes1);
            this.CurrentDeviceMAC = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();

            string msg = "正在连接设备<" + this.CurrentDeviceMAC + ">..";
            this.MessAgeChanged(MsgType.NotifyTxt, msg);
            this.CurrentDevice.ConnectionStatusChanged += this.CurrentDevice_ConnectionStatusChanged;
        }

        /// <summary>
        /// 搜索到的蓝牙设备
        /// </summary>
        /// <returns></returns>
        private async Task Matching(string Id)
        {
            try
            {
                BluetoothLEDevice.FromIdAsync(Id).Completed = async (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        BluetoothLEDevice bleDevice = asyncInfo.GetResults();
                        this.DeviceList.Add(bleDevice);
                        this.DeviceWatcherChanged(MsgType.BleDevice, bleDevice);
                    }
                };
            }
            catch (Exception e)
            {
                string msg = "没有发现设备" + e.ToString();
                this.MessAgeChanged(MsgType.NotifyTxt, msg);
                this.StartBleDeviceWatcher();
            }
        }

        /// <summary>
        /// 主动断开连接
        /// </summary>
        /// <returns></returns>
        public void Dispose()
        {

            CurrentDeviceMAC = null;
            CurrentService?.Dispose();
            CurrentDevice?.Dispose();
            CurrentDevice = null;
            CurrentService = null;
            CurrentWriteCharacteristic = null;
            CurrentNotifyCharacteristic = null;
            MessAgeChanged(MsgType.NotifyTxt, "主动断开连接");
        }

        private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
        {
            if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && CurrentDeviceMAC != null)
            {
                string msg = "设备已断开,自动重连";
                MessAgeChanged(MsgType.NotifyTxt, msg);
                if (!asyncLock)
                {
                    asyncLock = true;
                    this.CurrentDevice.Dispose();
                    this.CurrentDevice = null;
                    CurrentService = null;
                    CurrentWriteCharacteristic = null;
                    CurrentNotifyCharacteristic = null;
                    SelectDeviceFromIdAsync(CurrentDeviceMAC);
                }
            }
            else
            {
                string msg = "设备已连接";
                MessAgeChanged(MsgType.NotifyTxt, msg);
            }
        }

        /// <summary>
        /// 按MAC地址直接组装设备ID查找设备
        /// </summary>
        public async Task SelectDeviceFromIdAsync(string MAC)
        {
            CurrentDeviceMAC = MAC;
            CurrentDevice = null;
            BluetoothAdapter.GetDefaultAsync().Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    BluetoothAdapter mBluetoothAdapter = asyncInfo.GetResults();
                    byte[] _Bytes1 = BitConverter.GetBytes(mBluetoothAdapter.BluetoothAddress);//ulong转换为byte数组
                    Array.Reverse(_Bytes1);
                    string macAddress = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                    string Id = "BluetoothLE#BluetoothLE" + macAddress + "-" + MAC;
                    await Matching(Id);
                }
            };
        }

        /// <summary>
        /// 设置特征对象为接收通知对象
        /// </summary>
        /// <param name="characteristic"></param>
        /// <returns></returns>
        public async Task EnableNotifications(GattCharacteristic characteristic)
        {
            string msg = "收通知对象=" + CurrentDevice.ConnectionStatus;
            this.MessAgeChanged(MsgType.NotifyTxt, msg);

            characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    GattCommunicationStatus status = asyncInfo.GetResults();
                    if (status == GattCommunicationStatus.Unreachable)
                    {
                        msg = "设备不可用";
                        this.MessAgeChanged(MsgType.NotifyTxt, msg);
                        if (CurrentNotifyCharacteristic != null && !asyncLock)
                        {
                            await this.EnableNotifications(CurrentNotifyCharacteristic);
                        }
                    }
                    asyncLock = false;
                    msg = "设备连接状态" + status;
                    this.MessAgeChanged(MsgType.NotifyTxt, msg);
                }
            };
        }

        /// <summary>
        /// 接受到蓝牙数据
        /// </summary>
        private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            byte[] data;
            CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);
            string str = BitConverter.ToString(data);
            this.MessAgeChanged(MsgType.BleData, str, data);
        }

        /// <summary>
        /// 发送数据接口
        /// </summary>
        /// <returns></returns>
        public async Task Write(byte[] data)
        {
            if (CurrentWriteCharacteristic != null)
            {
                CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithResponse);
                string str = "发送数据:" + BitConverter.ToString(data);
                this.MessAgeChanged(MsgType.BleData, str, data);
            }

        }
    }
}
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;

namespace BleSolution
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            this.bleCore.MessAgeChanged += BleCore_MessAgeChanged;
            this.bleCore.DeviceWatcherChanged += BleCore_DeviceWatcherChanged;
            this.bleCore.GattDeviceServiceAdded += BleCore_GattDeviceServiceAdded;
            this.bleCore.CharacteristicAdded += BleCore_CharacteristicAdded;
            this.Init();
        }

        // 异步线程
        public static void RunAsync(Action action)
        {
            ((Action)(delegate ()
            {
                action.Invoke();
            })).BeginInvoke(null, null);
        }

        BleCore bleCore = new BleCore();
        /// <summary>
        /// 存储检测到的设备
        /// </summary>
        List<Windows.Devices.Bluetooth.BluetoothLEDevice> DeviceList = new List<Windows.Devices.Bluetooth.BluetoothLEDevice>();

        /// <summary>
        /// 当前蓝牙服务列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService> GattDeviceServices = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService>();

        /// <summary>
        /// 当前蓝牙服务特征列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic> GattCharacteristics = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic>();

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (this.btnSearch.Text == "搜索")
            {
                this.listboxMessage.Items.Clear();
                this.listboxBleDevice.Items.Clear();
                this.bleCore.StartBleDeviceWatcher();
                this.btnSearch.Text = "停止";
            }
            else
            {
                this.bleCore.StopBleDeviceWatcher();
                this.btnSearch.Text = "搜索";
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (this.listboxBleDevice.SelectedItem != null)
            {
                string DeviceName = this.listboxBleDevice.SelectedItem.ToString();
                Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice = this.DeviceList.Where(u => u.Name == DeviceName).FirstOrDefault();
                if (bluetoothLEDevice != null)
                {
                    bleCore.StartMatching(bluetoothLEDevice);
                    this.btnServer.Enabled = true;
                }
                else
                {
                    MessageBox.Show("没有发现此蓝牙,请重新搜索.");
                    this.btnServer.Enabled = false;
                }
            }
            else
            {
                MessageBox.Show("请选择连接的蓝牙.");
                this.btnServer.Enabled = false;
            }
        }

        private void btnServer_Click(object sender, EventArgs e)
        {
            this.cmbServer.Items.Clear();
            this.bleCore.FindService();
        }

        private void btnFeatures_Click(object sender, EventArgs e)
        {
            this.cmbFeatures.Items.Clear();
            if (this.cmbServer.SelectedItem != null)
            {
                var item = this.GattDeviceServices.Where(u => u.Uuid == new Guid(this.cmbServer.SelectedItem.ToString())).FirstOrDefault();
                this.bleCore.FindCharacteristic(item);
            }
            else
            {
                MessageBox.Show("选择蓝牙服务.");
            }
        }

        private void btnOpteron_Click(object sender, EventArgs e)
        {
            if (this.cmbFeatures.SelectedItem != null)
            {
                var item = this.GattCharacteristics.Where(u => u.Uuid == new Guid(this.cmbFeatures.SelectedItem.ToString())).FirstOrDefault();
                this.bleCore.SetOpteron(item);
                if (item.CharacteristicProperties == (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Notify | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Read | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Write))
                {
                    this.btnReader.Enabled = true;
                    this.btnSend.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("选择蓝牙服务.");
            }
        }

        private void btnReader_Click(object sender, EventArgs e)
        {

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] dataBytes = new byte[6];

            dataBytes[0] = 0x23;
            dataBytes[1] = 0x00;
            dataBytes[2] = 0x02;
            dataBytes[3] = 0x01;
            dataBytes[4] = (byte)(dataBytes[1] + dataBytes[2] + dataBytes[3]);
            dataBytes[5] = 0x2A;

            this.bleCore.Write(dataBytes);
        }

        /// <summary>
        /// 提示消息
        /// </summary>
        private void BleCore_MessAgeChanged(MsgType type, string message, byte[] data)
        {
            RunAsync(() =>
            {
                this.listboxMessage.Items.Add(message);
            });
        }

        /// <summary>
        /// 搜索蓝牙设备列表
        /// </summary>
        private void BleCore_DeviceWatcherChanged(MsgType type, Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice)
        {
            RunAsync(() =>
            {
                this.listboxBleDevice.Items.Add(bluetoothLEDevice.Name);
                this.DeviceList.Add(bluetoothLEDevice);
                this.btnConnect.Enabled = true;
            });
        }

        /// <summary>
        /// 获取蓝牙服务列表
        /// </summary>
        private void BleCore_GattDeviceServiceAdded(Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService gattDeviceService)
        {
            RunAsync(() =>
            {
                this.cmbServer.Items.Add(gattDeviceService.Uuid.ToString());
                this.GattDeviceServices.Add(gattDeviceService);
                this.btnFeatures.Enabled = true;
            });
        }

        /// <summary>
        /// 获取特征列表
        /// </summary>
        private void BleCore_CharacteristicAdded(Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic gattCharacteristic)
        {
            RunAsync(() =>
            {
                this.cmbFeatures.Items.Add(gattCharacteristic.Uuid);
                this.GattCharacteristics.Add(gattCharacteristic);
                this.btnOpteron.Enabled = true;
            });
        }

        private void Init()
        {
            this.btnConnect.Enabled = false;
            this.btnServer.Enabled = false;
            this.btnFeatures.Enabled = false;
            this.btnOpteron.Enabled = false;
            this.btnReader.Enabled = false;
            this.btnSend.Enabled = false;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.bleCore.Dispose();
        }
    }
}

 

 

关于服务和特性:蓝牙的服务和特性包含了多种,对于开发来说无非就是通知、读、写,所以只需要过滤uuid的头就可以了

关于蓝牙服务:其实可以直接过滤uuid使用标准协议uuid的前缀:0000ffff0

关于蓝牙特征:也是可以直接过滤uuid使用标准协议uuid的前缀:0000ffff1

跳过选选择服务和特性,这两个uuid的权限比较足,给了通知、读、写的功能,对于开发来说已经足够了。

美中不足的:在搜索蓝牙设备非常花时间,大概10~20s左右才能搜索出来

关于,在universal windows  sdk 找不到引用:一直没发现是什么问题,很多博主都说重装windows SDK和windows form模块可以解决,但我重试了很多次还是无法解决。

我的解决办法是:直接浏览引用:可直接使用windows sdk 的组件内容。

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.18362.0\Windows.winmd

非常感谢 鞪林 博主的的文章,在其上做了一些改动

https://www.cnblogs.com/webtojs/p/9675956.html

解决蓝牙搜索慢的问题:

搜索对象改用未:Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher deviceWatcher;

感谢https://blog.youkuaiyun.com/shengfakun1234/article/details/110928783  https://blog.youkuaiyun.com/shengfakun1234 解决搜索慢的问题

            this.deviceWatcher = new Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher();
            this.deviceWatcher.ScanningMode = Windows.Devices.Bluetooth.Advertisement.BluetoothLEScanningMode.Active;
            this.deviceWatcher.SignalStrengthFilter.InRangeThresholdInDBm = -80;
            this.deviceWatcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -90;
            this.deviceWatcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
            this.deviceWatcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);

            this.deviceWatcher.Received += DeviceWatcher_Received;

        private void DeviceWatcher_Received(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher sender, Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementReceivedEventArgs args)
        {
            BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    if (asyncInfo.GetResults() != null)
                    {
                        BluetoothLEDevice currentDevice = asyncInfo.GetResults();

                        Boolean contain = false;
                        foreach (BluetoothLEDevice device in DeviceList)//过滤重复的设备
                        {
                            if (device.DeviceId == currentDevice.DeviceId)
                            {
                                contain = true;
                            }
                        }
                        if (!contain)
                        {
                            this.DeviceList.Add(currentDevice);
                            this.DeviceWatcherChanged(currentDevice);
                        }
                    }
                }
            };

        }

 

 

关于蓝牙连接不上去,大伙可能有很多疑意,下面更新连接的两种方式
这里的MAC就是DeviceId,像:BluetoothLE#BluetoothLE20:0d:b0:16:00:ce-50:51:a9:7d:07:73

连接的时候使用的是id,通过前缀和mac拼接的一个ID,用这个ID去连接

1:按MAC地址查找系统中配对设备

当前设备PC已经已经连接或者配对成功的列表,从PC中寻找这个MAC配对,如果PC未配对则无法找到设备

        /// <summary>
        /// 按MAC地址查找系统中配对设备
        /// </summary>
        /// <param name="MAC"></param>
        public async Task SelectDevice(string MAC)
        {
            CurrentDeviceMAC = MAC;
            CurrentDevice = null;
            DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()).Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    DeviceInformationCollection deviceInformation = asyncInfo.GetResults();
                    foreach (DeviceInformation di in deviceInformation)
                    {
                        await Matching(di.Id);
                    }
                    if (CurrentDevice == null)
                    {
                        string msg = "没有发现设备";
                        StartBleDeviceWatcher();
                    }
                }
            };
        }

2:按MAC地址直接组装设备ID查找设备

在系统之外寻找并且配对,就是说当前PC未连接配对的设备,添加新的蓝牙、打印机设备并且连接

        /// <summary>
        /// 按MAC地址直接组装设备ID查找设备
        /// </summary>
        /// <param name="MAC"></param>
        /// <returns></returns>
        public async Task SelectDeviceFromIdAsync(string MAC)
        {
            CurrentDeviceMAC = MAC;
            CurrentDevice = null;
            BluetoothAdapter.GetDefaultAsync().Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    BluetoothAdapter mBluetoothAdapter = asyncInfo.GetResults();
                    if (mBluetoothAdapter != null)
                    {
                        await Matching(MAC);
                    }
                    else
                    {
                        string msg = "查找连接蓝牙设备异常.";
                    }
                }

            };
        }

 

代码地址:https://download.youkuaiyun.com/download/code_long/13686504

c# 居于Ble的蓝牙通讯数据交互 1、ble 的蓝牙通讯协议UUID。3、定义一个ble交互类。2、定义一个Enum。 阅读详情

相关推荐

Winform项目里用C#玩转BLE:从扫描到通信,一个实战Demo搞定所有(附避坑清单)

本文详细介绍了在Winform项目中使用C#开发BLE(低功耗蓝牙)应用的全流程,包括环境配置、设备扫描、连接通信等关键步骤,并提供了实战Demo和避坑清单。特别针对Winform与BLE蓝牙通信中的常见问题,如版本兼容性、线程安全和数据解析等,给出了专业解决方案,帮助开发者高效实现硬件交互功能。

weixin_42561040的博客 415

c#下BLE蓝牙通信

c#BLE蓝牙通信简单记录

TanZL的博客 1万+

C# 与蓝牙信标(Bluetooth Beacon)集成:如何实现位置跟踪与地理围栏应用

摘要:本文探讨了如何利用C#实现蓝牙信标(Bluetooth Beacon)的集成,构建位置跟踪与地理围栏应用。蓝牙信标通过广播信号实现短距离定位,适用于室内导航、智能门禁等场景。文章介绍了C#通过Windows.Devices.Bluetooth API扫描信标的方法,并提供了基于RSSI信号强度估算距离的代码示例。此外,还展示了地理围栏功能实现,通过判断设备与信标的距离触发特定事件。该技术为物联网、零售等领域提供了低成本、低功耗的定位解决方案。(150字)

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 498

C#和低功耗蓝牙BLE通讯

以前都是用手机APP和蓝牙设备通信,现在在一个项目中需要更改为用电脑端上位机与蓝牙通讯的需求,在此记录自己走过的坑和积攒的经验。

weixin_40314351的博客 1万+

告别30秒等待!优化C# BLE设备搜索,Win10下3秒快速发现蓝牙锁(附核心代码对比)

本文详细介绍了如何优化C# BLE设备搜索,在Win10下将蓝牙锁的发现时间从30秒缩短至3秒。通过调整扫描模式、信号强度过滤和广播设置等关键参数,显著提升BLE设备搜索效率。文章包含核心代码对比和实战测试数据,帮助开发者快速实现高性能蓝牙设备发现。

weixin_42524824的博客 331

Python蓝牙通信与传感器数据解析:Joy-Con手柄PC端开发实战

蓝牙低能耗(BLE)通信协议是物联网和嵌入式设备中广泛使用的无线技术,它通过定义服务(Service)和特征值(Characteristic)来实现设备间高效、低功耗的数据交换。在Python生态中,开发者可以利用bluepy、bleak等库进行蓝牙设备发现、连接与数据读写,这为硬件交互和原型开发提供了强大支持。其技术价值在于将封闭的消费电子设备转变为开放的可编程平台,极大降低了传感器数据获取和自定义控制的门槛。典型的应用场景包括体感交互、运动数据采集、机器人控制以及自定义输入设备开发。本文以任天堂Swit

weixin_30036289的博客 328

C BLE 4.0 低能耗蓝牙交互解决方案

C# BLE 4.0 低能耗蓝牙交互解决方案 去发现同类优质开源项目:https://gitcode.com/ 简介 BleSolution.zip 是一个包含C#代码的资源文件,旨在帮助开发者实现BLE 4.0低能耗蓝牙设备的连接、适配、服务发现和特征交互。通过本解决方案,您可以轻松地在Windows平台上配对蓝牙设备并进行数据交互。 功能特点 BLE 4.0 低能耗蓝牙支持:专为低能耗蓝牙设...

gitblog_09806的博客 521

C#ble低功耗蓝牙

弄了好久的C#WINFORM上的低功耗蓝牙,需要在WIN10上 VS2017上运行的。

C#实现笔记本自带蓝牙与汇承HC-08(BLE)蓝牙模块通讯

汇承HC-08蓝牙C#通讯 目录问题背景感谢BLE介绍参考代码参考业务逻辑参考库和例程难点介绍难点介绍新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 问题背景 因最近新项目需要与蓝牙仪器通讯,起初以为很简单,搜索一下C#蓝

Vishera的博客 5994

蓝牙ble连接和数据读取

亲测有用的,还有普通连接,ble连接,数据读取,数据同步等等

windows BLE编程 net winform 连接蓝牙低功耗

winform 程序调用Windows.Devices.Bluetoot API 实现windows下BLE蓝牙设备自动连接,收发数据功能。不需要使用win10的UWP开发。 实际例子用vs2022编写,可直接编译运行

每天记录学习的新知识 :蓝牙BLE数据传输记录

参考地址:android蓝牙BLE(一) —— 扫描 参考地址:蓝牙BLE(BlueTooth BLE)入门及爬坑指南 简介: Google在android 4.3(API Level 18)的android版本中引入了低功耗蓝牙BLE核心API。低功耗蓝牙BLE也就是我们经常说的蓝牙4.0。 BLE区别于经典蓝牙,有搜索、连接的速度更快、低能耗的优点;缺点是传输的速度慢,传输的数据量也很小,每次...

嗯... 2916

【Unity报错】Unity导入海康SDK 报错 DllNotFoundException: PlayCtrl assembly

2.尝试按网上其他的办法(包括使用depengs查看dll依赖等)1.先检查Plugins文件夹中是否存在PlayCtrl文件。3.如果网上查阅的办法都不能解决,请继续往下看。更换低版本的SDK库文件。

weixin_42968584的博客 1126

一种通过Visual Studio,C#语言的Windows版本与低功耗蓝牙通信的源码

以前都是用手机APP和蓝牙设备通信,现在在一个项目中需要更改为用电脑端上位机与蓝牙通讯的需求,在此记录自己走过的坑和积攒的经验。

a876106354的博客 1099

详解电路设计中的RC电路

​ 一、什么是RC电路 RC电路是指由电阻R和电容C组成的电路,它是脉冲产生和整形电路中常用到 的电路。 常见的RC充、放电电路、RC积分电路合RC微分电路接下来详细讲解。 二、RC充、放电电路 RC充、放电电路如下图所示,下面通过充电和放电两个过程来分析此电路。 ​RC充、放电电路图 (1)RC充电电路 RC充电电路图如下图(a)所示 RC充电电路图及充电曲线图 ​由上图分析: 将上图a中开关S置于“1”处,电源E开始通过电阻R对电容C充电,由于刚开始充电时电容两端没有..

IT xiaobai 4万+

利用Arcgis发布wmts服务

使用发布 GIS 服务连接连接到 ArcGIS Server 站点后,可以将各种 GIS 资源(如地图文档、数据库以及服务定义)发布到服务器上。此外,还可以添加、删除、启动和停止服务。使用管理 GIS 服务器连接到 ArcGIS Server 站点后,可以编辑各种服务器属性,例如配置存储位置、集群配置、参与到该站点中的计算机列表以及管理站点的数据存储。通过使用 GIS 服务连接建立连接后,可以查看并使用发布到该站点的服务。但不能编辑服务器或服务属性、发布服务,也不能添加、删除、启动、停止或暂停服务。

ghgfsasxda的博客 2392

蓝牙小试牛刀之蓝牙4.0BLE开发

首先简单介绍一下蓝牙4.0 BLE开发 BLE全名为Bluetooth Low Energy 顾名思义,蓝牙低能耗。 蓝牙4.0及以上称之为BLE,而4.0以下则称之为传统蓝牙。那么二者有什么区别呢? BLE与传统蓝牙相比四大特点: 1、低能耗,蓝牙4.0设备与周围设备交流时,其峰值能耗仅为传统蓝牙设备的一半 2、传输距离远,100米以上

lzq520210的博客 1127

macOS 12.7.6部署Ollama+Dify避坑指南

本文介绍了在macOS 12.7.6系统下部署Ollama和Dify的详细步骤及避坑指南。主要内容包括:1)关闭系统完整性保护(SIP)以允许修改系统目录;2)安装特定版本的Docker(2.1.0.5)和docker-compose(v2.38.2)以避免兼容性问题;3)配置Ollama服务并下载nomic-embed-text和deepseek-r1:7b模型;4)针对macOS调整Dify的docker配置文件,包括延长超时时间、修改存储路径、增加资源限制等关键设置。文中提供了完整的命令操作步骤和配置

Hi20240217的博客 3101

c# 低功耗蓝牙_c# – Windows 10 API中的蓝牙低能耗广告数据限制[已关闭]

如果我使用以下代码检查IBuffer成员数据的长度:var myDataSection = new BluetoothLEAdvertisementDataSection();Debug.WriteLine($"Data Capacity: {myDataSection.Data.Capacity}"); //Looks like SO needs to update for C# 6.0我得到了...

weixin_32641817的博客 507

OpenAI,从推出更强大的Sora 2模型展开探索与未来发展前景+部署方法大全+文末邀请码*12

摘要 OpenAI推出的Sora 2是第二代AI视频生成模型,在多模态内容生成领域实现重大突破。文末足足有12个邀请码,速来速享!!!

aqfcca的博客 2248

筑牢上线前安全防线:安全运维服务中的检测实践与深化

在日益严峻的网络安全形势下,将漏洞扫描、渗透测试和基线核查有机结合的上线前安全检测,是保障信息系统安全、稳定、合规上线的基石。通过专业、严谨、协作的检测实践,乙方安全团队能够有效协助甲方在系统生命周期的起点就构筑起坚固的安全防线,为业务的顺利开展和用户的信任保驾护航,真正实现“安全赋能业务”的价值。这道“守门人”的职责,是数字时代企业稳健前行的不可或缺的保障。专业的安全服务提供商(乙方)需要与甲方(系统所有者/运营方)建立紧密、透明、协作的伙伴关系,实现风险的闭环管理,甚至推动甲方安全能力的长期提升。

huluang的专栏 183

使用C#编写一个用于接收Amazfit Balance智能手表的心率广播数据的程序

使用C#编写一个用于接收Amazfit Balance智能手表的心率广播数据的程序

寒冰屋的专栏 349

车载以太网网络测试-27【SOME/IP-SD简述】

SOME/IP-SD协议是基于IP的可扩展面向服务中间件中的服务发现协议,是汽车电子和嵌入式系统中实现动态服务发现与通信的核心组件。该协议规范详细说明了协议SOME/IP服务发现(SOME/IP-SD)的格式、消息序列和语义。本文将对SOME/IP-SD协议进行详细介绍。

车载网络测试工程师的博客 1956
上一篇: 二维装箱
下一篇: C# WiFi多线程收发报文
code_long
博客等级 码龄16年 35粉丝 19原创
评论 79
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值