1、需要使用到的动态库

Bluetooth
Microsoft.Windows.SDK.Contracts

2、需要使用到的命名控件

using System.Threading.Tasks;
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;

3、创建蓝牙设备对象

      public BluetoothTools(){if (deviceWatcher == null){deviceWatcher = new BluetoothLEAdvertisementWatcher();deviceWatcher.ScanningMode = BluetoothLEScanningMode.Active;//扫描模式deviceWatcher.SignalStrengthFilter.InRangeThresholdInDBm = -80;deviceWatcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -90;deviceWatcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);deviceWatcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);deviceWatcher.Received += DeviceWatcher_Received;deviceWatcher.Stopped += DeviceWatcher_Stopped;}}
/// <summary>/// 蓝牙搜索停止时触发事件/// </summary>/// <param name="sender"></param>/// <param name="args"></param>private void DeviceWatcher_Stopped(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementWatcherStoppedEventArgs args){//搜索停止this.DeviceSearchComplete?.Invoke(this.BluetoothList);}/// <summary>/// 扫描到蓝牙设备时处理方法/// </summary>/// <param name="sender"></param>/// <param name="args"></param>private void DeviceWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args){BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress).Completed = async (asyncInfo, asyncStatus) =>{if (asyncStatus == AsyncStatus.Completed){if (asyncInfo.GetResults() != null){BluetoothLEDevice currentDevice = asyncInfo.GetResults();if (currentDevice.Name.ToUpper().StartsWith("FS")){bool state = BluetoothList.Where(x => x.BluetoothDeviceId == currentDevice.DeviceId).ToList().Count > 0;if (!state){BluetoothInfo info = new BluetoothInfo(){BluetoothName = currentDevice.Name,BluetoothDeviceId = currentDevice.DeviceId,BluetoothMac = currentDevice.DeviceId.Split('-')[1]};BluetoothList.Add(info); //添加设备到蓝牙列表DeviceWatcherChanged(info);}}currentDevice.Dispose();//释放掉蓝牙设备}}};}

4、开启蓝牙搜索,并在一定时间后停止蓝牙搜索操作

/// <summary>/// 搜索蓝牙设备/// </summary>public void Searching(){if (SearchingState){return;}this.BluetoothList.Clear();try{deviceWatcher.Start();SearchingState = true;this.ReceivedMessage(MessageType.Info, "蓝牙搜索中...");}catch (Exception ex){this.ReceivedMessage(MessageType.Error, "蓝牙搜索异常:"+ex.Message);return;}long time = Environment.TickCount +1000*5;Task.Factory.StartNew(() =>{while (SearchingState){if (Environment.TickCount > time){if (SearchingState){StopSearching();}}else{Thread.Sleep(50);}}});}/// <summary>/// 停止搜索/// </summary>public void StopSearching(bool isPassive=false){SearchingState = false;this.ReceivedMessage(MessageType.Info, isPassive? "停止蓝牙搜索..." : "主动停止蓝牙搜索...");deviceWatcher.Stop();   }

5、连接指定蓝牙 指定读写特征

  /// <summary>/// 连接蓝牙/// </summary>/// <param name="bluetoothAddress"></param>public async Task ConnectAsync(string mac){if (SearchingState){StopSearching(true);//搜索中停止搜索...}if (IsConnect && mac == CurrentDeviceMAC){this.ReceivedMessage(MessageType.Warning, $"已连接蓝牙:{CurrentDeviceMAC},无需重连!");return;}if (IsConnect){this.ReceivedMessage(MessageType.Info, $"连接新的蓝牙:{mac},主动断开已连接蓝牙:{CurrentDeviceMAC}");CloseConnect();//断开当前的蓝牙连接Thread.Sleep(500);}BluetoothAdapter bluetoothAdapter = await BluetoothAdapter.GetDefaultAsync();if (bluetoothAdapter == null){this.ReceivedMessage(MessageType.Error, "当前机器没有蓝牙模块");return;//没有蓝牙设备}//var itemList = BluetoothList.Where(x => x.BluetoothMac == mac).ToList();//if (itemList.Count < 1)//{//    this.ReceivedMessage(MessageType.Warning, "蓝牙列表中不存在当前蓝牙-请执行搜索蓝牙");//    return;////}//CurrentDevice = await BluetoothLEDevice.FromIdAsync(itemList[0].BluetoothDeviceId);// 修改:不用搜索也可以连接byte[] _Bytes1 = BitConverter.GetBytes(bluetoothAdapter.BluetoothAddress);//ulong转换为byte数组Array.Reverse(_Bytes1);string macAddress = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();string Id = "BluetoothLE#BluetoothLE" + macAddress + "-" + mac;CurrentDevice = await BluetoothLEDevice.FromIdAsync(Id);if (CurrentDevice != null){CurrentDeviceMAC = mac;CurrentDevice.ConnectionStatusChanged += CurrentDevice_ConnectionStatusChanged;//蓝牙状态}else{this.ReceivedMessage(MessageType.Warning, "通过MAC未查询到蓝牙");return;//查询不到蓝牙}CurrentDevice.GetGattServicesAsync().Completed = async (asyncInfo, asyncStatus) =>{if (asyncStatus == AsyncStatus.Completed){var services = asyncInfo.GetResults().Services;foreach (GattDeviceService ser in services){string uid = ser.Uuid.ToString();if (ser.Uuid.ToString().StartsWith("6e400001")){CurrentService = ser;FindCharacteristic();}else{// ser.Dispose();}}if (CurrentService == null){this.ReceivedMessage(MessageType.Error, "未获取蓝牙服务-链接失败");return;}}};}/// <summary>/// 查找读写特征/// </summary>public void FindCharacteristic(){CurrentService.GetCharacteristicsAsync().Completed = async (asyncInfo, asyncStatus) =>{if (asyncStatus == AsyncStatus.Completed){var characteristics = asyncInfo.GetResults().Characteristics;foreach (GattCharacteristic characteristic in characteristics){string uid = characteristic.Uuid.ToString();System.Console.WriteLine(uid);if (characteristic.Uuid.ToString().StartsWith("6e400003")){CurrentNotifyCharacteristic = characteristic;//读取CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;CurrentNotifyCharacteristic.ValueChanged += CurrentNotifyCharacteristic_ValueChanged;try{await CurrentNotifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);}catch (Exception ex){this.ReceivedMessage(MessageType.Error, "设置蓝牙读取特征Notify异常:" + ex.Message);return;}}else if (characteristic.Uuid.ToString().StartsWith("6e400002")){CurrentWriteCharacteristic = characteristic;//写入}}if (CurrentNotifyCharacteristic == null || CurrentWriteCharacteristic == null){this.ReceivedMessage(MessageType.Warning, "未查询到读或写特征码-断开蓝牙");this.CloseConnect();}}};}/// <summary>/// 蓝牙状态改变触发事件/// </summary>/// <param name="sender"></param>/// <param name="args"></param>private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args){if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected){this.IsConnect = false;if (CurrentDevice != null){CurrentDevice.ConnectionStatusChanged -= CurrentDevice_ConnectionStatusChanged;this.CloseConnect();CurrentDevice = null;}this.DeviceConnect(2, $"蓝牙:{CurrentDeviceMAC}已断开");CurrentDeviceMAC = null;}else{this.IsConnect = true;this.DeviceConnect(1, $"蓝牙:{CurrentDeviceMAC}已连接");//保存蓝牙配置foreach (BluetoothInfo item in BluetoothList){if (item.BluetoothMac == CurrentDeviceMAC){Globals.systemConfig.bluetooth = new BluetoothInfo(){BluetoothMac =item.BluetoothMac,BluetoothDeviceId=item.BluetoothDeviceId,BluetoothName=item.BluetoothName};Globals.SaveConfig();break;}}}}/// <summary>/// 读特征接收蓝牙数据事件/// </summary>/// <param name="sender"></param>/// <param name="args"></param>private void CurrentNotifyCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args){byte[] data;CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);string str = BitConverter.ToString(data);OnRev?.Invoke(this, new BleEventArgs(data));}

5、关闭蓝牙连接

 /// <summary>/// 关闭蓝牙连接/// </summary>public void CloseConnect(){//ReceivedMessage(MsgType.WarningMsg, $"正在断开蓝牙:{CurrentDeviceMAC}...");CurrentService?.Dispose();CurrentDevice?.Dispose();if (CurrentNotifyCharacteristic != null){CurrentNotifyCharacteristic.ValueChanged -= CurrentNotifyCharacteristic_ValueChanged;}CurrentService = null;CurrentWriteCharacteristic = null;CurrentNotifyCharacteristic = null;//if (CurrentDevice != null)//{//    CurrentDevice.ConnectionStatusChanged -= CurrentDevice_ConnectionStatusChanged;//}// CurrentDevice = null;}

6、通过写特征向蓝牙发送数据

/// <summary>/// 发送数据接口/// </summary>/// <param name="characteristic"></param>/// <param name="data"></param>/// <returns></returns>public async Task<bool> Write(byte[] data){if (CurrentWriteCharacteristic == null) { return false; }int count = 50;int len = count;try{for (int i = 0; i < data.Length; i += count){if (i + count > data.Length){len = data.Length - i;}byte[] b1 = new byte[len];Array.Copy(data, i, b1, 0, len);GattCommunicationStatus status = await CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(b1), GattWriteOption.WriteWithoutResponse);if (status != GattCommunicationStatus.Success) { return false; }else{Thread.Sleep(1);}}return true;}catch (Exception ex){this.ReceivedMessage(MessageType.Error,$"发送异常:{ex.Message}");return false;}}

windows 蓝牙程序开发 ble低功耗蓝牙相关推荐

  1. 22_微信小程序开发-BLE低功耗蓝牙开发-源码

    我没想到很多同学都在私信我,问我要这个 iBLETool 的源码,是我没考虑到的.其实最开始没有把源码分享出来,主要的原因是这个项目是我自己拿来练手的,有很多地方考虑不完善,怕误导了各位同学!现在很多 ...

  2. 13.6.3 程序案例:BLE低功耗蓝牙调试助手

    13.6.3 程序案例:BLE低功耗蓝牙调试助手 (配套代码CH13-02) (1) mainwindow.cpp文件代码 #include "mainwindow.h" #inc ...

  3. Qt低功耗蓝牙系列一(什么是低功耗蓝牙开发,低功耗蓝牙的通信机制原理)

    文章目录 前言 Android 蓝牙 BLE 低功耗蓝牙协议栈简介 蓝牙的选用 BLE 低功耗蓝牙模块具体应用场景 蓝牙灯控方案 BLE 蓝牙智能锁方案 蓝牙 MAC 地址扫描打印解决方案 蓝牙 Me ...

  4. 谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受

    谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受 谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受,注明下时间:2012-10-17写的博客,后期更新的也注明了时间 ...

  5. 开发android蓝牙4.0 BLE低功耗应用的感受

    文章转自: http://www.cnblogs.com/zdz8207/archive/2012/10/17/bluetooth_ble_android.html 谈谈几个月以来开发android蓝 ...

  6. Android 8.0 BLE 低功耗蓝牙开发记录

    Android 8.0 BLE 低功耗蓝牙开发记录(1-3)--------------(权限申请篇未完待续) 目的:开源博客,希望大家一起修改博客错误地方,共同完善并会鸣谢提供意见的朋友.为大家提供 ...

  7. android 连接蓝牙电子秤_电子秤蓝牙双模通讯Android低功耗蓝牙(蓝牙4.0)BLE开发(上)...

    电子秤蓝牙双模通讯Android低功耗蓝牙(蓝牙4.0)BLE开发(上) 前段时间,公司项目用到了手机APP和蓝牙设备的通讯开发,这里也正好对低功耗蓝牙(蓝牙4.0及以后标准)的开发,做一个总结. 蓝 ...

  8. Android BLE低功耗蓝牙开发

    啦啦啦在上一个项目中有用到BLE低功耗蓝牙开发,当时baidu google了很多资料,但大多数都是千篇一律,英文文档我这种渣渣又看不懂...总之刚开始查的很痛苦.所以要把自己的踩坑之路写下来记录下, ...

  9. ble 低功耗蓝牙开发学习 嵌入式交流学习

    ble 低功耗蓝牙开发学习 嵌入式交流学习 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 这篇文章教你学会低功耗蓝牙开发,从0到深入,适合自学的学生.初级工程师 前言 随着疫情爆发 ...

最新文章

  1. [CLR via C#]25. 线程基础
  2. 26.使用ajaxSetup()方法设置全局Ajax默认选项
  3. lisp不是函授型语言_【神奇的函数式编程语言的独特功能】Lisp 的运行期修改、编译代码,并替换当前运行版本的试验...
  4. 移动开发者选项手机如何打开真机调试模式
  5. js引用最外部的js中的文本信息
  6. PHP mysql数据迁移,如何自动化PHP/MySQL应用程序的迁移(架构和数据)
  7. 如何从程序员转型为项目经理
  8. 荣耀play3 鸿蒙,荣耀play系列跳过2直接上3代,999元的配置还能愉快play吗?
  9. 防止easyui的DataGride莫名其妙的选中最后一行或删除后编辑信息提示已有选中项的bug...
  10. 这14个Java核心并发容器,Java高手和低手的区别点
  11. react脚手架构建工程
  12. 【spring】spring源码搭建
  13. 使用wsdl2java编写webservice客户端
  14. 留言列表模板HTML代码
  15. 什么是Monitor?
  16. 四色定理已利用计算机证明,四色定理的一证明过程
  17. linux 改变输出端口,linux – 更改ssh端口后的Fail2ban设置
  18. spider-admin-pro 一个集爬虫Scrapy+Scrapyd爬虫项目查看 和 爬虫任务定时调度的可视化管理工具
  19. 通信教程 | USB接口、标准和基础原理
  20. java商城后台图片上传功能_淘淘商城图片上传功能的实现

热门文章

  1. element表格tooltip内容换行展示(本人第一次写帖子效果图在最后如果是各位想要的效果请点个赞,写的不好的地方也可以指导一下万分感谢)
  2. 央行昨天承认增发了43万亿人民币
  3. dreamweaver作业静态HTML网页设计——家乡海南旅游网站
  4. Linux驱动学习(一):什么是Linux驱动
  5. one piece_娜美_01
  6. 朝花夕拾 - 2023 精神错乱记录
  7. FCN..............
  8. 贪心算法 背包问题 java_贪心算法解背包问题
  9. Python - 知识整体框架 (思维导图)
  10. 入门前端-《JavaScript 语言入门教程-实例对象和New对象》