引用此js文件就行了

 // 使用方式import bluetooth from './bluetooth.js';// 使用设备名称匹配蓝牙设备bluetooth.name = 'xxxx';wx.showLoading({title: '开门中...',mask : true,});await bluetooth.openBluetoothAdapter();

蓝牙设备匹配具体实现

/* eslint-disable no-underscore-dangle */
function inArray(arr, key, val) {for (let i = 0; i < arr.length; i++) {if (arr[i][key] === val) {return i;}}return -1;
}// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {return ('00' + bit.toString(16)).slice(-2);});return hexArr.join('');
}/*** hex转ArrayBuffer*/
function stringToBuffer(arr) {var length = arr.length;var buffer = new ArrayBuffer(length);var dataview = new DataView(buffer);for (let i = 0; i < length; i++) {dataview.setUint8(i, '0x' + arr[i]);// dataview.setUint8(i, arr[i].charAt(i).charCodeAt())}return buffer;
}const bluetooth = {// 引用bluetooth时,获取后台传入的设备名称或者idname             : '',bluetoothDeviceId: '',// 1.初始化蓝牙模块。iOS 上开启主机/从机模式时需分别调用一次,指定对应的 mode:// central主机模式// peripheral从机模式async openBluetoothAdapter() {try {await wx.openBluetoothAdapter();this.startBluetoothDevicesDiscovery();} catch (error) {if (error.errCode === 10001) {wx.showToast({title   : '请打开蓝牙再次尝试开门',icon    : 'none',duration: 1500,});wx.onBluetoothAdapterStateChange((res) => {if (res.available) {this.startBluetoothDevicesDiscovery();}});}}},getBluetoothAdapterState() {wx.getBluetoothAdapterState({success: (res) => {if (res.discovering) {this.onBluetoothDeviceFound();} else if (res.available) {this.startBluetoothDevicesDiscovery();}},});},// 开始搜寻附近的蓝牙外围设备。// 2.此操作比较耗费系统资源,请在搜索并连接到设备后调用 wx.stopBluetoothDevicesDiscovery 方法停止搜索。async startBluetoothDevicesDiscovery() {if (this._discoveryStarted) {return;}this._discoveryStarted = true;await wx.startBluetoothDevicesDiscovery({allowDuplicatesKey: false,// 要搜索的蓝牙设备主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。services          : ['XXXX'],});this.onBluetoothDeviceFound();},//   停止搜寻附近的蓝牙外围设备。//   5.若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。stopBluetoothDevicesDiscovery() {wx.stopBluetoothDevicesDiscovery();},//   3.监听寻找到新设备的事件onBluetoothDeviceFound() {wx.onBluetoothDeviceFound((res) => {res.devices.forEach((device) => {// 设备匹配// 以蓝牙设备服务 uuid进行匹配// if (device.advertisServiceUUIDs.some(uuid => uuid === '000018F0-0000-1000-8000-00805F9B34FB')) {//   this.createBLEConnection(device.deviceId, device.name);// }// 以蓝牙设备 名称进行匹配if (device.name === this.name) {this.createBLEConnection(device.deviceId, device.name);}// 以蓝牙设备id进行匹配(此id在安卓系统为mac地址唯一不变,每台iOS设备获取的设备id都不同,可以让设备厂家暴露设备mac给iOS设备进行匹配)// if (device.deviceId === this.bluetoothDeviceId) {//   this.createBLEConnection(device.deviceId, device.name);// }});});// 计时器this.timer = setTimeout(async() => {await wx.hideLoading();wx.showToast({title   : '开门超时请重试',icon    : 'none',duration: 1500,});this.closeBluetoothAdapter();}, 10 * 1000);},//   连接低功耗蓝牙设备。//   4.createBLEConnection(deviceId, name) {wx.createBLEConnection({deviceId,success: (res) => {this.getBLEDeviceServices(deviceId);},});this.stopBluetoothDevicesDiscovery();},closeBLEConnection() {wx.closeBLEConnection({deviceId: this._deviceId,});},// 6.获取蓝牙设备所有服务(service)。getBLEDeviceServices(deviceId) {wx.getBLEDeviceServices({deviceId,success: (res) => {for (let i = 0; i < res.services.length; i++) {// 匹配设备厂家说明书所给的相应服务uuidif (res.services[i].uuid.includes('XXXX')) {this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);return;}}},});},// 获取蓝牙设备某个服务中所有特征值(characteristic)// 7.getBLEDeviceCharacteristics(deviceId, serviceId) {wx.getBLEDeviceCharacteristics({deviceId,serviceId,success: (res) => {for (let i = 0; i < res.characteristics.length; i++) {let item = res.characteristics[i];if (item.properties.read) {wx.readBLECharacteristicValue({deviceId,serviceId,characteristicId: item.uuid,});}// 匹配设备厂家说明书上相应的可写入服务if (item.uuid.includes('XXXX')) {this._deviceId = deviceId;this._serviceId = serviceId;this._characteristicId = item.uuid;this.writeBLECharacteristicValue();}// if (item.properties.notify || item.properties.indicate) {//   wx.notifyBLECharacteristicValueChange({//     deviceId,//     serviceId,//     characteristicId: item.uuid,//     state           : true,//   });// }}},fail(res) {console.error('getBLEDeviceCharacteristics', res);},});// 操作之前先监听,保证第一时间获取数据// wx.onBLECharacteristicValueChange((characteristic) => {//   const idx = inArray(//     this.data.chs,//     'uuid',//     characteristic.characteristicId,//   )//   const data = {}//   if (idx === -1) {//     data[`chs[${this.data.chs.length}]`] = {//       uuid: characteristic.characteristicId,//       value: ab2hex(characteristic.value),//     }//   } else {//     data[`chs[${idx}]`] = {//       uuid: characteristic.characteristicId,//       value: ab2hex(characteristic.value),//     }//   }// data[`chs[${this.data.chs.length}]`] = {//   uuid: characteristic.characteristicId,//   value: ab2hex(characteristic.value)// }//   this.setData(data)// })},// 向低功耗蓝牙设备特征值中写入二进制数据。// 注意:必须设备的特征值支持 write 才可以成功调用。// 8async writeBLECharacteristicValue() {// 蓝牙写入指令// 此为示例const arr = ['fe', '12','88','55','11'];const buffer = stringToBuffer(arr);try {await wx.writeBLECharacteristicValue({// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接deviceId        : this._deviceId,// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取serviceId       : this._serviceId,// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取characteristicId: this._characteristicId,value           : buffer,});// 关闭之前调用的 showLoadingawait wx.hideLoading();wx.showToast({title: '开门成功',icon : 'none',});// 开门成功清除定时器;clearTimeout(this.timer);} catch (error) {console.log(`error`, error);wx.showToast({title: '开门失败请重试',icon : 'none',});}this.closeBluetoothAdapter();},closeBluetoothAdapter() {wx.closeBluetoothAdapter();this._discoveryStarted = false;},
};export default bluetooth;

微信小程序-蓝牙设备连接-蓝牙开门相关推荐

  1. 微信小程序自动连接蓝牙电子秤

    不同品牌的称,只需要打印下方函数返回值,根据自己需要做处理就可以了. wx.onBLECharacteristicValueChange(function (res) {let receiverTex ...

  2. 微信小程序同时连接两台蓝牙设备

    微信小程序同时连接两台蓝牙设备 自己测试了微信小程序的蓝牙接口是否可以同时连接两台蓝牙设备并同时接收数据,实践测试发现,可以同时连接多台蓝牙设备但是不可以同时接收数据,监测接收数据的接口 wx.onB ...

  3. 微信小程序连接物联网(三):微信小程序远程遥控宿舍开门 基于NodeMCU通过MQTT协议连接阿里云物联网平台

    索引 这是用微信小程序遥控开门的系列文章,具体微信小程序连接物联网的代码在第三章提及. 微信小程序连接物联网(一):初始化ESP8266 NodeMCU 微信小程序连接物联网(二):NodeMCU L ...

  4. 微信小程序与低功耗蓝牙通信-接受硬件端发送来的数据(四)

    接受数据只要 wx.notifyBLECharacteristicValueChange监听器打开, wx.onBLECharacteristicValueChange是接受数据的函数. 数据接收到后 ...

  5. 【微信小程序控制硬件15 】 开源一个微信小程序,支持蓝牙快速配网+WiFi双控制ESP32-C3应用示范;(附带Demo)

    文章目录 一.前言 二. Blufi乐鑫自研的蓝牙配网协议 ESP32 配网流程 流程图 三.相关代码 3.1 蓝牙快速配网 3.2 蓝牙本地控制 2.3 外设驱动 3.1 蓝牙搜索 3.2 蓝牙服务 ...

  6. 乐鑫Esp32学习之旅 19 重磅开源,如何在微信小程序上ble蓝牙配网esp32,blufi的那些事!

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. 爬坑学习新旅程,虚拟机搭建esp32开发环境,打印 " ...

  7. 微信小程序直连蓝牙实现控制继电器及串口调试功能--全系统开源工程

    微信小程序直连蓝牙硬件设备,设备控制继电器,灯等设备,同时实现蓝牙串口调试助手等功能,设备能够输出微信小程序发出的蓝牙数据,可为工程师在手机上实现设备串口调试功能,当工程师去现场调试设备,没有带电脑, ...

  8. 微信小程序http连接访问解决方案

    微信小程序http连接访问解决方案 参考文章: (1)微信小程序http连接访问解决方案 (2)https://www.cnblogs.com/masterchd/p/9895636.html 备忘一 ...

  9. 微信小程序网络连接失败

    微信小程序网络连接失败 安装微信开发者工具,一直提示网络连接失败,在网上查找几乎都是这种帖子(连接失败),没有一个解决的,注册表删了,重装软件,重启电脑,电脑的代理也改了,还是没有用. 最后解决办法是 ...

  10. 微信小程序 Node连接本地MYSQL

    微信小程序 Node连接本地MYSQL 搭建Node环境 小程序中js发送请求 原博客基础上略微修改 搭建Node环境 前提:MYSQL已经创建好数据库 + 安装好node 项目中,新建一个文件ser ...

最新文章

  1. 递归函数 集合 列表 元组
  2. Vivado中ASYNC_REG命令讲解
  3. Big Data, Hadoop and StreamInsight™
  4. 文档类CDocument、子框架类CFrameWnd及视图类CView的关系及如何相互调用
  5. python class函数报错_Python 的函数是第一类 First-Class 对象
  6. 关于Eclipse中复制粘贴一个项目后的操作
  7. 使用 SASS Mixin 编写 clean code
  8. matlab slider不可移动,GUI界面能运行,但是_slider不能用,不能控制波长
  9. 什么是IPsec协议
  10. java读取yaml数据_Java类读取Yaml内罐
  11. (转)Putty server refused our key的三种原因和解决方法
  12. # JDK7+ MethodHandle
  13. 基于双二阶广义积分器(DSOGI)的软件锁相环需求的根源及s域仿真
  14. 端口号从8080变成8081,cmd关闭8080端口
  15. NYOJ 19 擅长排列的小名 next_permutation()的用法
  16. 累死你的不是工作,而是工作方式
  17. uni-app跳转连接到QQ
  18. 计算机flash操作,会考计算机word、Excel、Photoshop、Flash的操作方法(之二)
  19. 可编程计数器/定时器8253和8254
  20. AcWing 3531. 哈夫曼树(哈夫曼树)

热门文章

  1. 网易2020校招数据分析方向正式批笔试题 解析
  2. Dlib库实现人脸关键点检测(Opencv实现)
  3. html刷浏览量,批量刷网页点击量工具
  4. 微信公号开发实战之智能翻译
  5. wps word设置级别多级目录标题
  6. 计算机ps计划,ps教学计划
  7. 苏州真不能成为一线城市?
  8. android禁止屏幕自动旋转_在android程序中禁止屏幕旋转和避免重启Activity
  9. 关于php的梗儿_php是世界上最好的语言是什么梗?
  10. ftp服务器端口修改,FTP端口:默认为21端口