草庐IT

微信小程序蓝牙功能全套开发流程介绍

鱿鱼丝2号 2025-04-07 原文

一、开发流程

  1. 流程图:流程图作者原文章

  1. 实现模块顺序

1.1初始化蓝牙模块(打开蓝牙适配器)

初次加载,自动获取获取系统信息,检查蓝牙适配器是否可用

初始化蓝牙,提示打开GPS和蓝牙,开始自动搜索蓝牙设备

1.2搜索周围蓝牙

开始搜索蓝牙设备,定时1s获取搜索到的设备

把搜索到的设备保存在一个数组内,渲染在页面

1.3监听搜索设备

监听5s后停止搜索,并把新设备push到数组进行渲染

显示设备名称和连接按钮

1.4连接目标设备

点击连接按钮创建连接,获取设备信息

连接成功停止搜索,获取已连接蓝牙的服务

1.5获取服务、特征值

连接成功获取蓝牙设备服务和特征值(是否能读写)

1.6开启notify,监听特征值变化

开启监听功能,发送指令后接收设备响应的数据

1.7发送指令、读写数据

设备特征值中写入数据,必须设备的特征支持 write

ArrayBuffer转16进制字符串

1.8断开连接

清空设备名、设备id,关闭蓝牙模块

二、实现模块代码

  1. 初始化蓝牙模块(打开蓝牙适配器)

openBluetoothAdapter() {
        let that = this;
        uni.openBluetoothAdapter({ //初始化蓝牙模块
          success(res) {
            console.log(res, '初始化蓝牙成功');
            uni.onBluetoothAdapterStateChange((res) => { // 监听蓝牙适配器状态变化
              if (!res.available) {
                uni.showModal({
                  title: '温馨提示',
                  content: '蓝牙适配器不可用,请重新启动',
                  showCancel: false
                });
              }
            });
            that.searchBlue(); //开始搜索
          },
          fail(res) {
            console.log(res, '初始化蓝牙失败');
            uni.showToast({
              title: '请检查手机蓝牙是否打开',
              icon: 'none'
            });
          }
        });
      },
  1. 开始搜索周围蓝牙

searchBlue() {
        let that = this;
        uni.startBluetoothDevicesDiscovery({
          // services: [],
          success: (res) => {
            console.log(res, "开始搜索设备");
            uni.showLoading({
              title: '正在搜索设备'
            });
            that.getBluetoothDevices();
          },
          fail: (res) => {
            console.log(res, '搜索失败');
            uni.showToast({
              title: '搜索蓝牙设备失败!',
              icon: 'none'
            });
          }
        });
      },
  1. 获取搜索到的设备

getBluetoothDevices() {
        let that = this;
        setTimeout(() => {
          uni.getBluetoothDevices({ // 获取搜索到的设备
            success: (res) => {
              console.log(res, "搜索到的设备");
              let devicesListArr = [];
              if (res.devices.length > 0) {
                uni.hideLoading(res.devices);
                res.devices.forEach((device) => {
                  if (!device.name && !device.localName) {
                    return;
                  } else if (device.name.substring(0, 2) == 'AA') {
                    devicesListArr.push(device);
                    that.devicesList = devicesListArr;
                    that.isHideList = true;
                    that.watchBluetoothFound(); // 监听搜索到的新设备
                  } else {
                    return
                  }
                });
              } else {
                uni.hideLoading();
                uni.showModal({
                  title: '温馨提示',
                  content: '无法搜索到蓝牙设备,请重试',
                  showCancel: false
                });
                uni.closeBluetoothAdapter({ //关闭蓝牙模块
                  success: (res) => {
                    console.log(res, "关闭蓝牙模块");
                  }
                });
              }
            }
          });
        }, 2000);
      },
  1. 监听搜索设备

