Win10 平台C#与低功耗蓝牙BLE设备通信案例

前几天接了个单,客户要在win10电脑上做个工具软件,跟蓝牙锁设备相互通信。一开始以为是普通的蓝牙设备呢,收到客户寄来的测试设备,才发现是低功耗BLE蓝牙设备。

PS:当时我研发用的台式机是没有蓝牙设备的,客户给寄了个USB的蓝牙适配器,插上后,系统自动安装了驱动,但是在设备发现页面,一直无法发现附近的设备。后来联系到厂家,装了他们的专用驱动就可以了,有遇到类似情况的小伙伴,及得找蓝牙设备厂家要驱动试下。

下面进入正题,PC上与BLE通信的案例真不多,一开始打算用JavaFX做的呢,后来发现Java在PC上根本没有现成库可以支持与BLE设备通信,果断放弃,改用C#。

一番查找后,发现也没能找到整套通信案例。就在快要放弃的时候,发现一位博主大神的文章,终于找到了解决问题的方向,感谢互联网的无私分享精神。

传送门:https://blog.csdn.net/code_long/article/details/105636398?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control

在实际研发中,发现上面这位博主的代码有些地方还是有点问题的,本文将一一化解,另外博主最后提到的发现设备慢的问题,本文也一并解决了,目前发现附近设备的时间缩短至3秒左右。

1、有朋友留言说BluetoothAdapter类无法识别问题:

      本人当时也遇到这问题了,后来发现是文中提到的windows.winmd这个依赖库的问题,本人一开始是从网上下的这个库,里面其他类包括函数都没问题,就没有BluetoothAdapter这个类。后来发现在自己电脑里就能找到这个库,根本不用去网上下载。

      文件地址:C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17763.0,我的电脑是在这个文件夹下,由于Windows版本不同大家路径可能稍有差别,但注意必须是win10系统,win7系统应该不支持BLE通信,win8的就没试过了。

2、

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

在这段代码中,我这边运行的时候是获取不到服务列表的,所以改成如下模式:

this.CurrentDevice.GetGattServicesAsync().Completed = async (asyncInfo, asyncStatus) =>
            {
                if (asyncStatus == AsyncStatus.Completed)
                {
                    var services = asyncInfo.GetResults().Services;
                    this.MessAgeChanged(MsgType.NotifyTxt, "GattServices size="+ services.Count);
                    foreach (GattDeviceService ser in services)
                    {
                        FindCharacteristic(ser);
                    }
                    this.MessAgeChanged(MsgType.NotifyTxt, "获取特码收集完毕" );
                    
                }
            };

在获取特征码的时候,也是同样问题,这里就不赘述了,文末会送上整套代码

3、附近设备发现慢的问题(大概需要30秒左右才能发现附近设备),经过改良后,现在只需3秒左右即可发现附近设备,核心代码如下:

        /// <summary>
        /// 搜索蓝牙设备
        /// </summary>
        public void StartBleDeviceWatcher()
        {
            watcher = new BluetoothLEAdvertisementWatcher();

            watcher.ScanningMode = BluetoothLEScanningMode.Active;

            // only activate the watcher when we're recieving values >= -80
            watcher.SignalStrengthFilter.InRangeThresholdInDBm = -80;

            // stop watching if the value drops below -90 (user walked away)
            watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -90;

            // register callback for when we see an advertisements
            watcher.Received += OnAdvertisementReceived;

            // wait 5 seconds to make sure the device is really out of range
            watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
            watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);

            // starting watching for advertisements
            watcher.Start();
            string msg = "自动发现设备中..";

            this.MessAgeChanged(MsgType.NotifyTxt, msg);
        }
        private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
         BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).Completed = async (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        if (asyncInfo.GetResults() == null)
                        {
                            this.MessAgeChanged(MsgType.NotifyTxt, "没有得到结果集");
                        }
                        else
                        {
                            BluetoothLEDevice currentDevice = asyncInfo.GetResults();

                            Boolean contain = false;
                            foreach (BluetoothLEDevice device in DeviceList)//过滤重复的设备
                            {
                                if (device.DeviceId == currentDevice.DeviceId)
                                {
                                    contain = true;
                                }
                            }
                            if (!contain)
                            {
                                byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
                                Array.Reverse(_Bytes1);

                                this.DeviceList.Add(currentDevice);
                                this.MessAgeChanged(MsgType.NotifyTxt, "发现设备:"+ currentDevice.Name+"  address:"+ BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower());
                                this.DeviceWatcherChanged(MsgType.BleDevice, currentDevice);
                            }
                        }

                    }
                };
        }

软件运行界面截图如下:

整套代码下载链接:https://download.csdn.net/download/shengfakun1234/13617970

  • 5
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 31
    评论
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锦瑟-华年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值