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

这篇具有很好参考价值的文章主要介绍了微信小程序蓝牙功能全套开发流程介绍。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、开发流程

  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、遵循硬件文档:使用指定服务,写入、接收分别使用的特征值(成功解决);文章来源地址https://www.toymoban.com/news/detail-482615.html

到了这里,关于微信小程序蓝牙功能全套开发流程介绍的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序蓝牙授权完整流程

            1.1 authorize:                 提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。更多用法详见 用户授权。

    2024年04月27日
    浏览(38)
  • 微信小程序——实现蓝牙设备搜索及连接功能

    ✅作者简介:2022年 博客新星 第八 。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏:微信小程序学习分享 ✨特色专栏:国学周更-心性养成之路 🥭本文内容:微信小程序——实

    2024年02月08日
    浏览(37)
  • 微信小程序:BLE蓝牙开发

    一、添加蓝牙权限: 1.添加蓝牙权限(工程/app.json): 二、实现扫描/连接/接收BLE设备数据: 1.实现BLE蓝牙设备扫描: 2.实现连接设备/接收数据: 3.调用例子:

    2024年02月12日
    浏览(60)
  • 微信小程序低功耗蓝牙BLE快速开发js

    目的: 1、为了能三分钟快速开发BLE模块,特此做一个笔记,按照笔记的顺序开发,能够简单、快速、规范。 2、如果以后觉得有必要改动的地方就在这里更改。 3、主要是记录BLE连接的步骤。 https://note.youdao.com/ynoteshare/index.html?id=d662c9c1c58121ec28901d78d9aa5e80 比较完整的微信小程

    2024年02月10日
    浏览(48)
  • 微信小程序基础功能及技术栈实现介绍

    番茄钟功能 : 前端(Vant Weapp):使用Vant Weapp提供的倒计时组件或者自己开发一个正计时的组件来实现计时功能,同时可以用它的列表、排行榜组件等来展示各科目的学习时间和学习时长排行。 后端(PHP+ThinkPHP6):ThinkPHP6作为一个功能强大的PHP框架,可以方便地处理学习时

    2024年02月11日
    浏览(21)
  • 微信小程序用什么工具开发(微信小程序开发工具介绍)

    有很多人在开发小程序之前都会去了解微信小程序开发工具,想知道微信小程序用什么工具开发。时至今日,随着互联网技术的发展,现在开发微信小程序也能使用多种不同的工具,让我们来了解一下吧。 一、微信开发者工具 这是微信官方提供的微信小程序开发工具,可以

    2024年02月11日
    浏览(33)
  • 微信小程序从开发—到上线的流程讲解

    1.下载微信小程序开发工具:在微信官方文档中进入小程序模块、选择工具-下载、选择稳定版,根据自己的操作系统选择适合的版本。 2.购买云服务器:在阿里云或腾讯云等服务器厂商中,根据自己的需求买一个服务器并进行服务器的一些配置,建议选购的时候选择 Linux宝塔

    2024年02月05日
    浏览(34)
  • 微信小程序 云开发 聊天功能

    。功能要求为:一对一聊天,可以发送文字,图片,语音,文件,视频,含消息列表页。 暑假没事干来写篇博客复盘一下。框架和样式部分就是采用了colorUI 的组件,没啥好说的,这方面我也不会  这是聊天内容部分 浅浅地小讲一下 scroll-into-view string 值应为某子元素id(id不

    2024年02月09日
    浏览(29)
  • 【联机对战】微信小程序联机游戏开发流程详解

    现有一个微信小程序叫中国象棋项目,棋盘类的单机游戏看着有缺少了什么,现在给补上了,加个联机对战的功能,增加了可玩性,对新手来说,实现联机游戏还是有难度的,那要怎么实现的呢,接下来给大家讲一下。 考虑到搭建联机游戏的服务器成本不小,第一个想法是用

    2024年02月04日
    浏览(63)
  • 微信小程序发布上线全流程(注册/开发/上传审核)

    以下是微信小程序发布上线的详细流程: 确认小程序信息:在微信公众平台注册并登录后,进入小程序管理后台,在“开发”-“开发设置”中填写小程序基本信息和配置,包括小程序名称、图标设计、类目选择等。此外,需要在小程序管理后台中配置小程序服务类目和资质

    2024年02月10日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包