watchBluetoothFound() {
        let that = this;
        uni.onBluetoothDeviceFound(function(res) { // 监听搜索到的新设备
          if (String(res.devices.name).substring(0, 2) == 'AA') {
            devicesListArr.push(res.devices);
            that.devicesList = devicesListArr;
            console.log(res.devices, "监听新设备");
          }
        })
      },
  1. 连接目标设备

createBLEConnection(e) {
        let that = this;
        let deviceId = e.currentTarget.dataset.id;
        let connectName = e.currentTarget.dataset.name;
        console.log("正在连接" + connectName);
        uni.showLoading({
          title: '连接中...'
        });
        uni.createBLEConnection({
          deviceId,
          success: (res) => {
            uni.hideLoading();
            that.stopBluetoothDevicesDiscovery(); // 连接成功,停止搜索
            console.log(res, "连接成功");
            if (res.errCode == 0) {
              that.deviceId = deviceId;
              that.connectName = connectName;
              that.isHideConnect = true;
              that.getBLEDeviceServices(deviceId); // 获取服务
            } else if (res.errCode == 10012) {
              uni.showToast({
                title: '连接超时,请重试!'
              });
            }
          },
          fail(error) {
            uni.hideLoading();
            console.log(error, '连接失败');
            uni.showToast({
              title: '连接失败!'
            });
          }
        });
      },
  1. 获取设备所有服务

getBLEDeviceServices(deviceId) {
        let that = this;
        // let serviceId;
        uni.getBLEDeviceServices({
          deviceId,
          success: (res) => {
            console.log(res.services, "获取设备服务");
            for (let i = 0; i < res.services.length; i++) {
              let isPrimary = res.services[i].isPrimary
              let uuid = res.services[i].uuid.substring(4, 8) == 'FE60' 
              if (isPrimary && uuid) {
                this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
                return
              }
            }
          }
        });
      },
  1. 获取特征值

getBLEDeviceCharacteristics(deviceId, serviceId) {
        let that = this;
        uni.getBLEDeviceCharacteristics({ 
          deviceId,
          serviceId,
          success: (res) => {
            console.log(res.characteristics, '获取特征值成功')
            let characteristicId = res.characteristics[0].uuid;
            let writeNews = {
              deviceId,
              serviceId,
              characteristicId
            };
            that.writeNews = writeNews;
            let notifyId = res.characteristics[1].uuid;
            that.notifyBLECharacteristicValueChange(serviceId, notifyId);
          },
          fail(err) {
            console.log(err, "获取失败");
          }
        });
      },
  1. 启用监听特征值变化

notifyBLECharacteristicValueChange(serviceId, characteristicId) {
        let that = this;
        uni.notifyBLECharacteristicValueChange({ // 启用监听设备特征值变化 
          type: 'notification',
          state: true, // 启用 notify 功能
          deviceId: that.writeNews.deviceId,
          serviceId,
          characteristicId,
          success(res) {
            console.log(res, '启用监听成功');
            that.onBLECharacteristicValueChange()
          },
          fail: (err) => {
            console.log(err, "启用监听失败");
          }
        });
      },
  1. 监听特征值变化

onBLECharacteristicValueChange() {
        let that = this;
        uni.onBLECharacteristicValueChange(res => {
          console.log(res, '监听变化成功');
          let resHex = that.ab2hex(res.value)
          console.log('从机响应的数据:', resHex)
        })
      },
  1. 发送、读取数据

writeBLECharacteristicValue(order) { // 向蓝牙设备发送一个0x00的16进制数据
        let that = this;
        let msg = order;
        let buffer = new ArrayBuffer(msg.length / 2); // 定义 buffer 长度
        let dataView = new DataView(buffer); // 从二进制ArrayBuffer对象中读写多种数值类型
        let ind = 0;
        for (var i = 0, len = msg.length; i < len; i += 2) {
          let code = parseInt(msg.substr(i, 2), 16)
          dataView.setUint8(ind, code)
          ind++
        }
        console.log('主机写入的指令:', that.ab2hex(buffer));
        uni.writeBLECharacteristicValue({
          deviceId: that.writeNews.deviceId,
          serviceId: that.writeNews.serviceId,
          characteristicId: that.writeNews.characteristicId,
          value: buffer,
          writeType: 'writeNoResponse',
          success: (res) => {
            console.log(res, '写入数据成功');
            that.onBLECharacteristicValueChange()
          },
          fail: (err) => {
            console.log(err);
          }
        })
      },
  1. 断开连接

closeBLEConnection() {
        let that = this;
        console.log(that);
        uni.closeBLEConnection({
          deviceId: this.deviceId,
          success: () => {
            uni.showToast({
              title: '已断开连接'
            });
            that.deviceId = '';
            that.connectName = '';
            that.isHideConnect = false;
          }
        });
        that.closeBluetoothAdapter();
      },
  1. 关闭蓝牙模块

closeBluetoothAdapter() {
        let that = this;
        uni.closeBluetoothAdapter({
          success: (res) => {
            console.log(res);
            that.devicesList = [];
            that.isHideList = false;
            that.isHideConnect = false;
          }
        });
      },
  1. 停止搜索设备

stopBluetoothDevicesDiscovery() {
        uni.stopBluetoothDevicesDiscovery({
          success(res) {
            console.log(res);
          }
        });
      },
  1. ArrayBuffer转16进制字符串

ab2hex(buffer) {
        var hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function(bit) {
            return ('00' + bit.toString(16)).slice(-2);
          });
        return hexArr.join('');
      },

三、遇到的问题以及解决

问题1:onBLECharacteristicValueChange监听不到响应数据?

解决方法:

1、给onBLECharacteristicValueChange添加延时器;

2、给notifyBLECharacteristicValueChange添加type: 'notification';

3、给writeBLECharacteristicValue添加 writeType: 'writeNoResponse';

4、更换手机设备:Android、IOS设备;

5、查看特征值:read、notify、write、writeNoResponse;

6、分包发送:蓝牙BLE最大支持20个字节发送,因此超过20个字节需要分包发送;

7、遵循硬件文档:使用指定服务,写入、接收分别使用的特征值(成功解决);

有关微信小程序蓝牙功能全套开发流程介绍的更多相关文章

  1. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  2. Ruby Sinatra 配置用于生产和开发 - 2

    我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm

  3. ruby - 是否可以覆盖 gemfile 进行本地开发? - 2

    我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI

  4. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  5. ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型 - 2

    我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain

  6. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  7. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  8. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  9. Unity 热更新技术 | (三) Lua语言基本介绍及下载安装 - 2

    ?博客主页:https://xiaoy.blog.csdn.net?本文由呆呆敲代码的小Y原创,首发于CSDN??学习专栏推荐:Unity系统学习专栏?游戏制作专栏推荐:游戏制作?Unity实战100例专栏推荐:Unity实战100例教程?欢迎点赞?收藏⭐留言?如有错误敬请指正!?未来很长,值得我们全力奔赴更美好的生活✨------------------❤️分割线❤️-------------------------

  10. 微信小程序通过字典表匹配对应数据 - 2

    前言一般来说,前端根据后台返回code码展示对应内容只需要在前台判断code值展示对应的内容即可,但要是匹配的code码比较多或者多个页面用到时,为了便于后期维护,后台就会使用字典表让前端匹配,下面我将在微信小程序中通过wxs的方法实现这个操作。为什么要使用wxs?{{method(a,b)}}可以看到,上述代码是一个调用方法传值的操作,在vue中很常见,多用于数据之间的转换,但由于微信小程序诸多限制的原因,你并不能优雅的这样操作,可能有人会说,为什么不用if判断实现呢?但是if判断的局限性在于如果存在数据量过大时,大量重复性操作和if判断会让你的代码显得异常冗余。wxswxs相当于是一个独立

随机推荐